Repository: PHPOffice/PhpSpreadsheet Branch: master Commit: a1dacfdf79e4 Files: 3117 Total size: 12.5 MB Directory structure: gitextract_kqtir3pu/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE.md │ ├── PULL_REQUEST_TEMPLATE.md │ ├── dependabot.yml │ ├── stale.yml │ ├── support.yml │ └── workflows/ │ ├── github-pages.yml │ └── main.yml ├── .gitignore ├── .php-cs-fixer.dist.php ├── .phpcs.xml.dist ├── .readthedocs.yaml ├── CHANGELOG.PHPExcel.md ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bin/ │ ├── check-phpdoc-types.php │ ├── generate-document.php │ ├── generate-locales.php │ └── pre-commit ├── composer.json ├── docs/ │ ├── extra/ │ │ ├── extra.css │ │ └── extrajs.js │ ├── faq.md │ ├── index.md │ ├── references/ │ │ ├── features-cross-reference.md │ │ ├── function-list-by-category.md │ │ ├── function-list-by-name-compact.md │ │ └── function-list-by-name.md │ └── topics/ │ ├── Behind the Mask.md │ ├── Excel Anomalies.md │ ├── Looping the Loop.md │ ├── The Dating Game.md │ ├── accessing-cells.md │ ├── architecture.md │ ├── autofilters.md │ ├── calculation-engine.md │ ├── conditional-formatting.md │ ├── creating-spreadsheet.md │ ├── defined-names.md │ ├── file-formats.md │ ├── images/ │ │ └── Behind the Mask/ │ │ └── Stock Portfolio.xlsx │ ├── memory_saving.md │ ├── migration-from-PHPExcel.md │ ├── reading-and-writing-to-file.md │ ├── reading-files.md │ ├── recipes.md │ ├── settings.md │ ├── tables.md │ └── worksheets.md ├── infra/ │ ├── DocumentGenerator.php │ └── LocaleGenerator.php ├── mkdocs.yml ├── phpstan-baseline.neon ├── phpstan.neon.dist ├── phpunit.xml.dist ├── samples/ │ ├── Autofilter/ │ │ ├── 10_Autofilter.php │ │ ├── 10_Autofilter_dynamic_dates.php │ │ ├── 10_Autofilter_selection_1.php │ │ ├── 10_Autofilter_selection_2.php │ │ └── 10_Autofilter_selection_display.php │ ├── Basic/ │ │ ├── 01_Simple.php │ │ ├── 01_Simple_download_ods.php │ │ ├── 01_Simple_download_pdf.php │ │ ├── 01_Simple_download_xls.php │ │ ├── 01_Simple_download_xlsx.php │ │ ├── 02_Types.php │ │ ├── 03_Formulas.php │ │ ├── 04_Printing.php │ │ ├── 05_Feature_demo.php │ │ ├── 05_UnexpectedCharacters.php │ │ ├── 06_Largescale.php │ │ ├── 07_Reader.php │ │ ├── 08_Conditional_formatting.php │ │ ├── 08_Conditional_formatting_2.php │ │ └── 09_Pagebreaks.php │ ├── Basic1/ │ │ ├── 11_Documentsecurity.php │ │ ├── 12_CellProtection.php │ │ ├── 13_Calculation.php │ │ ├── 13_CalculationCyclicFormulae.php │ │ ├── 14_Xls.php │ │ ├── 15_Datavalidation.php │ │ ├── 16_Csv.php │ │ ├── 17_Html.php │ │ ├── 17a_Html.php │ │ ├── 17b_Html.php │ │ ├── 18_Extendedcalculation.php │ │ └── 19_Namedrange.php │ ├── Basic2/ │ │ ├── 20_Read_Excel2003XML.php │ │ ├── 20_Read_Gnumeric.php │ │ ├── 20_Read_Ods.php │ │ ├── 20_Read_Sylk.php │ │ ├── 20_Read_Xls.php │ │ ├── 22_Heavily_formatted.php │ │ ├── 23_Sharedstyles.php │ │ ├── 24_Readfilter.php │ │ ├── 25_In_memory_image.php │ │ ├── 26_Utf8.php │ │ ├── 27_Images_Html_Pdf.php │ │ ├── 27_Images_Xls.php │ │ ├── 27_Images_Xlsx.php │ │ ├── 28_Iterator.php │ │ └── 29_Advanced_value_binder.php │ ├── Basic3/ │ │ ├── 30_Template.php │ │ ├── 30_Templatebiff5.php │ │ ├── 31_Document_properties_write.php │ │ ├── 31_Document_properties_write_xls.php │ │ ├── 37_Page_layout_view.php │ │ ├── 38_Clone_worksheet.php │ │ ├── 39_Dropdown.php │ │ └── data/ │ │ └── continents/ │ │ ├── Africa.txt │ │ ├── Asia.txt │ │ ├── Europe.txt │ │ ├── North America.txt │ │ ├── Oceania.txt │ │ └── South America.txt │ ├── Basic4/ │ │ ├── 40_Duplicate_style.php │ │ ├── 41_Password.php │ │ ├── 42_RichText.php │ │ ├── 42b_RichText.php │ │ ├── 43_Merge_workbooks.php │ │ ├── 44_Worksheet_info.php │ │ ├── 45_Quadratic_equation_solver.php │ │ ├── 46_ReadHtml.php │ │ ├── 47_xlsfill.php │ │ ├── 47_xlsxfill.php │ │ ├── 48_Image_move_size_with_cells.php │ │ └── 49_alignment.php │ ├── Basic5/ │ │ ├── 50_xlsverticalbreak.php │ │ ├── 51_ProtectedSort.php │ │ ├── 52_Currency.php │ │ ├── 53_ImageOpacity.php │ │ ├── 54_ImagesInAndOut.php │ │ ├── 55_DefinedStyles.php │ │ └── 56_OdsToISO8601.php │ ├── Bitwise/ │ │ ├── BITAND.php │ │ ├── BITLSHIFT.php │ │ ├── BITOR.php │ │ ├── BITRSHIFT.php │ │ └── BITXOR.php │ ├── Bootstrap.php │ ├── Chart/ │ │ ├── 32_Chart_read_write.php │ │ ├── 32_Chart_read_write_HTML.php │ │ ├── 32_Chart_read_write_PDF.php │ │ ├── 34_Chart_update.php │ │ ├── 35_Chart_render.php │ │ ├── 35_Chart_render33.php │ │ └── 37_Chart_dynamic_title.php │ ├── Chart33a/ │ │ ├── 33_Chart_create_area.php │ │ ├── 33_Chart_create_area_2.php │ │ ├── 33_Chart_create_bar.php │ │ ├── 33_Chart_create_bar_custom_colors.php │ │ ├── 33_Chart_create_bar_labels_lines.php │ │ ├── 33_Chart_create_bar_stacked.php │ │ ├── 33_Chart_create_bubble.php │ │ ├── 33_Chart_create_column.php │ │ ├── 33_Chart_create_column_2.php │ │ ├── 33_Chart_create_composite.alternate.php │ │ ├── 33_Chart_create_composite.php │ │ ├── 33_Chart_create_line.php │ │ └── 33_Chart_create_line_dateaxis.php │ ├── Chart33b/ │ │ ├── 33_Chart_create_multiple_charts.php │ │ ├── 33_Chart_create_pie.php │ │ ├── 33_Chart_create_pie_custom_colors.php │ │ ├── 33_Chart_create_radar.php │ │ ├── 33_Chart_create_scatter.php │ │ ├── 33_Chart_create_scatter2.php │ │ ├── 33_Chart_create_scatter3.php │ │ ├── 33_Chart_create_scatter4.php │ │ ├── 33_Chart_create_scatter5_trendlines.php │ │ ├── 33_Chart_create_scatter6_value_xaxis.php │ │ ├── 33_Chart_create_scatter7_blanks.php │ │ ├── 33_Chart_create_stock.php │ │ └── 33_Chart_create_stock2.php │ ├── ComplexNumbers1/ │ │ ├── COMPLEX.php │ │ ├── IMABS.php │ │ ├── IMAGINARY.php │ │ ├── IMARGUMENT.php │ │ ├── IMCONJUGATE.php │ │ └── IMREAL.php │ ├── ComplexNumbers2/ │ │ ├── IMCOS.php │ │ ├── IMCOSH.php │ │ ├── IMCOT.php │ │ ├── IMCSC.php │ │ ├── IMCSCH.php │ │ ├── IMDIV.php │ │ ├── IMEXP.php │ │ ├── IMLN.php │ │ ├── IMLOG10.php │ │ └── IMLOG2.php │ ├── ComplexNumbers3/ │ │ ├── IMPOWER.php │ │ ├── IMPRODUCT.php │ │ ├── IMSEC.php │ │ ├── IMSECH.php │ │ ├── IMSIN.php │ │ ├── IMSINH.php │ │ ├── IMSQRT.php │ │ ├── IMSUB.php │ │ ├── IMSUM.php │ │ └── IMTAN.php │ ├── ConditionalFormatting/ │ │ ├── 01_Basic_Comparisons.php │ │ ├── 02_Text_Comparisons.php │ │ ├── 03_Blank_Comparisons.php │ │ ├── 04_Error_Comparisons.php │ │ ├── 05_Date_Comparisons.php │ │ ├── 06_Duplicate_Comparisons.php │ │ ├── 07_Expression_Comparisons.php │ │ ├── cond08_colorscale.php │ │ └── cond09_iconset.php │ ├── Database/ │ │ ├── DAVERAGE.php │ │ ├── DCOUNT.php │ │ ├── DCOUNTA.php │ │ ├── DGET.php │ │ ├── DMAX.php │ │ ├── DMIN.php │ │ ├── DPRODUCT.php │ │ ├── DSTDEV.php │ │ ├── DSTDEVP.php │ │ ├── DSUM.php │ │ ├── DVAR.php │ │ └── DVARP.php │ ├── DateTime/ │ │ ├── DATE.php │ │ ├── DATEDIF.php │ │ ├── DATEVALUE.php │ │ ├── DAY.php │ │ ├── DAYS.php │ │ ├── DAYS360.php │ │ ├── EDATE.php │ │ ├── EOMONTH.php │ │ ├── HOUR.php │ │ ├── ISOWEEKNUM.php │ │ ├── MINUTE.php │ │ └── MONTH.php │ ├── DateTime2/ │ │ ├── NETWORKDAYS.php │ │ ├── NOW.php │ │ ├── SECOND.php │ │ ├── TIME.php │ │ ├── TIMEVALUE.php │ │ ├── TODAY.php │ │ ├── WEEKDAY.php │ │ ├── WEEKNUM.php │ │ ├── WORKDAY.php │ │ ├── YEAR.php │ │ └── YEARFRAC.php │ ├── DefinedNames/ │ │ ├── AbsoluteNamedRange.php │ │ ├── CrossWorksheetNamedFormula.php │ │ ├── NamedFormulaeAndRanges.php │ │ ├── RelativeNamedRange.php │ │ ├── RelativeNamedRange2.php │ │ ├── RelativeNamedRangeAsFunction.php │ │ ├── ScopedNamedRange.php │ │ ├── ScopedNamedRange2.php │ │ ├── SimpleNamedFormula.php │ │ └── SimpleNamedRange.php │ ├── Engineering/ │ │ ├── BESSELI.php │ │ ├── BESSELJ.php │ │ ├── BESSELK.php │ │ ├── BESSELY.php │ │ ├── CONVERT.php │ │ ├── Convert-Online.php │ │ ├── DELTA.php │ │ ├── ERF.php │ │ ├── ERFC.php │ │ └── GESTEP.php │ ├── Financial1/ │ │ ├── ACCRINT.php │ │ ├── ACCRINTM.php │ │ ├── AMORDEGRC.php │ │ ├── AMORLINC.php │ │ ├── COUPDAYBS.php │ │ ├── COUPDAYS.php │ │ ├── COUPDAYSNC.php │ │ ├── COUPNCD.php │ │ ├── COUPNUM.php │ │ ├── COUPPCD.php │ │ ├── CUMIPMT.php │ │ └── CUMPRINC.php │ ├── Financial2/ │ │ ├── DB.php │ │ ├── DDB.php │ │ ├── DISC.php │ │ ├── DOLLARDE.php │ │ ├── DOLLARFR.php │ │ ├── EFFECT.php │ │ ├── FV.php │ │ └── FVSCHEDULE.php │ ├── Financial3/ │ │ ├── INTRATE.php │ │ ├── IPMT.php │ │ ├── IRR.php │ │ ├── ISPMT.php │ │ ├── MIRR.php │ │ ├── NOMINAL.php │ │ ├── NPER.php │ │ └── NPV.php │ ├── Header.php │ ├── HexEtcConversions/ │ │ ├── BIN2DEC.php │ │ ├── BIN2HEX.php │ │ ├── BIN2OCT.php │ │ ├── DEC2BIN.php │ │ ├── DEC2HEX.php │ │ ├── DEC2OCT.php │ │ ├── HEX2BIN.php │ │ ├── HEX2DEC.php │ │ ├── HEX2OCT.php │ │ ├── OCT2BIN.php │ │ ├── OCT2DEC.php │ │ └── OCT2HEX.php │ ├── Html/ │ │ ├── html_01_Basic_Conditional_Formatting.php │ │ ├── html_02_More_Conditional_Formatting.php │ │ ├── html_03_Color_Scale.php │ │ ├── html_04_Table_Format_without_Conditional.php │ │ ├── html_05_Table_Format_with_Conditional.php │ │ └── html_06_Table_Cellspacing.php │ ├── LookupRef/ │ │ ├── ADDRESS.php │ │ ├── COLUMN.php │ │ ├── COLUMNS.php │ │ ├── INDEX.php │ │ ├── INDIRECT.php │ │ ├── OFFSET.php │ │ ├── ROW.php │ │ ├── ROWS.php │ │ ├── SortExcel.php │ │ ├── SortExcelCols.php │ │ └── VLOOKUP.php │ ├── Pdf/ │ │ ├── 21_Pdf_Domdf.php │ │ ├── 21_Pdf_TCPDF.php │ │ ├── 21_Pdf_mPDF.php │ │ ├── 21a_Pdf.php │ │ ├── 21b_Pdf.php │ │ ├── 21d_FitToHeightPdf.php │ │ ├── 21e_UnusualFont_mpdf.php │ │ ├── 21f_Drawing.php │ │ ├── 21g_Direction.php │ │ ├── 21h_DirectionMultiple.php │ │ ├── Dompdf_Canvas_Headers.php │ │ ├── Dompdf_Custom_Headers.php │ │ ├── Mpdf_Custom_Headers.php │ │ └── Tcpdf_Custom_Headers.php │ ├── Reader/ │ │ ├── 01_Simple_file_reader_using_IOFactory.php │ │ ├── 02_Simple_file_reader_using_a_specified_reader.php │ │ ├── 03_Simple_file_reader_using_the_IOFactory_to_return_a_reader.php │ │ ├── 04_Simple_file_reader_using_the_IOFactory_to_identify_a_reader_to_use.php │ │ ├── 05_Simple_file_reader_using_the_read_data_only_option.php │ │ ├── 06_Simple_file_reader_loading_all_worksheets.php │ │ ├── 07_Simple_file_reader_loading_a_single_named_worksheet.php │ │ ├── 08_Simple_file_reader_loading_several_named_worksheets.php │ │ ├── 09_Simple_file_reader_using_a_read_filter.php │ │ ├── 10_Simple_file_reader_using_a_configurable_read_filter.php │ │ ├── 11_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_version_1.php │ │ ├── 12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_version_2.php │ │ └── sampleData/ │ │ ├── example1.xls │ │ ├── example1xls │ │ └── example2.xls │ ├── Reader2/ │ │ ├── 13_Simple_file_reader_for_multiple_CSV_files.php │ │ ├── 14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php │ │ ├── 15_Simple_file_reader_for_tab_separated_value_file_using_the_Advanced_Value_Binder.php │ │ ├── 16_Handling_loader_exceptions_using_TryCatch.php │ │ ├── 17_Simple_file_reader_loading_several_named_worksheets.php │ │ ├── 18_Reading_list_of_worksheets_without_loading_entire_file.php │ │ ├── 19_Reading_worksheet_information_without_loading_entire_file.php │ │ ├── 20_Reader_worksheet_hyperlink_image.php │ │ ├── 21_Reader_CSV_Long_Integers_with_String_Value_Binder.php │ │ ├── 22_Reader_formscomments.php │ │ ├── 22_Reader_issue1767.php │ │ ├── 23_iterateRowsYield.php │ │ └── sampleData/ │ │ ├── example1.csv │ │ ├── example1.tsv │ │ ├── example1.xls │ │ ├── example2.csv │ │ ├── formscomments.xlsx │ │ ├── issue.1767.xlsx │ │ └── longIntegers.csv │ ├── Reading_workbook_data/ │ │ ├── Custom_properties.php │ │ ├── Custom_property_names.php │ │ ├── Properties.php │ │ ├── Worksheet_count_and_names.php │ │ └── sampleData/ │ │ ├── example1.xls │ │ ├── example1.xlsx │ │ └── example2.xls │ ├── Table/ │ │ ├── 01_Table.php │ │ ├── 02_Table_Total.php │ │ ├── 03_Column_Formula.php │ │ └── 04_Column_Formula_with_Totals.php │ ├── Wizards/ │ │ ├── Header.php │ │ └── NumberFormat/ │ │ ├── Accounting.php │ │ ├── Currency.php │ │ ├── Number.php │ │ ├── Percentage.php │ │ └── Scientific.php │ ├── bootstrap/ │ │ ├── css/ │ │ │ └── phpspreadsheet.css │ │ └── fonts/ │ │ └── FontAwesome.otf │ ├── download.php │ ├── index.php │ └── templates/ │ ├── 21d_FitToHeightPdf.xlsx │ ├── 26template.xlsx │ ├── 27template.xls │ ├── 27template.xlsx │ ├── 28iterators.xlsx │ ├── 30template.xls │ ├── 30templatebiff5.xls │ ├── 31docproperties.xls │ ├── 31docproperties.xlsx │ ├── 32chartreadwrite.xlsx │ ├── 32complexChartreadwrite.xlsx │ ├── 32readwriteAreaChart1.xlsx │ ├── 32readwriteAreaChart2.xlsx │ ├── 32readwriteAreaChart3.xlsx │ ├── 32readwriteAreaChart3D1.xlsx │ ├── 32readwriteAreaChart4.xlsx │ ├── 32readwriteAreaPercentageChart1.xlsx │ ├── 32readwriteAreaPercentageChart2.xlsx │ ├── 32readwriteAreaPercentageChart3D1.xlsx │ ├── 32readwriteAreaStackedChart1.xlsx │ ├── 32readwriteAreaStackedChart2.xlsx │ ├── 32readwriteAreaStackedChart3D1.xlsx │ ├── 32readwriteBarChart1.xlsx │ ├── 32readwriteBarChart2.xlsx │ ├── 32readwriteBarChart3.xlsx │ ├── 32readwriteBarChart3D1.xlsx │ ├── 32readwriteBarChart4.xlsx │ ├── 32readwriteBarPercentageChart1.xlsx │ ├── 32readwriteBarPercentageChart2.xlsx │ ├── 32readwriteBarPercentageChart3D1.xlsx │ ├── 32readwriteBarStackedChart1.xlsx │ ├── 32readwriteBarStackedChart2.xlsx │ ├── 32readwriteBarStackedChart3D1.xlsx │ ├── 32readwriteBubbleChart1.xlsx │ ├── 32readwriteBubbleChart2.xlsx │ ├── 32readwriteBubbleChart3D1.xlsx │ ├── 32readwriteChartWithImages1.xlsx │ ├── 32readwriteColumnChart1.xlsx │ ├── 32readwriteColumnChart2.xlsx │ ├── 32readwriteColumnChart3.xlsx │ ├── 32readwriteColumnChart3D1.xlsx │ ├── 32readwriteColumnChart4.xlsx │ ├── 32readwriteColumnPercentageChart1.xlsx │ ├── 32readwriteColumnPercentageChart2.xlsx │ ├── 32readwriteColumnPercentageChart3D1.xlsx │ ├── 32readwriteColumnStackedChart1.xlsx │ ├── 32readwriteColumnStackedChart2.xlsx │ ├── 32readwriteColumnStackedChart3D1.xlsx │ ├── 32readwriteComboChart1.xlsx │ ├── 32readwriteDonutChart1.xlsx │ ├── 32readwriteDonutChart2.xlsx │ ├── 32readwriteDonutChart3.xlsx │ ├── 32readwriteDonutChart4.xlsx │ ├── 32readwriteDonutChartExploded1.xlsx │ ├── 32readwriteDonutChartMultiseries1.xlsx │ ├── 32readwriteLineChart1.xlsx │ ├── 32readwriteLineChart2.xlsx │ ├── 32readwriteLineChart3.xlsx │ ├── 32readwriteLineChart3D1.xlsx │ ├── 32readwriteLineChart4.xlsx │ ├── 32readwriteLineChart5.xlsx │ ├── 32readwriteLineChart6.xlsx │ ├── 32readwriteLineChartNoPointMarkers1.xlsx │ ├── 32readwriteLineDateAxisChart1.xlsx │ ├── 32readwriteLinePercentageChart1.xlsx │ ├── 32readwriteLinePercentageChart2.xlsx │ ├── 32readwriteLineStackedChart1.xlsx │ ├── 32readwriteLineStackedChart2.xlsx │ ├── 32readwritePieChart1.xlsx │ ├── 32readwritePieChart2.xlsx │ ├── 32readwritePieChart3.xlsx │ ├── 32readwritePieChart3D1.xlsx │ ├── 32readwritePieChart4.xlsx │ ├── 32readwritePieChartExploded1.xlsx │ ├── 32readwritePieChartExploded3D1.xlsx │ ├── 32readwriteRadarChart1.xlsx │ ├── 32readwriteRadarChart2.xlsx │ ├── 32readwriteRadarChart3.xlsx │ ├── 32readwriteScatterChart1.xlsx │ ├── 32readwriteScatterChart10.xlsx │ ├── 32readwriteScatterChart2.xlsx │ ├── 32readwriteScatterChart3.xlsx │ ├── 32readwriteScatterChart4.xlsx │ ├── 32readwriteScatterChart5.xlsx │ ├── 32readwriteScatterChart6.xlsx │ ├── 32readwriteScatterChart7.xlsx │ ├── 32readwriteScatterChart8.xlsx │ ├── 32readwriteScatterChart9.xlsx │ ├── 32readwriteScatterChartTrendlines1.xlsx │ ├── 32readwriteStockChart1.xlsx │ ├── 32readwriteStockChart2.xlsx │ ├── 32readwriteStockChart3.xlsx │ ├── 32readwriteStockChart4.xlsx │ ├── 32readwriteStockChart5.xlsx │ ├── 32readwriteSurfaceChart1.xlsx │ ├── 32readwriteSurfaceChart2.xlsx │ ├── 32readwriteSurfaceChart3.xlsx │ ├── 32readwriteSurfaceChart4.xlsx │ ├── 36writeLineChart1.xlsx │ ├── 36writeMultiple1.xlsx │ ├── 37dynamictitle.xlsx │ ├── 43mergeBook1.xlsx │ ├── 43mergeBook2.xlsx │ ├── 46readHtml.html │ ├── 47_xlsfill.xls │ ├── 47_xlsxfill.xlsx │ ├── 50_xlsverticalbreak.xls │ ├── 56_MixedDateFormats.ods │ ├── BasicConditionalFormatting.xlsx │ ├── ColourScale.xlsx │ ├── ConditionalFormattingConditions.xlsx │ ├── Excel2003XMLTest.xml │ ├── GnumericTest.gnumeric │ ├── Mpdf2.php │ ├── OOCalcTest.ods │ ├── ShadowsIntoLight.OFL.txt │ ├── SylkTest.slk │ ├── TableFormat.xlsx │ ├── chart-with-and-without-overlays.xlsx │ ├── chartSpreadsheet.php │ ├── excel2003.short.bad.xml │ ├── excel2003.xml │ ├── largeSpreadsheet.php │ ├── old.gnumeric │ ├── sampleSpreadsheet.php │ └── sampleSpreadsheet2.php ├── src/ │ └── PhpSpreadsheet/ │ ├── Calculation/ │ │ ├── ArrayEnabled.php │ │ ├── BinaryComparison.php │ │ ├── Calculation.php │ │ ├── CalculationBase.php │ │ ├── CalculationLocale.php │ │ ├── CalculationParserOnly.php │ │ ├── Category.php │ │ ├── Database/ │ │ │ ├── DAverage.php │ │ │ ├── DCount.php │ │ │ ├── DCountA.php │ │ │ ├── DGet.php │ │ │ ├── DMax.php │ │ │ ├── DMin.php │ │ │ ├── DProduct.php │ │ │ ├── DStDev.php │ │ │ ├── DStDevP.php │ │ │ ├── DSum.php │ │ │ ├── DVar.php │ │ │ ├── DVarP.php │ │ │ └── DatabaseAbstract.php │ │ ├── DateTimeExcel/ │ │ │ ├── Constants.php │ │ │ ├── Current.php │ │ │ ├── Date.php │ │ │ ├── DateParts.php │ │ │ ├── DateValue.php │ │ │ ├── Days.php │ │ │ ├── Days360.php │ │ │ ├── Difference.php │ │ │ ├── Helpers.php │ │ │ ├── Month.php │ │ │ ├── NetworkDays.php │ │ │ ├── Time.php │ │ │ ├── TimeParts.php │ │ │ ├── TimeValue.php │ │ │ ├── Week.php │ │ │ ├── WorkDay.php │ │ │ └── YearFrac.php │ │ ├── Engine/ │ │ │ ├── ArrayArgumentHelper.php │ │ │ ├── ArrayArgumentProcessor.php │ │ │ ├── BranchPruner.php │ │ │ ├── CyclicReferenceStack.php │ │ │ ├── FormattedNumber.php │ │ │ ├── Logger.php │ │ │ └── Operands/ │ │ │ ├── Operand.php │ │ │ └── StructuredReference.php │ │ ├── Engineering/ │ │ │ ├── BesselI.php │ │ │ ├── BesselJ.php │ │ │ ├── BesselK.php │ │ │ ├── BesselY.php │ │ │ ├── BitWise.php │ │ │ ├── Compare.php │ │ │ ├── Complex.php │ │ │ ├── ComplexFunctions.php │ │ │ ├── ComplexOperations.php │ │ │ ├── Constants.php │ │ │ ├── ConvertBase.php │ │ │ ├── ConvertBinary.php │ │ │ ├── ConvertDecimal.php │ │ │ ├── ConvertHex.php │ │ │ ├── ConvertOctal.php │ │ │ ├── ConvertUOM.php │ │ │ ├── EngineeringValidations.php │ │ │ ├── Erf.php │ │ │ └── ErfC.php │ │ ├── Exception.php │ │ ├── ExceptionHandler.php │ │ ├── Financial/ │ │ │ ├── Amortization.php │ │ │ ├── CashFlow/ │ │ │ │ ├── CashFlowValidations.php │ │ │ │ ├── Constant/ │ │ │ │ │ ├── Periodic/ │ │ │ │ │ │ ├── Cumulative.php │ │ │ │ │ │ ├── Interest.php │ │ │ │ │ │ ├── InterestAndPrincipal.php │ │ │ │ │ │ └── Payments.php │ │ │ │ │ └── Periodic.php │ │ │ │ ├── Single.php │ │ │ │ └── Variable/ │ │ │ │ ├── NonPeriodic.php │ │ │ │ └── Periodic.php │ │ │ ├── Constants.php │ │ │ ├── Coupons.php │ │ │ ├── Depreciation.php │ │ │ ├── Dollar.php │ │ │ ├── FinancialValidations.php │ │ │ ├── Helpers.php │ │ │ ├── InterestRate.php │ │ │ ├── Securities/ │ │ │ │ ├── AccruedInterest.php │ │ │ │ ├── Price.php │ │ │ │ ├── Rates.php │ │ │ │ ├── SecurityValidations.php │ │ │ │ └── Yields.php │ │ │ └── TreasuryBill.php │ │ ├── FormulaParser.php │ │ ├── FormulaToken.php │ │ ├── FunctionArray.php │ │ ├── Functions.php │ │ ├── Information/ │ │ │ ├── ErrorValue.php │ │ │ ├── ExcelError.php │ │ │ ├── Info.php │ │ │ └── Value.php │ │ ├── Internal/ │ │ │ ├── ExcelArrayPseudoFunctions.php │ │ │ ├── MakeMatrix.php │ │ │ └── WildcardMatch.php │ │ ├── Logical/ │ │ │ ├── Boolean.php │ │ │ ├── Conditional.php │ │ │ └── Operations.php │ │ ├── LookupRef/ │ │ │ ├── Address.php │ │ │ ├── ChooseRowsEtc.php │ │ │ ├── ExcelMatch.php │ │ │ ├── Filter.php │ │ │ ├── Formula.php │ │ │ ├── HLookup.php │ │ │ ├── Helpers.php │ │ │ ├── Hstack.php │ │ │ ├── Hyperlink.php │ │ │ ├── Indirect.php │ │ │ ├── Lookup.php │ │ │ ├── LookupBase.php │ │ │ ├── LookupRefValidations.php │ │ │ ├── Matrix.php │ │ │ ├── Offset.php │ │ │ ├── RowColumnInformation.php │ │ │ ├── Selection.php │ │ │ ├── Sort.php │ │ │ ├── TorowTocol.php │ │ │ ├── Unique.php │ │ │ ├── VLookup.php │ │ │ └── Vstack.php │ │ ├── MathTrig/ │ │ │ ├── Absolute.php │ │ │ ├── Angle.php │ │ │ ├── Arabic.php │ │ │ ├── Base.php │ │ │ ├── Ceiling.php │ │ │ ├── Combinations.php │ │ │ ├── Exp.php │ │ │ ├── Factorial.php │ │ │ ├── Floor.php │ │ │ ├── Gcd.php │ │ │ ├── Helpers.php │ │ │ ├── IntClass.php │ │ │ ├── Lcm.php │ │ │ ├── Logarithms.php │ │ │ ├── MatrixFunctions.php │ │ │ ├── Operations.php │ │ │ ├── Random.php │ │ │ ├── Roman.php │ │ │ ├── Round.php │ │ │ ├── SeriesSum.php │ │ │ ├── Sign.php │ │ │ ├── Sqrt.php │ │ │ ├── Subtotal.php │ │ │ ├── Sum.php │ │ │ ├── SumSquares.php │ │ │ ├── Trig/ │ │ │ │ ├── Cosecant.php │ │ │ │ ├── Cosine.php │ │ │ │ ├── Cotangent.php │ │ │ │ ├── Secant.php │ │ │ │ ├── Sine.php │ │ │ │ └── Tangent.php │ │ │ └── Trunc.php │ │ ├── Statistical/ │ │ │ ├── AggregateBase.php │ │ │ ├── Averages/ │ │ │ │ └── Mean.php │ │ │ ├── Averages.php │ │ │ ├── Conditional.php │ │ │ ├── Confidence.php │ │ │ ├── Counts.php │ │ │ ├── Deviations.php │ │ │ ├── Distributions/ │ │ │ │ ├── Beta.php │ │ │ │ ├── Binomial.php │ │ │ │ ├── ChiSquared.php │ │ │ │ ├── DistributionValidations.php │ │ │ │ ├── Exponential.php │ │ │ │ ├── F.php │ │ │ │ ├── Fisher.php │ │ │ │ ├── Gamma.php │ │ │ │ ├── GammaBase.php │ │ │ │ ├── HyperGeometric.php │ │ │ │ ├── LogNormal.php │ │ │ │ ├── NewtonRaphson.php │ │ │ │ ├── Normal.php │ │ │ │ ├── Poisson.php │ │ │ │ ├── StandardNormal.php │ │ │ │ ├── StudentT.php │ │ │ │ └── Weibull.php │ │ │ ├── MaxMinBase.php │ │ │ ├── Maximum.php │ │ │ ├── Minimum.php │ │ │ ├── Percentiles.php │ │ │ ├── Permutations.php │ │ │ ├── Size.php │ │ │ ├── StandardDeviations.php │ │ │ ├── Standardize.php │ │ │ ├── StatisticalValidations.php │ │ │ ├── Trends.php │ │ │ ├── VarianceBase.php │ │ │ └── Variances.php │ │ ├── TextData/ │ │ │ ├── CaseConvert.php │ │ │ ├── CharacterConvert.php │ │ │ ├── Concatenate.php │ │ │ ├── Extract.php │ │ │ ├── Format.php │ │ │ ├── Helpers.php │ │ │ ├── Replace.php │ │ │ ├── Search.php │ │ │ ├── Text.php │ │ │ ├── Thai.php │ │ │ └── Trim.php │ │ ├── Token/ │ │ │ └── Stack.php │ │ ├── Web/ │ │ │ └── Service.php │ │ └── locale/ │ │ ├── Translations.xlsx │ │ ├── bg/ │ │ │ ├── config │ │ │ └── functions │ │ ├── cs/ │ │ │ ├── config │ │ │ └── functions │ │ ├── da/ │ │ │ ├── config │ │ │ └── functions │ │ ├── de/ │ │ │ ├── config │ │ │ └── functions │ │ ├── en/ │ │ │ └── uk/ │ │ │ └── config │ │ ├── es/ │ │ │ ├── config │ │ │ └── functions │ │ ├── fi/ │ │ │ ├── config │ │ │ └── functions │ │ ├── fr/ │ │ │ ├── config │ │ │ └── functions │ │ ├── hu/ │ │ │ ├── config │ │ │ └── functions │ │ ├── it/ │ │ │ ├── config │ │ │ └── functions │ │ ├── nb/ │ │ │ ├── config │ │ │ └── functions │ │ ├── nl/ │ │ │ ├── config │ │ │ └── functions │ │ ├── pl/ │ │ │ ├── config │ │ │ └── functions │ │ ├── pt/ │ │ │ ├── br/ │ │ │ │ ├── config │ │ │ │ └── functions │ │ │ ├── config │ │ │ └── functions │ │ ├── ru/ │ │ │ ├── config │ │ │ └── functions │ │ ├── sv/ │ │ │ ├── config │ │ │ └── functions │ │ └── tr/ │ │ ├── config │ │ └── functions │ ├── Cell/ │ │ ├── AddressHelper.php │ │ ├── AddressRange.php │ │ ├── AdvancedValueBinder.php │ │ ├── Cell.php │ │ ├── CellAddress.php │ │ ├── CellRange.php │ │ ├── ColumnRange.php │ │ ├── Coordinate.php │ │ ├── DataType.php │ │ ├── DataValidation.php │ │ ├── DataValidator.php │ │ ├── DefaultValueBinder.php │ │ ├── Hyperlink.php │ │ ├── IValueBinder.php │ │ ├── IgnoredErrors.php │ │ ├── RowRange.php │ │ └── StringValueBinder.php │ ├── CellReferenceHelper.php │ ├── Chart/ │ │ ├── Axis.php │ │ ├── AxisText.php │ │ ├── Chart.php │ │ ├── ChartColor.php │ │ ├── DataSeries.php │ │ ├── DataSeriesValues.php │ │ ├── Exception.php │ │ ├── GridLines.php │ │ ├── Layout.php │ │ ├── Legend.php │ │ ├── PlotArea.php │ │ ├── Properties.php │ │ ├── Renderer/ │ │ │ ├── IRenderer.php │ │ │ ├── JpGraph.php │ │ │ ├── JpGraphRendererBase.php │ │ │ ├── MtJpGraphRenderer.php │ │ │ └── PHP Charting Libraries.txt │ │ ├── Title.php │ │ └── TrendLine.php │ ├── Collection/ │ │ ├── Cells.php │ │ ├── CellsFactory.php │ │ └── Memory/ │ │ ├── SimpleCache1.php │ │ └── SimpleCache3.php │ ├── Comment.php │ ├── DefinedName.php │ ├── Document/ │ │ ├── Properties.php │ │ └── Security.php │ ├── Exception.php │ ├── HashTable.php │ ├── Helper/ │ │ ├── Dimension.php │ │ ├── Downloader.php │ │ ├── Handler.php │ │ ├── Html.php │ │ ├── Sample.php │ │ ├── Size.php │ │ ├── TextGrid.php │ │ └── TextGridRightAlign.php │ ├── IComparable.php │ ├── IOFactory.php │ ├── NamedFormula.php │ ├── NamedRange.php │ ├── Reader/ │ │ ├── BaseReader.php │ │ ├── Csv/ │ │ │ └── Delimiter.php │ │ ├── Csv.php │ │ ├── DefaultReadFilter.php │ │ ├── Exception.php │ │ ├── Gnumeric/ │ │ │ ├── PageSetup.php │ │ │ ├── Properties.php │ │ │ └── Styles.php │ │ ├── Gnumeric.php │ │ ├── Html.php │ │ ├── IReadFilter.php │ │ ├── IReader.php │ │ ├── Ods/ │ │ │ ├── AutoFilter.php │ │ │ ├── BaseLoader.php │ │ │ ├── DefinedNames.php │ │ │ ├── FormulaTranslator.php │ │ │ ├── PageSettings.php │ │ │ └── Properties.php │ │ ├── Ods.php │ │ ├── Security/ │ │ │ └── XmlScanner.php │ │ ├── Slk.php │ │ ├── Xls/ │ │ │ ├── Biff5.php │ │ │ ├── Biff8.php │ │ │ ├── Color/ │ │ │ │ ├── BIFF5.php │ │ │ │ ├── BIFF8.php │ │ │ │ └── BuiltIn.php │ │ │ ├── Color.php │ │ │ ├── ConditionalFormatting.php │ │ │ ├── DataValidationHelper.php │ │ │ ├── ErrorCode.php │ │ │ ├── Escher.php │ │ │ ├── ListFunctions.php │ │ │ ├── LoadSpreadsheet.php │ │ │ ├── MD5.php │ │ │ ├── Mappings.php │ │ │ ├── RC4.php │ │ │ └── Style/ │ │ │ ├── Border.php │ │ │ ├── CellAlignment.php │ │ │ ├── CellFont.php │ │ │ └── FillPattern.php │ │ ├── Xls.php │ │ ├── XlsBase.php │ │ ├── Xlsx/ │ │ │ ├── AutoFilter.php │ │ │ ├── BaseParserClass.php │ │ │ ├── Chart.php │ │ │ ├── ColumnAndRowAttributes.php │ │ │ ├── ConditionalStyles.php │ │ │ ├── DataValidations.php │ │ │ ├── Hyperlinks.php │ │ │ ├── Namespaces.php │ │ │ ├── PageSetup.php │ │ │ ├── Properties.php │ │ │ ├── SharedFormula.php │ │ │ ├── SheetViewOptions.php │ │ │ ├── SheetViews.php │ │ │ ├── Styles.php │ │ │ ├── TableReader.php │ │ │ ├── Theme.php │ │ │ └── WorkbookView.php │ │ ├── Xlsx.php │ │ ├── Xml/ │ │ │ ├── DataValidations.php │ │ │ ├── PageSettings.php │ │ │ ├── Properties.php │ │ │ ├── Style/ │ │ │ │ ├── Alignment.php │ │ │ │ ├── Border.php │ │ │ │ ├── Fill.php │ │ │ │ ├── Font.php │ │ │ │ ├── NumberFormat.php │ │ │ │ └── StyleBase.php │ │ │ └── Style.php │ │ └── Xml.php │ ├── ReferenceHelper.php │ ├── RichText/ │ │ ├── ITextElement.php │ │ ├── RichText.php │ │ ├── Run.php │ │ └── TextElement.php │ ├── Settings.php │ ├── Shared/ │ │ ├── CodePage.php │ │ ├── Date.php │ │ ├── Drawing.php │ │ ├── Escher/ │ │ │ ├── DgContainer/ │ │ │ │ ├── SpgrContainer/ │ │ │ │ │ └── SpContainer.php │ │ │ │ └── SpgrContainer.php │ │ │ ├── DgContainer.php │ │ │ ├── DggContainer/ │ │ │ │ ├── BstoreContainer/ │ │ │ │ │ ├── BSE/ │ │ │ │ │ │ └── Blip.php │ │ │ │ │ └── BSE.php │ │ │ │ └── BstoreContainer.php │ │ │ └── DggContainer.php │ │ ├── Escher.php │ │ ├── File.php │ │ ├── Font.php │ │ ├── IntOrFloat.php │ │ ├── OLE/ │ │ │ ├── ChainedBlockStream.php │ │ │ ├── PPS/ │ │ │ │ ├── File.php │ │ │ │ └── Root.php │ │ │ └── PPS.php │ │ ├── OLE.php │ │ ├── OLERead.php │ │ ├── PasswordHasher.php │ │ ├── StringHelper.php │ │ ├── TimeZone.php │ │ ├── Trend/ │ │ │ ├── BestFit.php │ │ │ ├── ExponentialBestFit.php │ │ │ ├── LinearBestFit.php │ │ │ ├── LogarithmicBestFit.php │ │ │ ├── PolynomialBestFit.php │ │ │ ├── PowerBestFit.php │ │ │ └── Trend.php │ │ ├── XMLWriter.php │ │ └── Xls.php │ ├── Spreadsheet.php │ ├── Style/ │ │ ├── Alignment.php │ │ ├── Border.php │ │ ├── Borders.php │ │ ├── Color.php │ │ ├── Conditional.php │ │ ├── ConditionalFormatting/ │ │ │ ├── CellMatcher.php │ │ │ ├── CellStyleAssessor.php │ │ │ ├── ConditionalColorScale.php │ │ │ ├── ConditionalDataBar.php │ │ │ ├── ConditionalDataBarExtension.php │ │ │ ├── ConditionalFormatValueObject.php │ │ │ ├── ConditionalFormattingRuleExtension.php │ │ │ ├── ConditionalIconSet.php │ │ │ ├── IconSetValues.php │ │ │ ├── MergedCellStyle.php │ │ │ ├── StyleMerger.php │ │ │ ├── Wizard/ │ │ │ │ ├── Blanks.php │ │ │ │ ├── CellValue.php │ │ │ │ ├── DateValue.php │ │ │ │ ├── Duplicates.php │ │ │ │ ├── Errors.php │ │ │ │ ├── Expression.php │ │ │ │ ├── TextValue.php │ │ │ │ ├── WizardAbstract.php │ │ │ │ └── WizardInterface.php │ │ │ └── Wizard.php │ │ ├── Fill.php │ │ ├── Font.php │ │ ├── NumberFormat/ │ │ │ ├── BaseFormatter.php │ │ │ ├── DateFormatter.php │ │ │ ├── Formatter.php │ │ │ ├── FractionFormatter.php │ │ │ ├── NumberFormatter.php │ │ │ ├── PercentageFormatter.php │ │ │ └── Wizard/ │ │ │ ├── Accounting.php │ │ │ ├── Currency.php │ │ │ ├── CurrencyBase.php │ │ │ ├── CurrencyNegative.php │ │ │ ├── Date.php │ │ │ ├── DateTime.php │ │ │ ├── DateTimeWizard.php │ │ │ ├── Duration.php │ │ │ ├── Locale.php │ │ │ ├── Number.php │ │ │ ├── NumberBase.php │ │ │ ├── Percentage.php │ │ │ ├── Scientific.php │ │ │ ├── Time.php │ │ │ └── Wizard.php │ │ ├── NumberFormat.php │ │ ├── Protection.php │ │ ├── RgbTint.php │ │ ├── Style.php │ │ └── Supervisor.php │ ├── Theme.php │ ├── Worksheet/ │ │ ├── AutoFilter/ │ │ │ ├── Column/ │ │ │ │ └── Rule.php │ │ │ └── Column.php │ │ ├── AutoFilter.php │ │ ├── AutoFit.php │ │ ├── BaseDrawing.php │ │ ├── CellIterator.php │ │ ├── Column.php │ │ ├── ColumnCellIterator.php │ │ ├── ColumnDimension.php │ │ ├── ColumnIterator.php │ │ ├── Dimension.php │ │ ├── Drawing/ │ │ │ └── Shadow.php │ │ ├── Drawing.php │ │ ├── HeaderFooter.php │ │ ├── HeaderFooterDrawing.php │ │ ├── Iterator.php │ │ ├── MemoryDrawing.php │ │ ├── PageBreak.php │ │ ├── PageMargins.php │ │ ├── PageSetup.php │ │ ├── Pane.php │ │ ├── ProtectedRange.php │ │ ├── Protection.php │ │ ├── Row.php │ │ ├── RowCellIterator.php │ │ ├── RowDimension.php │ │ ├── RowIterator.php │ │ ├── SheetView.php │ │ ├── Table/ │ │ │ ├── Column.php │ │ │ ├── TableDxfsStyle.php │ │ │ └── TableStyle.php │ │ ├── Table.php │ │ ├── Validations.php │ │ └── Worksheet.php │ └── Writer/ │ ├── BaseWriter.php │ ├── Csv.php │ ├── Exception.php │ ├── Html.php │ ├── IWriter.php │ ├── Ods/ │ │ ├── AutoFilters.php │ │ ├── Cell/ │ │ │ ├── Comment.php │ │ │ └── Style.php │ │ ├── Content.php │ │ ├── Formula.php │ │ ├── Meta.php │ │ ├── MetaInf.php │ │ ├── Mimetype.php │ │ ├── NamedExpressions.php │ │ ├── Settings.php │ │ ├── Styles.php │ │ ├── Thumbnails.php │ │ └── WriterPart.php │ ├── Ods.php │ ├── Pdf/ │ │ ├── Dompdf.php │ │ ├── Mpdf.php │ │ ├── Tcpdf.php │ │ └── TcpdfNoDie.php │ ├── Pdf.php │ ├── Xls/ │ │ ├── BIFFwriter.php │ │ ├── CellDataValidation.php │ │ ├── ConditionalHelper.php │ │ ├── ErrorCode.php │ │ ├── Escher.php │ │ ├── Font.php │ │ ├── Parser.php │ │ ├── Style/ │ │ │ ├── CellAlignment.php │ │ │ ├── CellBorder.php │ │ │ └── CellFill.php │ │ ├── Workbook.php │ │ ├── Worksheet.php │ │ └── Xf.php │ ├── Xls.php │ ├── Xlsx/ │ │ ├── AutoFilter.php │ │ ├── Chart.php │ │ ├── Comments.php │ │ ├── ContentTypes.php │ │ ├── DefinedNames.php │ │ ├── DocProps.php │ │ ├── Drawing.php │ │ ├── FeaturePropertyBag.php │ │ ├── FunctionPrefix.php │ │ ├── Metadata.php │ │ ├── Rels.php │ │ ├── RelsRibbon.php │ │ ├── RelsVBA.php │ │ ├── RichDataDrawing.php │ │ ├── StringTable.php │ │ ├── Style.php │ │ ├── Table.php │ │ ├── Theme.php │ │ ├── Workbook.php │ │ ├── Worksheet.php │ │ └── WriterPart.php │ ├── Xlsx.php │ ├── ZipStream0.php │ ├── ZipStream2.php │ └── ZipStream3.php └── tests/ ├── PhpSpreadsheetTests/ │ ├── A1LocaleGeneratorTest.php │ ├── Calculation/ │ │ ├── ArrayFormulaTest.php │ │ ├── ArrayTest.php │ │ ├── AssociativityTest.php │ │ ├── BinaryComparisonTest.php │ │ ├── CalculationCoverageTest.php │ │ ├── CalculationErrorTest.php │ │ ├── CalculationFunctionListTest.php │ │ ├── CalculationLoggingTest.php │ │ ├── CalculationSettingsTest.php │ │ ├── CalculationTest.php │ │ ├── CustomFunction.php │ │ ├── CustomFunctionTest.php │ │ ├── CyclicTest.php │ │ ├── DefinedNameConfusedForCellTest.php │ │ ├── DefinedNameWithQuotePrefixedCellTest.php │ │ ├── DefinedNamesCalculationTest.php │ │ ├── Discussion1950Test.php │ │ ├── Engine/ │ │ │ ├── FormattedNumberSlashTest.php │ │ │ ├── FormattedNumberTest.php │ │ │ ├── RangeTest.php │ │ │ ├── StructuredReferenceSlashTest.php │ │ │ └── StructuredReferenceTest.php │ │ ├── FormulaAsStringTest.php │ │ ├── FormulaParserTest.php │ │ ├── Functions/ │ │ │ ├── Database/ │ │ │ │ ├── DAverageTest.php │ │ │ │ ├── DCountATest.php │ │ │ │ ├── DCountTest.php │ │ │ │ ├── DGetTest.php │ │ │ │ ├── DMaxTest.php │ │ │ │ ├── DMinTest.php │ │ │ │ ├── DProductTest.php │ │ │ │ ├── DStDevPTest.php │ │ │ │ ├── DStDevTest.php │ │ │ │ ├── DSumTest.php │ │ │ │ ├── DVarPTest.php │ │ │ │ ├── DVarTest.php │ │ │ │ └── SetupTeardownDatabases.php │ │ │ ├── DateTime/ │ │ │ │ ├── DateDifTest.php │ │ │ │ ├── DateTest.php │ │ │ │ ├── DateValueTest.php │ │ │ │ ├── DayTest.php │ │ │ │ ├── Days360Test.php │ │ │ │ ├── DaysTest.php │ │ │ │ ├── EDateTest.php │ │ │ │ ├── EoMonthTest.php │ │ │ │ ├── HelpersTest.php │ │ │ │ ├── HourTest.php │ │ │ │ ├── IsoWeekNumTest.php │ │ │ │ ├── MinuteTest.php │ │ │ │ ├── MonthTest.php │ │ │ │ ├── NetworkDaysTest.php │ │ │ │ ├── NowTest.php │ │ │ │ ├── SecondTest.php │ │ │ │ ├── TimeTest.php │ │ │ │ ├── TimeValueTest.php │ │ │ │ ├── TodayTest.php │ │ │ │ ├── WeekDayTest.php │ │ │ │ ├── WeekNumTest.php │ │ │ │ ├── WorkDayTest.php │ │ │ │ ├── YearFracTest.php │ │ │ │ └── YearTest.php │ │ │ ├── Engineering/ │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── BesselITest.php │ │ │ │ ├── BesselJTest.php │ │ │ │ ├── BesselKTest.php │ │ │ │ ├── BesselYTest.php │ │ │ │ ├── Bin2DecTest.php │ │ │ │ ├── Bin2HexTest.php │ │ │ │ ├── Bin2OctTest.php │ │ │ │ ├── BitAndTest.php │ │ │ │ ├── BitLShiftTest.php │ │ │ │ ├── BitOrTest.php │ │ │ │ ├── BitRShiftTest.php │ │ │ │ ├── BitXorTest.php │ │ │ │ ├── ComplexTest.php │ │ │ │ ├── ConvertUoMTest.php │ │ │ │ ├── Dec2BinTest.php │ │ │ │ ├── Dec2HexTest.php │ │ │ │ ├── Dec2OctTest.php │ │ │ │ ├── DeltaTest.php │ │ │ │ ├── ErfCTest.php │ │ │ │ ├── ErfPreciseTest.php │ │ │ │ ├── ErfTest.php │ │ │ │ ├── GeStepTest.php │ │ │ │ ├── Hex2BinTest.php │ │ │ │ ├── Hex2DecTest.php │ │ │ │ ├── Hex2OctTest.php │ │ │ │ ├── ImAbsTest.php │ │ │ │ ├── ImArgumentTest.php │ │ │ │ ├── ImConjugateTest.php │ │ │ │ ├── ImCosTest.php │ │ │ │ ├── ImCoshTest.php │ │ │ │ ├── ImCotTest.php │ │ │ │ ├── ImCscTest.php │ │ │ │ ├── ImCschTest.php │ │ │ │ ├── ImDivTest.php │ │ │ │ ├── ImExpTest.php │ │ │ │ ├── ImLnTest.php │ │ │ │ ├── ImLog10Test.php │ │ │ │ ├── ImLog2Test.php │ │ │ │ ├── ImPowerTest.php │ │ │ │ ├── ImProductTest.php │ │ │ │ ├── ImRealTest.php │ │ │ │ ├── ImSecTest.php │ │ │ │ ├── ImSechTest.php │ │ │ │ ├── ImSinTest.php │ │ │ │ ├── ImSinhTest.php │ │ │ │ ├── ImSqrtTest.php │ │ │ │ ├── ImSubTest.php │ │ │ │ ├── ImSumTest.php │ │ │ │ ├── ImTanTest.php │ │ │ │ ├── ImaginaryTest.php │ │ │ │ ├── Oct2BinTest.php │ │ │ │ ├── Oct2DecTest.php │ │ │ │ └── Oct2HexTest.php │ │ │ ├── Financial/ │ │ │ │ ├── AccrintMTest.php │ │ │ │ ├── AccrintTest.php │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── AmorDegRcTest.php │ │ │ │ ├── AmorLincTest.php │ │ │ │ ├── CoupDayBsTest.php │ │ │ │ ├── CoupDaysNcTest.php │ │ │ │ ├── CoupDaysTest.php │ │ │ │ ├── CoupNcdTest.php │ │ │ │ ├── CoupNumTest.php │ │ │ │ ├── CoupPcdTest.php │ │ │ │ ├── CumIpmtTest.php │ │ │ │ ├── CumPrincTest.php │ │ │ │ ├── DbTest.php │ │ │ │ ├── DdbTest.php │ │ │ │ ├── DiscTest.php │ │ │ │ ├── DollarDeTest.php │ │ │ │ ├── DollarFrTest.php │ │ │ │ ├── EffectTest.php │ │ │ │ ├── FvScheduleTest.php │ │ │ │ ├── FvTest.php │ │ │ │ ├── HelpersTest.php │ │ │ │ ├── IPmtTest.php │ │ │ │ ├── IntRateTest.php │ │ │ │ ├── IrrTest.php │ │ │ │ ├── IsPmtTest.php │ │ │ │ ├── MirrTest.php │ │ │ │ ├── NPerTest.php │ │ │ │ ├── NominalTest.php │ │ │ │ ├── NpvTest.php │ │ │ │ ├── PDurationTest.php │ │ │ │ ├── PmtTest.php │ │ │ │ ├── PpmtTest.php │ │ │ │ ├── PriceDiscTest.php │ │ │ │ ├── PriceMatTest.php │ │ │ │ ├── PriceTest.php │ │ │ │ ├── PvTest.php │ │ │ │ ├── RateTest.php │ │ │ │ ├── ReceivedTest.php │ │ │ │ ├── RriTest.php │ │ │ │ ├── SlnTest.php │ │ │ │ ├── SydTest.php │ │ │ │ ├── TBillEqTest.php │ │ │ │ ├── TBillPriceTest.php │ │ │ │ ├── TBillYieldTest.php │ │ │ │ ├── UsDollarTest.php │ │ │ │ ├── XNpvTest.php │ │ │ │ ├── XirrTest.php │ │ │ │ ├── YieldDiscTest.php │ │ │ │ └── YieldMatTest.php │ │ │ ├── FormulaArguments.php │ │ │ ├── Information/ │ │ │ │ ├── Div0Test.php │ │ │ │ ├── ErrorTypeTest.php │ │ │ │ ├── InfoTest.php │ │ │ │ ├── IsBlankTest.php │ │ │ │ ├── IsErrTest.php │ │ │ │ ├── IsErrorTest.php │ │ │ │ ├── IsEvenTest.php │ │ │ │ ├── IsFormulaTest.php │ │ │ │ ├── IsLogicalTest.php │ │ │ │ ├── IsNaTest.php │ │ │ │ ├── IsNonTextTest.php │ │ │ │ ├── IsNumberTest.php │ │ │ │ ├── IsOddTest.php │ │ │ │ ├── IsRefTest.php │ │ │ │ ├── IsTextTest.php │ │ │ │ ├── NTest.php │ │ │ │ ├── NaTest.php │ │ │ │ ├── NameTest.php │ │ │ │ ├── NanTest.php │ │ │ │ ├── NullTest.php │ │ │ │ ├── RefTest.php │ │ │ │ ├── TypeTest.php │ │ │ │ └── ValueTest.php │ │ │ ├── Logical/ │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── AndTest.php │ │ │ │ ├── FalseTest.php │ │ │ │ ├── IfErrorTest.php │ │ │ │ ├── IfNaTest.php │ │ │ │ ├── IfTest.php │ │ │ │ ├── IfsTest.php │ │ │ │ ├── NotTest.php │ │ │ │ ├── OrTest.php │ │ │ │ ├── SwitchTest.php │ │ │ │ ├── TrueTest.php │ │ │ │ └── XorTest.php │ │ │ ├── LookupRef/ │ │ │ │ ├── AddressInternationalTest.php │ │ │ │ ├── AddressTest.php │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── ChooseColsTest.php │ │ │ │ ├── ChooseRowsTest.php │ │ │ │ ├── ChooseTest.php │ │ │ │ ├── ColumnOnSpreadsheetTest.php │ │ │ │ ├── ColumnTest.php │ │ │ │ ├── ColumnsOnSpreadsheetTest.php │ │ │ │ ├── ColumnsTest.php │ │ │ │ ├── DropTest.php │ │ │ │ ├── ExpandTest.php │ │ │ │ ├── FilterOnSpreadsheetTest.php │ │ │ │ ├── FilterTest.php │ │ │ │ ├── FormulaTextTest.php │ │ │ │ ├── HLookupTest.php │ │ │ │ ├── HStackTest.php │ │ │ │ ├── HyperlinkTest.php │ │ │ │ ├── IndexOnSpreadsheetTest.php │ │ │ │ ├── IndexTest.php │ │ │ │ ├── IndirectInternationalTest.php │ │ │ │ ├── IndirectMissingCellTest.php │ │ │ │ ├── IndirectTest.php │ │ │ │ ├── LookupTest.php │ │ │ │ ├── MatchTest.php │ │ │ │ ├── MatrixHelperFunctionsTest.php │ │ │ │ ├── OffsetTest.php │ │ │ │ ├── RowOnSpreadsheetTest.php │ │ │ │ ├── RowTest.php │ │ │ │ ├── RowsOnSpreadsheetTest.php │ │ │ │ ├── RowsTest.php │ │ │ │ ├── SortBetterTest.php │ │ │ │ ├── SortByBetterTest.php │ │ │ │ ├── SortByTest.php │ │ │ │ ├── SortTest.php │ │ │ │ ├── TakeTest.php │ │ │ │ ├── TocolTest.php │ │ │ │ ├── TorowTest.php │ │ │ │ ├── TransposeOnSpreadsheetTest.php │ │ │ │ ├── TransposeTest.php │ │ │ │ ├── UniqueTest.php │ │ │ │ ├── VLookupTest.php │ │ │ │ └── VStackTest.php │ │ │ ├── MathTrig/ │ │ │ │ ├── AbsTest.php │ │ │ │ ├── AcosTest.php │ │ │ │ ├── AcoshTest.php │ │ │ │ ├── AcotTest.php │ │ │ │ ├── AcothTest.php │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── ArabicTest.php │ │ │ │ ├── AsinTest.php │ │ │ │ ├── AsinhTest.php │ │ │ │ ├── Atan2Test.php │ │ │ │ ├── AtanTest.php │ │ │ │ ├── AtanhTest.php │ │ │ │ ├── BaseTest.php │ │ │ │ ├── CeilingMathTest.php │ │ │ │ ├── CeilingPreciseTest.php │ │ │ │ ├── CeilingTest.php │ │ │ │ ├── CombinATest.php │ │ │ │ ├── CombinTest.php │ │ │ │ ├── CosTest.php │ │ │ │ ├── CoshTest.php │ │ │ │ ├── CotTest.php │ │ │ │ ├── CothTest.php │ │ │ │ ├── CscTest.php │ │ │ │ ├── CschTest.php │ │ │ │ ├── DegreesTest.php │ │ │ │ ├── EvenTest.php │ │ │ │ ├── ExpTest.php │ │ │ │ ├── FactDoubleTest.php │ │ │ │ ├── FactTest.php │ │ │ │ ├── FloorMathTest.php │ │ │ │ ├── FloorPreciseTest.php │ │ │ │ ├── FloorTest.php │ │ │ │ ├── GcdTest.php │ │ │ │ ├── IntTest.php │ │ │ │ ├── LcmTest.php │ │ │ │ ├── LnTest.php │ │ │ │ ├── Log10Test.php │ │ │ │ ├── LogTest.php │ │ │ │ ├── MInverseTest.php │ │ │ │ ├── MMultTest.php │ │ │ │ ├── MRoundTest.php │ │ │ │ ├── MUnitTest.php │ │ │ │ ├── MdeTermTest.php │ │ │ │ ├── ModTest.php │ │ │ │ ├── MultinomialTest.php │ │ │ │ ├── OddTest.php │ │ │ │ ├── PiTest.php │ │ │ │ ├── PowerTest.php │ │ │ │ ├── ProductTest.php │ │ │ │ ├── QuotientTest.php │ │ │ │ ├── RadiansTest.php │ │ │ │ ├── RandArrayTest.php │ │ │ │ ├── RandBetweenTest.php │ │ │ │ ├── RandTest.php │ │ │ │ ├── RomanTest.php │ │ │ │ ├── RoundDownTest.php │ │ │ │ ├── RoundTest.php │ │ │ │ ├── RoundUpTest.php │ │ │ │ ├── SecTest.php │ │ │ │ ├── SechTest.php │ │ │ │ ├── SequenceTest.php │ │ │ │ ├── SeriesSumTest.php │ │ │ │ ├── SignTest.php │ │ │ │ ├── SinTest.php │ │ │ │ ├── SinhTest.php │ │ │ │ ├── SqrtPiTest.php │ │ │ │ ├── SqrtTest.php │ │ │ │ ├── SubTotalTest.php │ │ │ │ ├── SumIfTest.php │ │ │ │ ├── SumIfsTest.php │ │ │ │ ├── SumProduct2Test.php │ │ │ │ ├── SumProductTest.php │ │ │ │ ├── SumSqTest.php │ │ │ │ ├── SumTest.php │ │ │ │ ├── SumX2MY2Test.php │ │ │ │ ├── SumX2PY2Test.php │ │ │ │ ├── SumXMY2Test.php │ │ │ │ ├── TanTest.php │ │ │ │ ├── TanhTest.php │ │ │ │ └── TruncTest.php │ │ │ ├── Statistical/ │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── AveDevTest.php │ │ │ │ ├── AverageATest.php │ │ │ │ ├── AverageIf2Test.php │ │ │ │ ├── AverageIfTest.php │ │ │ │ ├── AverageIfsTest.php │ │ │ │ ├── AverageTest.php │ │ │ │ ├── BetaDistTest.php │ │ │ │ ├── BetaInvTest.php │ │ │ │ ├── BinomDistRangeTest.php │ │ │ │ ├── BinomDistTest.php │ │ │ │ ├── BinomInvTest.php │ │ │ │ ├── ChiDistLeftTailTest.php │ │ │ │ ├── ChiDistRightTailTest.php │ │ │ │ ├── ChiInvLeftTailTest.php │ │ │ │ ├── ChiInvRightTailTest.php │ │ │ │ ├── ChiTestTest.php │ │ │ │ ├── ConfidenceTest.php │ │ │ │ ├── CorrelTest.php │ │ │ │ ├── CountATest.php │ │ │ │ ├── CountBlankTest.php │ │ │ │ ├── CountIfTest.php │ │ │ │ ├── CountIfsTest.php │ │ │ │ ├── CountTest.php │ │ │ │ ├── CovarTest.php │ │ │ │ ├── DevSqTest.php │ │ │ │ ├── ExponDistTest.php │ │ │ │ ├── FDistTest.php │ │ │ │ ├── FisherInvTest.php │ │ │ │ ├── FisherTest.php │ │ │ │ ├── ForecastTest.php │ │ │ │ ├── GammaDistTest.php │ │ │ │ ├── GammaInvTest.php │ │ │ │ ├── GammaLnTest.php │ │ │ │ ├── GammaTest.php │ │ │ │ ├── GaussTest.php │ │ │ │ ├── GeoMeanTest.php │ │ │ │ ├── GrowthTest.php │ │ │ │ ├── HarMeanTest.php │ │ │ │ ├── HypGeomDistTest.php │ │ │ │ ├── InterceptTest.php │ │ │ │ ├── KurtTest.php │ │ │ │ ├── LargeTest.php │ │ │ │ ├── LinEstTest.php │ │ │ │ ├── LogEstTest.php │ │ │ │ ├── LogInvTest.php │ │ │ │ ├── LogNormDist2Test.php │ │ │ │ ├── LogNormDistTest.php │ │ │ │ ├── MaxATest.php │ │ │ │ ├── MaxIfsTest.php │ │ │ │ ├── MaxTest.php │ │ │ │ ├── MedianTest.php │ │ │ │ ├── MinATest.php │ │ │ │ ├── MinIfsTest.php │ │ │ │ ├── MinTest.php │ │ │ │ ├── ModeTest.php │ │ │ │ ├── NegBinomDistTest.php │ │ │ │ ├── NormDistTest.php │ │ │ │ ├── NormInvTest.php │ │ │ │ ├── NormSDist2Test.php │ │ │ │ ├── NormSDistTest.php │ │ │ │ ├── NormSInvTest.php │ │ │ │ ├── PercentRankTest.php │ │ │ │ ├── PercentileTest.php │ │ │ │ ├── PermutTest.php │ │ │ │ ├── PermutationATest.php │ │ │ │ ├── PoissonTest.php │ │ │ │ ├── QuartileTest.php │ │ │ │ ├── RankTest.php │ │ │ │ ├── RsqTest.php │ │ │ │ ├── SkewTest.php │ │ │ │ ├── SlopeTest.php │ │ │ │ ├── SmallTest.php │ │ │ │ ├── StDevATest.php │ │ │ │ ├── StDevPATest.php │ │ │ │ ├── StDevPTest.php │ │ │ │ ├── StDevTest.php │ │ │ │ ├── StandardizeTest.php │ │ │ │ ├── SteyxTest.php │ │ │ │ ├── TDist2TTest.php │ │ │ │ ├── TDistRTTest.php │ │ │ │ ├── TDistTest.php │ │ │ │ ├── TDotInvDot2TTest.php │ │ │ │ ├── TDotInvTest.php │ │ │ │ ├── TdotDistFalseTest.php │ │ │ │ ├── TdotDistTrueTest.php │ │ │ │ ├── TinvTest.php │ │ │ │ ├── TrendTest.php │ │ │ │ ├── TrimMeanTest.php │ │ │ │ ├── VarATest.php │ │ │ │ ├── VarPATest.php │ │ │ │ ├── VarPTest.php │ │ │ │ ├── VarTest.php │ │ │ │ ├── WeibullTest.php │ │ │ │ └── ZTestTest.php │ │ │ ├── TextData/ │ │ │ │ ├── AllSetupTeardown.php │ │ │ │ ├── ArrayToTextTest.php │ │ │ │ ├── BahtTest.php │ │ │ │ ├── CharNonPrintableTest.php │ │ │ │ ├── CharTest.php │ │ │ │ ├── CleanTest.php │ │ │ │ ├── CodeTest.php │ │ │ │ ├── ConcatTest.php │ │ │ │ ├── ConcatenateGnumericTest.php │ │ │ │ ├── ConcatenateRangeTest.php │ │ │ │ ├── ConcatenateTest.php │ │ │ │ ├── DollarTest.php │ │ │ │ ├── ErrorPropagationTest.php │ │ │ │ ├── ExactTest.php │ │ │ │ ├── FindTest.php │ │ │ │ ├── FixedTest.php │ │ │ │ ├── LeftTest.php │ │ │ │ ├── LenTest.php │ │ │ │ ├── LowerTest.php │ │ │ │ ├── MidTest.php │ │ │ │ ├── NumberValueTest.php │ │ │ │ ├── OpenOfficeTest.php │ │ │ │ ├── ProperTest.php │ │ │ │ ├── ReplaceTest.php │ │ │ │ ├── ReptTest.php │ │ │ │ ├── RightTest.php │ │ │ │ ├── SearchTest.php │ │ │ │ ├── SubstituteTest.php │ │ │ │ ├── TTest.php │ │ │ │ ├── TextAfterTest.php │ │ │ │ ├── TextBeforeTest.php │ │ │ │ ├── TextJoinTest.php │ │ │ │ ├── TextSplitTest.php │ │ │ │ ├── TextTest.php │ │ │ │ ├── TrimTest.php │ │ │ │ ├── UnicharTest.php │ │ │ │ ├── UnicodeTest.php │ │ │ │ ├── UpperTest.php │ │ │ │ ├── ValueTest.php │ │ │ │ └── ValueToTextTest.php │ │ │ └── Web/ │ │ │ ├── UrlEncodeTest.php │ │ │ └── WebServiceTest.php │ │ ├── FunctionsTest.php │ │ ├── InternalFunctionsTest.php │ │ ├── Issue4451Test.php │ │ ├── Issue4656Test.php │ │ ├── Issue606Test.php │ │ ├── MergedCellTest.php │ │ ├── MissingArgumentsTest.php │ │ ├── NullEqualsZeroTest.php │ │ ├── ParseFormulaTest.php │ │ ├── RefErrorTest.php │ │ ├── RowColumnReferenceTest.php │ │ ├── StringLengthTest.php │ │ ├── StructuredReferenceFormulaTest.php │ │ ├── TranslationTest.php │ │ └── XlfnFunctionsTest.php │ ├── Cell/ │ │ ├── AddressHelperTest.php │ │ ├── AddressRangeTest.php │ │ ├── AdvancedValueBinderTest.php │ │ ├── CellAddressTest.php │ │ ├── CellArrayFormulaTest.php │ │ ├── CellDetachTest.php │ │ ├── CellFormulaTest.php │ │ ├── CellRangeTest.php │ │ ├── CellTest.php │ │ ├── ColumnRangeTest.php │ │ ├── ConvertSpecialArrayTest.php │ │ ├── CoordinateTest.php │ │ ├── DataType2Test.php │ │ ├── DataTypeTest.php │ │ ├── DataValidationTest.php │ │ ├── DataValidator2Test.php │ │ ├── DataValidator3Test.php │ │ ├── DataValidatorTest.php │ │ ├── DefaultValueBinderTest.php │ │ ├── Hyperlink2Test.php │ │ ├── HyperlinkTest.php │ │ ├── RowRangeTest.php │ │ ├── SetValueExplicitCellTest.php │ │ ├── StringValueBinder2Test.php │ │ ├── StringValueBinderTest.php │ │ ├── StringableObject.php │ │ └── ValueBinderWithOverriddenDataTypeForValue.php │ ├── CellReferenceHelperTest.php │ ├── Chart/ │ │ ├── AxisGlowTest.php │ │ ├── AxisPropertiesTest.php │ │ ├── AxisShadowTest.php │ │ ├── BarChartCustomColorsTest.php │ │ ├── ChartBorderTest.php │ │ ├── ChartCloneTest.php │ │ ├── ChartMethodTest.php │ │ ├── Charts32CatAxValAxTest.php │ │ ├── Charts32ColoredAxisLabelTest.php │ │ ├── Charts32DsvGlowTest.php │ │ ├── Charts32DsvLabelsTest.php │ │ ├── Charts32ScatterTest.php │ │ ├── Charts32XmlTest.php │ │ ├── ChartsByNameTest.php │ │ ├── ChartsDynamicTitleTest.php │ │ ├── ChartsOpenpyxlTest.php │ │ ├── ChartsTitleTest.php │ │ ├── ColorTest.php │ │ ├── DataSeriesColorTest.php │ │ ├── DataSeriesValues2Test.php │ │ ├── DataSeriesValuesTest.php │ │ ├── DisplayBlanksAsTest.php │ │ ├── GridlinesLineStyleTest.php │ │ ├── GridlinesShadowGlowTest.php │ │ ├── Issue2077Test.php │ │ ├── Issue2506Test.php │ │ ├── Issue2931Test.php │ │ ├── Issue2965Test.php │ │ ├── Issue316Test.php │ │ ├── Issue3397Test.php │ │ ├── Issue3833Test.php │ │ ├── Issue4201Test.php │ │ ├── Issue562Test.php │ │ ├── Issue589Test.php │ │ ├── LayoutEffectsTest.php │ │ ├── LayoutTest.php │ │ ├── LegendColorTest.php │ │ ├── LegendTest.php │ │ ├── LineStylesTest.php │ │ ├── MultiplierTest.php │ │ ├── PR3163Test.php │ │ ├── PieFillTest.php │ │ ├── PlotAreaTest.php │ │ ├── RenderTest.php │ │ ├── RoundedCornersTest.php │ │ ├── ShadowPresetsTest.php │ │ ├── TitleTest.php │ │ └── TrendLineTest.php │ ├── Collection/ │ │ ├── Cells2Test.php │ │ ├── CellsTest.php │ │ └── SimpleCache3xxx.php │ ├── CommentTest.php │ ├── Custom/ │ │ └── ComplexAssert.php │ ├── CustomReader.php │ ├── CustomWriter.php │ ├── DefinedNameFormulaTest.php │ ├── DefinedNameTest.php │ ├── Document/ │ │ ├── EpochTest.php │ │ ├── PropertiesTest.php │ │ └── SecurityTest.php │ ├── DocumentGeneratorTest.php │ ├── Features/ │ │ └── AutoFilter/ │ │ └── Xlsx/ │ │ └── BasicLoadTest.php │ ├── FloatImprecisionTest.php │ ├── Functional/ │ │ ├── AbstractFunctional.php │ │ ├── ActiveSheetTest.php │ │ ├── ArrayFunctionsCellTest.php │ │ ├── ArrayFunctionsSpillTest.php │ │ ├── ColumnWidthTest.php │ │ ├── CommentsTest.php │ │ ├── ConditionalStopIfTrueTest.php │ │ ├── ConditionalTextTest.php │ │ ├── DrawingImageHyperlinkTest.php │ │ ├── EnclosureTest.php │ │ ├── FreezePaneTest.php │ │ ├── MergedCellsTest.php │ │ ├── PrintAreaTest.php │ │ ├── ReadBlankCellsTest.php │ │ ├── ReadFilterFilter.php │ │ ├── ReadFilterTest.php │ │ ├── SelectedCellsTest.php │ │ ├── StreamTest.php │ │ ├── TypeAttributePreservationTest.php │ │ └── WorkbookViewAttributesTest.php │ ├── HashTableTest.php │ ├── Helper/ │ │ ├── DimensionTest.php │ │ ├── HandlerTest.php │ │ ├── HtmlTest.php │ │ ├── SampleCoverageTest.php │ │ ├── SampleTest.php │ │ ├── TextGridExtended.php │ │ └── TextGridTest.php │ ├── IOFactoryRegisterTest.php │ ├── IOFactoryTest.php │ ├── Issue1449Test.php │ ├── Issue4521Test.php │ ├── NamedFormulaTest.php │ ├── NamedRange2Test.php │ ├── NamedRange3Test.php │ ├── NamedRangeTest.php │ ├── Reader/ │ │ ├── BaseNoLoad.php │ │ ├── BaseNoLoadTest.php │ │ ├── CreateBlankSheetIfNoneReadTest.php │ │ ├── Csv/ │ │ │ ├── BinderTest.php │ │ │ ├── CsvCallbackTest.php │ │ │ ├── CsvContiguousFilter.php │ │ │ ├── CsvContiguousTest.php │ │ │ ├── CsvEncodingTest.php │ │ │ ├── CsvIssue2232Test.php │ │ │ ├── CsvIssue2840Test.php │ │ │ ├── CsvLineEndingTest.php │ │ │ ├── CsvLoadFromStringTest.php │ │ │ ├── CsvNumberFormatLocaleTest.php │ │ │ ├── CsvNumberFormatTest.php │ │ │ ├── CsvTest.php │ │ │ ├── NotHtmlTest.php │ │ │ └── Php9Test.php │ │ ├── Gnumeric/ │ │ │ ├── ArrayFormula2Test.php │ │ │ ├── ArrayFormulaTest.php │ │ │ ├── AutoFilterTest.php │ │ │ ├── DefinedNameTest.php │ │ │ ├── GnumericFilter.php │ │ │ ├── GnumericInfoTest.php │ │ │ ├── GnumericLoadTest.php │ │ │ ├── GnumericStylesTest.php │ │ │ ├── HiddenWorksheetTest.php │ │ │ └── PageSetupTest.php │ │ ├── Html/ │ │ │ ├── BinderTest.php │ │ │ ├── DataFormulaTest.php │ │ │ ├── DirectionTest.php │ │ │ ├── HtmlBorderTest.php │ │ │ ├── HtmlCharsetTest.php │ │ │ ├── HtmlExtend.php │ │ │ ├── HtmlHelper.php │ │ │ ├── HtmlImage2Test.php │ │ │ ├── HtmlImageTest.php │ │ │ ├── HtmlLibxmlTest.php │ │ │ ├── HtmlLoadStringTest.php │ │ │ ├── HtmlPhpunit10Test.php │ │ │ ├── HtmlTagsTest.php │ │ │ ├── HtmlTest.php │ │ │ ├── Issue1107Test.php │ │ │ ├── Issue1284Test.php │ │ │ ├── Issue2029Test.php │ │ │ ├── Issue2810Test.php │ │ │ ├── Issue2942Test.php │ │ │ ├── OpacityTest.php │ │ │ ├── StyleCheckBoxTest.php │ │ │ └── ViewportTest.php │ │ ├── Ods/ │ │ │ ├── AlignmentStyleTest.php │ │ │ ├── ArrayFormulaTest.php │ │ │ ├── ArrayTest.php │ │ │ ├── AutoFilterTest.php │ │ │ ├── BooleanDataTest.php │ │ │ ├── BorderStyleTest.php │ │ │ ├── CeilingFloorTest.php │ │ │ ├── ColGroupTest.php │ │ │ ├── CurrencyTest.php │ │ │ ├── DefinedNamesTest.php │ │ │ ├── EmptyFileTest.php │ │ │ ├── FontStyleTest.php │ │ │ ├── FormulaTranslatorTest.php │ │ │ ├── HiddenMergeCellsTest.php │ │ │ ├── HiddenWorksheetTest.php │ │ │ ├── HyperlinkTest.php │ │ │ ├── InvalidFileTest.php │ │ │ ├── Issue2810Test.php │ │ │ ├── Issue3721Test.php │ │ │ ├── Issue4099Test.php │ │ │ ├── Issue4435Test.php │ │ │ ├── Issue804Test.php │ │ │ ├── MergeRangeTest.php │ │ │ ├── MultiLineCommentTest.php │ │ │ ├── NestedTableRowTest.php │ │ │ ├── NumberFormatCallbackTest.php │ │ │ ├── OdsInfoTest.php │ │ │ ├── OdsPropertiesTest.php │ │ │ ├── OdsTest.php │ │ │ ├── OldCalculatedTest.php │ │ │ ├── PageSetupBug1772Test.php │ │ │ ├── PageSetupTest.php │ │ │ ├── ProtectionStyleTest.php │ │ │ ├── RepeatEmptyCellsAndRowsTest.php │ │ │ └── RepeatedColumnsTest.php │ │ ├── Security/ │ │ │ └── XmlScannerTest.php │ │ ├── Slk/ │ │ │ ├── BinderTest.php │ │ │ ├── SlkCommentsTest.php │ │ │ ├── SlkSharedFormulasTest.php │ │ │ └── SlkTest.php │ │ ├── Utility/ │ │ │ └── File.php │ │ ├── Xls/ │ │ │ ├── Biff8CoverTest.php │ │ │ ├── ColorMapTest.php │ │ │ ├── ColourTest.php │ │ │ ├── ConditionalBorderTest.php │ │ │ ├── ConditionalFormattingBasicTest.php │ │ │ ├── ConditionalFormattingExpressionTest.php │ │ │ ├── ConditionalItalicTest.php │ │ │ ├── DataValidationTest.php │ │ │ ├── DateReaderTest.php │ │ │ ├── DefinedNameTest.php │ │ │ ├── ErrorCodeMapTest.php │ │ │ ├── FormulasTest.php │ │ │ ├── HiddenMergeCellsTest.php │ │ │ ├── HiddenWorksheetTest.php │ │ │ ├── InfoNamesTest.php │ │ │ ├── IsOddTest.php │ │ │ ├── Issue2463Test.php │ │ │ ├── Issue3202Test.php │ │ │ ├── Issue4356Test.php │ │ │ ├── LoadSheetsOnlyTest.php │ │ │ ├── Md5Test.php │ │ │ ├── NonExistentFileTest.php │ │ │ ├── NumberFormatGeneralTest.php │ │ │ ├── PageBreakTest.php │ │ │ ├── PageSetupTest.php │ │ │ ├── PasswordTest.php │ │ │ ├── Pr607Test.php │ │ │ ├── Rc4Test.php │ │ │ ├── RichTextSizeTest.php │ │ │ ├── SheetProtectionTest.php │ │ │ ├── WholeRowAndColumnTest.php │ │ │ ├── XlsBugPr3734Test.php │ │ │ ├── XlsSpecialCodePage.php │ │ │ └── XlsTest.php │ │ ├── Xlsx/ │ │ │ ├── AbsolutePathTest.php │ │ │ ├── AlignmentTest.php │ │ │ ├── ApostropheTest.php │ │ │ ├── AutoFilter2Test.php │ │ │ ├── AutoFilterEvaluateTest.php │ │ │ ├── AutoFilterTest.php │ │ │ ├── ChartSheetTest.php │ │ │ ├── ColorTabTest.php │ │ │ ├── CommentTest.php │ │ │ ├── CondNumFmtTest.php │ │ │ ├── ConditionalBorderTest.php │ │ │ ├── ConditionalColorScaleTest.php │ │ │ ├── ConditionalFormattingDataBarXlsxTest.php │ │ │ ├── ConditionalIconSetTest.php │ │ │ ├── ConditionalNoFormatSetTest.php │ │ │ ├── ConditionalPriority2Test.php │ │ │ ├── ConditionalPriorityTest.php │ │ │ ├── ConditionalTest.php │ │ │ ├── CoverageGapsTest.php │ │ │ ├── DataValidationBooleanValueTest.php │ │ │ ├── DataValidationTest.php │ │ │ ├── DateReaderTest.php │ │ │ ├── DefaultFillTest.php │ │ │ ├── DefaultFontTest.php │ │ │ ├── DirectorySeparatorTest.php │ │ │ ├── DrawingInCellTest.php │ │ │ ├── DrawingOneCellAnchorTest.php │ │ │ ├── EmptyFileTest.php │ │ │ ├── ExplicitDateTest.php │ │ │ ├── GridlinesTest.php │ │ │ ├── GroupByLimitedTest.php │ │ │ ├── HiddenMergeCellsTest.php │ │ │ ├── HiddenWorksheetTest.php │ │ │ ├── HyperlinkTest.php │ │ │ ├── IgnoredErrorTest.php │ │ │ ├── InvalidFileTest.php │ │ │ ├── Issue1482Test.php │ │ │ ├── Issue1637Test.php │ │ │ ├── Issue2301Test.php │ │ │ ├── Issue2331Test.php │ │ │ ├── Issue2362Test.php │ │ │ ├── Issue2387Test.php │ │ │ ├── Issue2450Test.php │ │ │ ├── Issue2488Test.php │ │ │ ├── Issue2490Test.php │ │ │ ├── Issue2494Test.php │ │ │ ├── Issue2501Test.php │ │ │ ├── Issue2516Test.php │ │ │ ├── Issue2542Test.php │ │ │ ├── Issue2581Test.php │ │ │ ├── Issue2778Test.php │ │ │ ├── Issue2885Test.php │ │ │ ├── Issue3126Test.php │ │ │ ├── Issue3145Test.php │ │ │ ├── Issue3277Test.php │ │ │ ├── Issue3435Test.php │ │ │ ├── Issue3464Test.php │ │ │ ├── Issue3495Test.php │ │ │ ├── Issue3534Test.php │ │ │ ├── Issue3552Test.php │ │ │ ├── Issue3553Test.php │ │ │ ├── Issue3613Test.php │ │ │ ├── Issue3665Test.php │ │ │ ├── Issue3679ImgTest.php │ │ │ ├── Issue3720Test.php │ │ │ ├── Issue3730Test.php │ │ │ ├── Issue3767Test.php │ │ │ ├── Issue3770Test.php │ │ │ ├── Issue3807Test.php │ │ │ ├── Issue3863Test.php │ │ │ ├── Issue3982Test.php │ │ │ ├── Issue4039Test.php │ │ │ ├── Issue4049Test.php │ │ │ ├── Issue4063Test.php │ │ │ ├── Issue4248Test.php │ │ │ ├── Issue4356Test.php │ │ │ ├── Issue4375Test.php │ │ │ ├── Issue4415Test.php │ │ │ ├── Issue4416Filter.php │ │ │ ├── Issue4416Test.php │ │ │ ├── Issue4477Test.php │ │ │ ├── Issue4505Test.php │ │ │ ├── Issue4629Test.php │ │ │ ├── Issue4800Test.php │ │ │ ├── Issue731Test.php │ │ │ ├── LoadSheetsOnlyTest.php │ │ │ ├── MySpreadsheet.php │ │ │ ├── MyXlsxReader.php │ │ │ ├── MyXlsxTest.php │ │ │ ├── NamedRangeTest.php │ │ │ ├── NamespaceIssue2109bTest.php │ │ │ ├── NamespaceNonStdTest.php │ │ │ ├── NamespaceOpenpyxl35Test.php │ │ │ ├── NamespacePurlTest.php │ │ │ ├── NamespaceStdTest.php │ │ │ ├── NumericCellTypeTest.php │ │ │ ├── OctothorpeTest.php │ │ │ ├── OddColumnReadFilter.php │ │ │ ├── OutlineTest.php │ │ │ ├── PageSetup2Test.php │ │ │ ├── PageSetupTest.php │ │ │ ├── PropertiesTest.php │ │ │ ├── ReadDynamTest.php │ │ │ ├── RgbTintTest.php │ │ │ ├── RibbonTest.php │ │ │ ├── RichTextTest.php │ │ │ ├── RowBreakTest.php │ │ │ ├── SharedFormulaTest.php │ │ │ ├── SharedFormulaeTest.php │ │ │ ├── SheetProtectionTest.php │ │ │ ├── SheetsXlsxChartTest.php │ │ │ ├── SplitsTest.php │ │ │ ├── TableTest.php │ │ │ ├── URLImageTest.php │ │ │ ├── UnderscoreTest.php │ │ │ ├── VerticalAlignTest.php │ │ │ ├── VmlTest.php │ │ │ ├── WorksheetInfoNamesTest.php │ │ │ ├── Xlsx2Test.php │ │ │ ├── XlsxRootZipFilesTest.php │ │ │ └── XlsxTest.php │ │ └── Xml/ │ │ ├── ArrayFormulaTest.php │ │ ├── DataValidationsTest.php │ │ ├── HtmlEntitiesLoadTest.php │ │ ├── Issue4448Test.php │ │ ├── PageSetupTest.php │ │ ├── ReadOrderTest.php │ │ ├── SplitsTest.php │ │ ├── XmlActiveSheetTest.php │ │ ├── XmlColSpanTest.php │ │ ├── XmlColumnRowHiddenTest.php │ │ ├── XmlFilter.php │ │ ├── XmlFontBoldItalicTest.php │ │ ├── XmlFreezePanesTest.php │ │ ├── XmlInfoTest.php │ │ ├── XmlIssue4000Test.php │ │ ├── XmlIssue4002Test.php │ │ ├── XmlLoadTest.php │ │ ├── XmlOddTest.php │ │ ├── XmlPropertiesTest.php │ │ ├── XmlProtectionTest.php │ │ ├── XmlRichTextTest.php │ │ ├── XmlStyleCoverageTest.php │ │ ├── XmlStylesTest.php │ │ ├── XmlTest.php │ │ └── XmlTopLeftTest.php │ ├── RefRangeTest.php │ ├── ReferenceHelper2Test.php │ ├── ReferenceHelper3Test.php │ ├── ReferenceHelper4Test.php │ ├── ReferenceHelper5Test.php │ ├── ReferenceHelperDVTest.php │ ├── ReferenceHelperTest.php │ ├── RichTextTest.php │ ├── SettingsTest.php │ ├── Shared/ │ │ ├── CodePageTest.php │ │ ├── Date2Test.php │ │ ├── DateTest.php │ │ ├── DgContainerTest.php │ │ ├── DggContainerTest.php │ │ ├── DrawingTest.php │ │ ├── ExactFontTest.php │ │ ├── FileTest.php │ │ ├── Font2Test.php │ │ ├── Font3Test.php │ │ ├── FontFileNameTest.php │ │ ├── FontTest.php │ │ ├── Issue1324Test.php │ │ ├── Issue347Test.php │ │ ├── Issue4696Test.php │ │ ├── OLEPhpunit10Test.php │ │ ├── OLEReadTest.php │ │ ├── OLETest.php │ │ ├── PasswordHasherTest.php │ │ ├── PasswordReloadTest.php │ │ ├── SpgrContainerTest.php │ │ ├── StringHelperInvalidCharTest.php │ │ ├── StringHelperLocale2Test.php │ │ ├── StringHelperLocaleTest.php │ │ ├── StringHelperNoIconv.php │ │ ├── StringHelperNoIconv2.php │ │ ├── StringHelperNoIconv3.php │ │ ├── StringHelperNoIntl.php │ │ ├── StringHelperTest.php │ │ ├── TimeZoneTest.php │ │ ├── Trend/ │ │ │ ├── BestFitTest.php │ │ │ ├── ExponentialBestFitTest.php │ │ │ └── LinearBestFitTest.php │ │ ├── XMLWriterNoUri.php │ │ ├── XlsTest.php │ │ └── XmlWriterTest.php │ ├── SpreadsheetCopyCloneTest.php │ ├── SpreadsheetCoverageTest.php │ ├── SpreadsheetDuplicateSheetTest.php │ ├── SpreadsheetSerializeTest.php │ ├── SpreadsheetTest.php │ ├── Style/ │ │ ├── AlignmentMiddleTest.php │ │ ├── AlignmentTest.php │ │ ├── BorderRangeTest.php │ │ ├── BorderTest.php │ │ ├── ColorIndexTest.php │ │ ├── ColorTest.php │ │ ├── ConditionalBoolTest.php │ │ ├── ConditionalFormatting/ │ │ │ ├── CellMatcherTest.php │ │ │ ├── PR3946Test.php │ │ │ └── Wizard/ │ │ │ ├── BlankWizardTest.php │ │ │ ├── CellValueWizardTest.php │ │ │ ├── DateValueWizardTest.php │ │ │ ├── DuplicatesWizardTest.php │ │ │ ├── ErrorWizardTest.php │ │ │ ├── ExpressionWizardTest.php │ │ │ ├── TextValueWizardTest.php │ │ │ └── WizardFactoryTest.php │ │ ├── ConditionalTest.php │ │ ├── ExportArrayTest.php │ │ ├── FillTest.php │ │ ├── FontTest.php │ │ ├── NumberFormat/ │ │ │ └── Wizard/ │ │ │ ├── AccountingTest.php │ │ │ ├── CurrencyTest.php │ │ │ ├── DateTest.php │ │ │ ├── DateTimeTest.php │ │ │ ├── DurationTest.php │ │ │ ├── NumberBase2.php │ │ │ ├── NumberTest.php │ │ │ ├── PercentageTest.php │ │ │ ├── ScientificTest.php │ │ │ └── TimeTest.php │ │ ├── NumberFormatBuiltinTest.php │ │ ├── NumberFormatFractionalSecondTest.php │ │ ├── NumberFormatRoundTest.php │ │ ├── NumberFormatSystemDateTimeTest.php │ │ ├── NumberFormatTest.php │ │ ├── ReplaceBuiltinNumberFormatTest.php │ │ └── StyleTest.php │ ├── Worksheet/ │ │ ├── ApplyStylesTest.php │ │ ├── AutoFilter/ │ │ │ ├── AutoFilterAverageTop10Test.php │ │ │ ├── AutoFilterCustomNumericTest.php │ │ │ ├── AutoFilterCustomTextTest.php │ │ │ ├── AutoFilterMonthTest.php │ │ │ ├── AutoFilterQuarterTest.php │ │ │ ├── AutoFilterTest.php │ │ │ ├── AutoFilterTodayTest.php │ │ │ ├── AutoFilterWeekTest.php │ │ │ ├── AutoFilterYearTest.php │ │ │ ├── ColumnTest.php │ │ │ ├── DateGroupTest.php │ │ │ ├── DeleteAutoFilterTest.php │ │ │ ├── RuleCustomTest.php │ │ │ ├── RuleDateGroupTest.php │ │ │ ├── RuleTest.php │ │ │ └── SetupTeardown.php │ │ ├── AutoSizeTest.php │ │ ├── ByColumnAndRowTest.php │ │ ├── ByColumnAndRowUndeprecatedTest.php │ │ ├── CloneTest.php │ │ ├── ColumnCellIterator2Test.php │ │ ├── ColumnCellIteratorTest.php │ │ ├── ColumnDimension2Test.php │ │ ├── ColumnDimension3Test.php │ │ ├── ColumnDimensionTest.php │ │ ├── ColumnIteratorEmptyTest.php │ │ ├── ColumnIteratorTest.php │ │ ├── ColumnRowStyleTest.php │ │ ├── ColumnTest.php │ │ ├── ConditionalIntersectionTest.php │ │ ├── ConditionalStyleTest.php │ │ ├── CopyCellsTest.php │ │ ├── DefaultPaperSizeTest.php │ │ ├── DrawingTest.php │ │ ├── InsertTest.php │ │ ├── Issue1203Test.php │ │ ├── Issue1425Test.php │ │ ├── Issue1457Test.php │ │ ├── Issue4112Test.php │ │ ├── Issue4128Test.php │ │ ├── Issue4241Test.php │ │ ├── Issue641Test.php │ │ ├── IteratorTest.php │ │ ├── MemoryDrawing2.php │ │ ├── MemoryDrawingTest.php │ │ ├── MergeBehaviourTest.php │ │ ├── MergeCellsDeletedTest.php │ │ ├── PageBreakTest.php │ │ ├── PageMarginsTest.php │ │ ├── PrintAreaTest.php │ │ ├── ProtectedRangeTest.php │ │ ├── Protection2Test.php │ │ ├── ProtectionTest.php │ │ ├── RemoveTest.php │ │ ├── RowCellIterator2Test.php │ │ ├── RowCellIteratorTest.php │ │ ├── RowDimensionSaveTest.php │ │ ├── RowDimensionTest.php │ │ ├── RowIteratorEmptyTest.php │ │ ├── RowIteratorTest.php │ │ ├── RowTest.php │ │ ├── SetValueExplicitWorksheetTest.php │ │ ├── SheetViewTest.php │ │ ├── Table/ │ │ │ ├── ColumnTest.php │ │ │ ├── FormulaTest.php │ │ │ ├── Issue3635Test.php │ │ │ ├── Issue3659Test.php │ │ │ ├── Issue3820Test.php │ │ │ ├── RemoveTableTest.php │ │ │ ├── SetupTeardown.php │ │ │ ├── TableStyleTest.php │ │ │ └── TableTest.php │ │ ├── ToArrayOldCalculatedValueTest.php │ │ ├── ToArrayTest.php │ │ ├── Worksheet2Test.php │ │ ├── Worksheet3Test.php │ │ ├── WorksheetNamedRangesTest.php │ │ ├── WorksheetParentTest.php │ │ └── WorksheetTest.php │ └── Writer/ │ ├── Csv/ │ │ ├── CsvArrayTest.php │ │ ├── CsvEnclosureTest.php │ │ ├── CsvExcelCompatibilityTest.php │ │ ├── CsvOutputEncodingTest.php │ │ ├── CsvWriteTest.php │ │ ├── HyperlinkTest.php │ │ └── VariableColumnsTest.php │ ├── Dompdf/ │ │ ├── GridlinesInlineTest.php │ │ ├── HideMergeTest.php │ │ ├── HideTest.php │ │ ├── PaperSizeArrayTest.php │ │ ├── PrintAreaTest.php │ │ └── TextRotationTest.php │ ├── Html/ │ │ ├── AllOrOneSheetTest.php │ │ ├── BackgroundImageTest.php │ │ ├── BadCustomPropertyTest.php │ │ ├── BadHyperlinkBaseTest.php │ │ ├── BadHyperlinkTest.php │ │ ├── BetterBooleanTest.php │ │ ├── CalcErrorTest.php │ │ ├── CallbackTest.php │ │ ├── CommentAlignmentTest.php │ │ ├── DirectionTest.php │ │ ├── ExtendForChartsAndImagesTest.php │ │ ├── FixHeightTest.php │ │ ├── FloatInlineTest.php │ │ ├── GridlinesInlineTest.php │ │ ├── GridlinesTest.php │ │ ├── HideMergeTest.php │ │ ├── HideTest.php │ │ ├── HtmlArrayTest.php │ │ ├── HtmlColourScaleTest.php │ │ ├── HtmlCommentsTest.php │ │ ├── HtmlConditionalFormattingTest.php │ │ ├── HtmlDifferentConditionalFormattingsTest.php │ │ ├── HtmlExtend2.php │ │ ├── HtmlNumberFormatTest.php │ │ ├── HtmlTableFormatTest.php │ │ ├── HtmlTableFormatWithConditionalTest.php │ │ ├── ImageCopyTest.php │ │ ├── ImageEmbedTest.php │ │ ├── ImagesRootTest.php │ │ ├── InvalidFileNameTest.php │ │ ├── Issue1319Test.php │ │ ├── Issue3678Test.php │ │ ├── Issue4539Test.php │ │ ├── Issue4773Test.php │ │ ├── LineEndingTest.php │ │ ├── LongTitleTest.php │ │ ├── MailtoTest.php │ │ ├── MemoryDrawingOffsetTest.php │ │ ├── NavigationBadTitleTest.php │ │ ├── NoJavascriptLinksTest.php │ │ ├── NoTitleTest.php │ │ ├── PrintAreaTest.php │ │ ├── ReadOrderTest.php │ │ ├── RepeatedRowsTest.php │ │ ├── RichTextTest.php │ │ ├── TextRotationTest.php │ │ ├── TransparentDrawingsTest.php │ │ ├── VisibilityTest.php │ │ └── XssVulnerabilityTest.php │ ├── Mpdf/ │ │ ├── GridlinesInlineTest.php │ │ ├── HideMergeTest.php │ │ ├── HideTest.php │ │ ├── ImageCopyPdfTest.php │ │ ├── Issue4773Test.php │ │ ├── MergedBorderTest.php │ │ ├── OrientationTest.php │ │ ├── PrintAreaTest.php │ │ └── TextRotationTest.php │ ├── Ods/ │ │ ├── ArrayTest.php │ │ ├── AutoColorTest.php │ │ ├── AutoFilterTest.php │ │ ├── ContentTest.php │ │ ├── DefinedNamesTest.php │ │ ├── DurationTest.php │ │ ├── FreezeTest.php │ │ ├── IndentTest.php │ │ ├── Issue4537Test.php │ │ ├── Issue4584Test.php │ │ ├── Issue4798Test.php │ │ ├── MergeRangeTest.php │ │ ├── MicrosecondsTest.php │ │ └── ReadOrderTest.php │ ├── PreCalcTest.php │ ├── RetainSelectedCellsTest.php │ ├── Tcpdf/ │ │ ├── GridlinesInlineTest.php │ │ ├── HideMergeTest.php │ │ ├── HideTest.php │ │ ├── MergedBorderTest.php │ │ ├── MergedCellTest.php │ │ ├── NoDieTest.php │ │ └── PrintAreaTest.php │ ├── Xls/ │ │ ├── BooleanLiteralTest.php │ │ ├── Calendar1904Test.php │ │ ├── ConditionalFontColorTest.php │ │ ├── ConditionalLimitsTest.php │ │ ├── ConditionalUnionTest.php │ │ ├── DataValidationTest.php │ │ ├── DimensionsRecordTest.php │ │ ├── FormulaErrTest.php │ │ ├── HyperlinkTest.php │ │ ├── Issue4331Test.php │ │ ├── Issue4584Test.php │ │ ├── Issue642Test.php │ │ ├── Issue918Test.php │ │ ├── MicrosecondsTest.php │ │ ├── NonLatinFormulasTest.php │ │ ├── ParserTest.php │ │ ├── ReadOrderTest.php │ │ ├── RichTextTest.php │ │ ├── Sample19Test.php │ │ ├── VisibilityTest.php │ │ ├── WorkbookTest.php │ │ └── XlsGifBmpTest.php │ └── Xlsx/ │ ├── ArrayFormulaPrefixTest.php │ ├── ArrayFormulaValidationTest.php │ ├── ArrayFunctions2Test.php │ ├── ArrayFunctionsInlineTest.php │ ├── ArrayFunctionsTest.php │ ├── AutoColorTest.php │ ├── BackgroundImageTest.php │ ├── BadParamExceptionTest.php │ ├── CalculationErrorTest.php │ ├── Calendar1904Test.php │ ├── CheckBoxStyleTest.php │ ├── CommentAlignmentTest.php │ ├── ConditionalFillTest.php │ ├── ConditionalFormatIconSetTest.php │ ├── ConditionalTest.php │ ├── DataValidationTest.php │ ├── DrawingInCellTest.php │ ├── DrawingPassThroughTest.php │ ├── DrawingsInsertRowsTest.php │ ├── DrawingsTest.php │ ├── ExplicitStyle0Test.php │ ├── FloatsRetainedTest.php │ ├── FontCharsetTest.php │ ├── FunctionPrefixTest.php │ ├── HyperlinkTest.php │ ├── Issue2082Test.php │ ├── Issue2266Test.php │ ├── Issue2368Test.php │ ├── Issue3443Test.php │ ├── Issue3711Test.php │ ├── Issue3843Test.php │ ├── Issue3951Test.php │ ├── Issue3988Test.php │ ├── Issue4025Test.php │ ├── Issue4179Test.php │ ├── Issue4200Test.php │ ├── Issue4269Test.php │ ├── Issue4537Test.php │ ├── Issue4542Test.php │ ├── Issue4584Test.php │ ├── Issue476Test.php │ ├── Issue484Test.php │ ├── Issue993Test.php │ ├── LocaleFloatsTest.php │ ├── MemoryDrawingTest.php │ ├── MetadataTest.php │ ├── MicrosecondsTest.php │ ├── PageBreakTest.php │ ├── RichTextTest.php │ ├── StartsWithHashTest.php │ ├── StylesWriterTest.php │ ├── TableTest.php │ ├── ThemeColorsTest.php │ ├── ThemeFontsTest.php │ ├── TransparentDrawingsTest.php │ ├── Unparsed2396Test.php │ ├── UnparsedDataCloneTest.php │ ├── UnparsedDataTest.php │ ├── VisibilityTest.php │ └── WmfTest.php ├── bootstrap.php └── data/ ├── Calculation/ │ ├── BinaryComparisonOperations.php │ ├── Calculation.php │ ├── DateTime/ │ │ ├── DATE.php │ │ ├── DATEDIF.php │ │ ├── DATEVALUE.php │ │ ├── DAY.php │ │ ├── DAYOpenOffice.php │ │ ├── DAYS.php │ │ ├── DAYS360.php │ │ ├── EDATE.php │ │ ├── EOMONTH.php │ │ ├── HOUR.php │ │ ├── ISOWEEKNUM.php │ │ ├── ISOWEEKNUM1904.php │ │ ├── MINUTE.php │ │ ├── MONTH.php │ │ ├── NETWORKDAYS.php │ │ ├── SECOND.php │ │ ├── TIME.php │ │ ├── TIMEVALUE.php │ │ ├── WEEKDAY.php │ │ ├── WEEKNUM.php │ │ ├── WEEKNUM1904.php │ │ ├── WORKDAY.php │ │ ├── YEAR.php │ │ └── YEARFRAC.php │ ├── DefinedNames/ │ │ ├── NamedFormulae.xlsx │ │ └── NamedRanges.xlsx │ ├── Engineering/ │ │ ├── BESSELI.php │ │ ├── BESSELJ.php │ │ ├── BESSELK.php │ │ ├── BESSELY.php │ │ ├── BIN2DEC.php │ │ ├── BIN2DECOpenOffice.php │ │ ├── BIN2HEX.php │ │ ├── BIN2HEXOpenOffice.php │ │ ├── BIN2OCT.php │ │ ├── BIN2OCTOpenOffice.php │ │ ├── BITAND.php │ │ ├── BITLSHIFT.php │ │ ├── BITOR.php │ │ ├── BITRSHIFT.php │ │ ├── BITXOR.php │ │ ├── COMPLEX.php │ │ ├── CONVERTUOM.php │ │ ├── DEC2BIN.php │ │ ├── DEC2BINOpenOffice.php │ │ ├── DEC2HEX.php │ │ ├── DEC2HEXOpenOffice.php │ │ ├── DEC2OCT.php │ │ ├── DEC2OCTOpenOffice.php │ │ ├── DELTA.php │ │ ├── ERF.php │ │ ├── ERFC.php │ │ ├── ERFPRECISE.php │ │ ├── GESTEP.php │ │ ├── HEX2BIN.php │ │ ├── HEX2BINOpenOffice.php │ │ ├── HEX2DEC.php │ │ ├── HEX2DECOpenOffice.php │ │ ├── HEX2OCT.php │ │ ├── HEX2OCTOpenOffice.php │ │ ├── IMABS.php │ │ ├── IMAGINARY.php │ │ ├── IMARGUMENT.php │ │ ├── IMCONJUGATE.php │ │ ├── IMCOS.php │ │ ├── IMCOSH.php │ │ ├── IMCOT.php │ │ ├── IMCSC.php │ │ ├── IMCSCH.php │ │ ├── IMDIV.php │ │ ├── IMEXP.php │ │ ├── IMLN.php │ │ ├── IMLOG10.php │ │ ├── IMLOG2.php │ │ ├── IMPOWER.php │ │ ├── IMPRODUCT.php │ │ ├── IMREAL.php │ │ ├── IMSEC.php │ │ ├── IMSECH.php │ │ ├── IMSIN.php │ │ ├── IMSINH.php │ │ ├── IMSQRT.php │ │ ├── IMSUB.php │ │ ├── IMSUM.php │ │ ├── IMTAN.php │ │ ├── OCT2BIN.php │ │ ├── OCT2BINOpenOffice.php │ │ ├── OCT2DEC.php │ │ ├── OCT2DECOpenOffice.php │ │ ├── OCT2HEX.php │ │ └── OCT2HEXOpenOffice.php │ ├── Financial/ │ │ ├── ACCRINT.php │ │ ├── ACCRINTM.php │ │ ├── AMORDEGRC.php │ │ ├── AMORLINC.php │ │ ├── COUPDAYBS.php │ │ ├── COUPDAYS.php │ │ ├── COUPDAYSNC.php │ │ ├── COUPNCD.php │ │ ├── COUPNUM.php │ │ ├── COUPPCD.php │ │ ├── CUMIPMT.php │ │ ├── CUMPRINC.php │ │ ├── DB.php │ │ ├── DDB.php │ │ ├── DISC.php │ │ ├── DOLLARDE.php │ │ ├── DOLLARFR.php │ │ ├── DaysPerYear.php │ │ ├── EFFECT.php │ │ ├── FV.php │ │ ├── FVSCHEDULE.php │ │ ├── INTRATE.php │ │ ├── IPMT.php │ │ ├── IRR.php │ │ ├── ISPMT.php │ │ ├── MIRR.php │ │ ├── NOMINAL.php │ │ ├── NPER.php │ │ ├── NPV.php │ │ ├── PDURATION.php │ │ ├── PMT.php │ │ ├── PPMT.php │ │ ├── PRICE.php │ │ ├── PRICE3.php │ │ ├── PRICEDISC.php │ │ ├── PRICEMAT.php │ │ ├── PV.php │ │ ├── RATE.php │ │ ├── RECEIVED.php │ │ ├── RRI.php │ │ ├── SLN.php │ │ ├── SYD.php │ │ ├── TBILLEQ.php │ │ ├── TBILLPRICE.php │ │ ├── TBILLYIELD.php │ │ ├── USDOLLAR.php │ │ ├── XIRR.php │ │ ├── XNPV.php │ │ ├── YIELDDISC.php │ │ └── YIELDMAT.php │ ├── Functions/ │ │ └── IF_CONDITION.php │ ├── FunctionsAsString.php │ ├── Information/ │ │ ├── ERROR_TYPE.php │ │ ├── INFO.php │ │ ├── IS_BLANK.php │ │ ├── IS_ERR.php │ │ ├── IS_ERROR.php │ │ ├── IS_EVEN.php │ │ ├── IS_LOGICAL.php │ │ ├── IS_NA.php │ │ ├── IS_NONTEXT.php │ │ ├── IS_NUMBER.php │ │ ├── IS_ODD.php │ │ ├── IS_TEXT.php │ │ ├── N.php │ │ └── TYPE.php │ ├── Logical/ │ │ ├── AND.php │ │ ├── ANDLiteral.php │ │ ├── IF.php │ │ ├── IFERROR.php │ │ ├── IFNA.php │ │ ├── IFS.php │ │ ├── NOT.php │ │ ├── OR.php │ │ ├── ORLiteral.php │ │ ├── SWITCH.php │ │ ├── XOR.php │ │ └── XORLiteral.php │ ├── LookupRef/ │ │ ├── ADDRESS.php │ │ ├── CHOOSE.php │ │ ├── CHOOSECOLS.php │ │ ├── CHOOSEROWS.php │ │ ├── COLUMN.php │ │ ├── COLUMNS.php │ │ ├── COLUMNSonSpreadsheet.php │ │ ├── COLUMNonSpreadsheet.php │ │ ├── DROP.php │ │ ├── EXPAND.php │ │ ├── FORMULATEXT.php │ │ ├── HLOOKUP.php │ │ ├── HYPERLINK.php │ │ ├── INDEX.php │ │ ├── INDEXonSpreadsheet.php │ │ ├── INDIRECT.php │ │ ├── IndirectDefinedName.xlsx │ │ ├── IndirectFormulaSelection.xlsx │ │ ├── LOOKUP.php │ │ ├── MATCH.php │ │ ├── OFFSET.php │ │ ├── ROW.php │ │ ├── ROWS.php │ │ ├── ROWSonSpreadsheet.php │ │ ├── ROWonSpreadsheet.php │ │ ├── TAKE.php │ │ ├── TRANSPOSE.php │ │ └── VLOOKUP.php │ ├── MathTrig/ │ │ ├── ABS.php │ │ ├── ACOS.php │ │ ├── ACOSH.php │ │ ├── ACOT.php │ │ ├── ACOTH.php │ │ ├── ARABIC.php │ │ ├── ASIN.php │ │ ├── ASINH.php │ │ ├── ATAN.php │ │ ├── ATAN2.php │ │ ├── ATANH.php │ │ ├── BASE.php │ │ ├── CEILING.php │ │ ├── CEILINGMATH.php │ │ ├── CEILINGPRECISE.php │ │ ├── COMBIN.php │ │ ├── COMBINA.php │ │ ├── COS.php │ │ ├── COSH.php │ │ ├── COT.php │ │ ├── COTH.php │ │ ├── CSC.php │ │ ├── CSCH.php │ │ ├── DEGREES.php │ │ ├── EVEN.php │ │ ├── EXP.php │ │ ├── FACT.php │ │ ├── FACTDOUBLE.php │ │ ├── FACTGNUMERIC.php │ │ ├── FLOOR.php │ │ ├── FLOORMATH.php │ │ ├── FLOORPRECISE.php │ │ ├── GCD.php │ │ ├── INT.php │ │ ├── LCM.php │ │ ├── LN.php │ │ ├── LOG.php │ │ ├── LOG10.php │ │ ├── MDETERM.php │ │ ├── MINVERSE.php │ │ ├── MMULT.php │ │ ├── MOD.php │ │ ├── MROUND.php │ │ ├── MULTINOMIAL.php │ │ ├── ODD.php │ │ ├── PI.php │ │ ├── POWER.php │ │ ├── PRODUCT.php │ │ ├── QUOTIENT.php │ │ ├── RADIANS.php │ │ ├── RANDBETWEEN.php │ │ ├── ROMAN.php │ │ ├── ROUND.php │ │ ├── ROUNDDOWN.php │ │ ├── ROUNDUP.php │ │ ├── SEC.php │ │ ├── SECH.php │ │ ├── SEQUENCE.php │ │ ├── SERIESSUM.php │ │ ├── SIGN.php │ │ ├── SIN.php │ │ ├── SINH.php │ │ ├── SQRT.php │ │ ├── SQRTPI.php │ │ ├── SUBTOTAL.php │ │ ├── SUBTOTALHIDDEN.php │ │ ├── SUM.php │ │ ├── SUMIF.php │ │ ├── SUMIFS.php │ │ ├── SUMLITERALS.php │ │ ├── SUMPRODUCT.php │ │ ├── SUMSQ.php │ │ ├── SUMWITHINDEXMATCH.php │ │ ├── SUMX2MY2.php │ │ ├── SUMX2PY2.php │ │ ├── SUMXMY2.php │ │ ├── TAN.php │ │ ├── TANH.php │ │ └── TRUNC.php │ ├── Statistical/ │ │ ├── AVEDEV.php │ │ ├── AVERAGE.php │ │ ├── AVERAGEA.php │ │ ├── AVERAGEIF.php │ │ ├── AVERAGEIFS.php │ │ ├── BETADIST.php │ │ ├── BETAINV.php │ │ ├── BINOMDIST.php │ │ ├── BINOMDISTRANGE.php │ │ ├── BINOMINV.php │ │ ├── BasicCOUNT.php │ │ ├── CHIDISTLeftTail.php │ │ ├── CHIDISTRightTail.php │ │ ├── CHIINVLeftTail.php │ │ ├── CHIINVRightTail.php │ │ ├── CHITEST.php │ │ ├── CONFIDENCE.php │ │ ├── CORREL.php │ │ ├── COUNTA.php │ │ ├── COUNTBLANK.php │ │ ├── COUNTIF.php │ │ ├── COUNTIFS.php │ │ ├── COVAR.php │ │ ├── DEVSQ.php │ │ ├── EXPONDIST.php │ │ ├── ExcelCOUNT.php │ │ ├── FDIST.php │ │ ├── FISHER.php │ │ ├── FISHERINV.php │ │ ├── FORECAST.php │ │ ├── GAMMA.php │ │ ├── GAMMADIST.php │ │ ├── GAMMAINV.php │ │ ├── GAMMALN.php │ │ ├── GAUSS.php │ │ ├── GEOMEAN.php │ │ ├── GROWTH.php │ │ ├── GnumericCOUNT.php │ │ ├── HARMEAN.php │ │ ├── HYPGEOMDIST.php │ │ ├── INTERCEPT.php │ │ ├── KURT.php │ │ ├── LARGE.php │ │ ├── LINEST.php │ │ ├── LOGEST.php │ │ ├── LOGINV.php │ │ ├── LOGNORMDIST.php │ │ ├── LOGNORMDIST2.php │ │ ├── MAX.php │ │ ├── MAXA.php │ │ ├── MAXIFS.php │ │ ├── MEDIAN.php │ │ ├── MIN.php │ │ ├── MINA.php │ │ ├── MINIFS.php │ │ ├── MODE.php │ │ ├── NEGBINOMDIST.php │ │ ├── NORMDIST.php │ │ ├── NORMINV.php │ │ ├── NORMSDIST.php │ │ ├── NORMSDIST2.php │ │ ├── NORMSINV.php │ │ ├── OpenOfficeCOUNT.php │ │ ├── PERCENTILE.php │ │ ├── PERCENTRANK.php │ │ ├── PERMUT.php │ │ ├── PERMUTATIONA.php │ │ ├── POISSON.php │ │ ├── QUARTILE.php │ │ ├── RANK.php │ │ ├── RSQ.php │ │ ├── SKEW.php │ │ ├── SLOPE.php │ │ ├── SMALL.php │ │ ├── STANDARDIZE.php │ │ ├── STDEV.php │ │ ├── STDEVA.php │ │ ├── STDEVA_ODS.php │ │ ├── STDEVP.php │ │ ├── STDEVPA.php │ │ ├── STDEVPA_ODS.php │ │ ├── STDEVP_ODS.php │ │ ├── STDEV_ODS.php │ │ ├── STEYX.php │ │ ├── TDIST.php │ │ ├── TDIST2T.php │ │ ├── TDISTRT.php │ │ ├── TINV.php │ │ ├── TREND.php │ │ ├── TRIMMEAN.php │ │ ├── TdotINV.php │ │ ├── VAR.php │ │ ├── VARA.php │ │ ├── VARA_ODS.php │ │ ├── VARP.php │ │ ├── VARPA.php │ │ ├── VARPA_ODS.php │ │ ├── VARP_ODS.php │ │ ├── VAR_ODS.php │ │ ├── WEIBULL.php │ │ ├── ZTEST.php │ │ ├── tDotDistFalse.php │ │ └── tDotDistTrue.php │ ├── TableFormulae.xlsx │ ├── TextData/ │ │ ├── ARRAYTOTEXT.php │ │ ├── BAHTTEXT.php │ │ ├── CHAR.php │ │ ├── CLEAN.php │ │ ├── CODE.php │ │ ├── CONCAT.php │ │ ├── CONCATENATE.php │ │ ├── DOLLAR.php │ │ ├── EXACT.php │ │ ├── FIND.php │ │ ├── FIXED.php │ │ ├── LEFT.php │ │ ├── LEN.php │ │ ├── LOWER.php │ │ ├── MID.php │ │ ├── NUMBERVALUE.php │ │ ├── OpenOffice.php │ │ ├── PROPER.php │ │ ├── REPLACE.php │ │ ├── REPT.php │ │ ├── RIGHT.php │ │ ├── SEARCH.php │ │ ├── SUBSTITUTE.php │ │ ├── T.php │ │ ├── TEXT.php │ │ ├── TEXTAFTER.php │ │ ├── TEXTBEFORE.php │ │ ├── TEXTJOIN.php │ │ ├── TEXTSPLIT.php │ │ ├── TRIM.php │ │ ├── UPPER.php │ │ ├── VALUE.php │ │ └── VALUETOTEXT.php │ ├── Translations.php │ └── Web/ │ ├── URLENCODE.php │ └── WEBSERVICE.php ├── CalculationBinaryComparisonOperation.php ├── Cell/ │ ├── A1ConversionToR1C1Absolute.php │ ├── A1ConversionToR1C1Exception.php │ ├── A1ConversionToR1C1Relative.php │ ├── ConvertFormulaToA1FromR1C1Absolute.php │ ├── ConvertFormulaToA1FromR1C1Relative.php │ ├── ConvertFormulaToA1FromSpreadsheetXml.php │ ├── CoordinateIsInsideRange.php │ ├── CoordinateIsInsideRangeException.php │ ├── IndexesFromString.php │ ├── R1C1ConversionToA1Absolute.php │ ├── R1C1ConversionToA1Exception.php │ ├── R1C1ConversionToA1Relative.php │ ├── SetValueExplicit.php │ ├── SetValueExplicitException.php │ └── SetValueExplicitTypeArguments.php ├── CellAbsoluteCoordinate.php ├── CellAbsoluteReference.php ├── CellBuildRange.php ├── CellCoordinates.php ├── CellExtractAllCellReferencesInRange.php ├── CellGetRangeBoundaries.php ├── CellMergeRangesInCollection.php ├── CellRangeBoundaries.php ├── CellRangeDimension.php ├── CellSplitRange.php ├── ColumnIndex.php ├── ColumnString.php ├── CoordinateIsRange.php ├── Features/ │ └── AutoFilter/ │ └── Xlsx/ │ ├── AutoFilter_Basic.xlsx │ └── AutoFilter_Basic_Office365.xlsx ├── Functional/ │ └── TypeAttributePreservation/ │ └── Formula.php ├── Reader/ │ ├── CSV/ │ │ ├── NumberFormatTest.csv │ │ ├── NumberFormatTest.de.csv │ │ ├── backslash.csv │ │ ├── contains_html.csv │ │ ├── csv_without_extension │ │ ├── empty.csv │ │ ├── enclosure.csv │ │ ├── encoding.iso88591.csv │ │ ├── encoding.utf16be.csv │ │ ├── encoding.utf16le.csv │ │ ├── encoding.utf32be.csv │ │ ├── encoding.utf32le.csv │ │ ├── encoding.utf8.csv │ │ ├── encoding.utf8bom.csv │ │ ├── escape.csv │ │ ├── issue.2232.csv │ │ ├── line_break_escaped_32le.csv │ │ ├── line_break_in_enclosure.csv │ │ ├── line_break_in_enclosure_with_escaped_quotes.csv │ │ ├── linend.mac.csv │ │ ├── linend.unix.csv │ │ ├── linend.win.csv │ │ ├── no_delimiter.csv │ │ ├── premiere.utf16be.csv │ │ ├── premiere.utf16bebom.csv │ │ ├── premiere.utf16le.csv │ │ ├── premiere.utf16lebom.csv │ │ ├── premiere.utf32be.csv │ │ ├── premiere.utf32bebom.csv │ │ ├── premiere.utf32le.csv │ │ ├── premiere.utf32lebom.csv │ │ ├── premiere.utf8.csv │ │ ├── premiere.utf8bom.csv │ │ ├── premiere.win1252.csv │ │ ├── semicolon_separated.csv │ │ ├── sep.csv │ │ └── utf16be.line_break_in_enclosure.csv │ ├── Gnumeric/ │ │ ├── ArrayFormulaTest.gnumeric │ │ ├── ArrayFormulaTest2.gnumeric │ │ ├── Autofilter_Basic.gnumeric │ │ ├── HiddenSheet.gnumeric │ │ ├── PageSetup.gnumeric │ │ ├── PageSetup.gnumeric.unzipped.xml │ │ ├── apostrophe3a.gnumeric │ │ ├── apostrophe3b.gnumeric │ │ └── xmlwithdoctype.gnumeric │ ├── HTML/ │ │ ├── badhtml.html │ │ ├── charset.ISO-8859-1.html │ │ ├── charset.ISO-8859-1.html4.html │ │ ├── charset.ISO-8859-2.html │ │ ├── charset.UTF-16.bebom.html │ │ ├── charset.UTF-16.lebom.html │ │ ├── charset.UTF-8.bom.html │ │ ├── charset.UTF-8.html │ │ ├── charset.gb18030.html │ │ ├── charset.nocharset.html │ │ ├── charset.unknown.html │ │ ├── csv_with_angle_bracket.csv │ │ ├── html.opacity.3.html │ │ ├── rowspan.html │ │ ├── utf8chars.charset.html │ │ ├── utf8chars.html │ │ └── xhtml4.entity.xhtml │ ├── NotASpreadsheetFile.doc │ ├── Ods/ │ │ ├── ArrayFormulaTest.ods │ │ ├── AutoFilter.ods │ │ ├── DefinedNames.apostrophe.ods │ │ ├── DefinedNames.ods │ │ ├── HiddenMergeCellsTest.ods │ │ ├── HiddenSheet2.ods │ │ ├── MergeRangeTest.ods │ │ ├── PageSetup.ods │ │ ├── RepeatedCells.ods │ │ ├── RepeatedDataCells.ods │ │ ├── bug1772.ods │ │ ├── colgroup.ods │ │ ├── colheader.ods │ │ ├── corruptMeta.ods │ │ ├── currency4.ods │ │ ├── data.ods │ │ ├── issue.2507.ods │ │ ├── issue.2810.ods │ │ ├── issue.3658.ods │ │ ├── issue.3721.ods │ │ ├── issue.407.ods │ │ ├── issue.4081.ods │ │ ├── issue.4099.ods │ │ ├── issue.4435b.ods │ │ ├── issue.4528.ods │ │ ├── issue.804.ods │ │ ├── nomimetype.ods │ │ ├── odsstyles5.ods │ │ └── propertyTest.ods │ ├── Slk/ │ │ ├── issue.2267c.slk │ │ ├── issue.2276.slk │ │ └── issue.3658.slk │ ├── XLS/ │ │ ├── 1900_Calendar.xls │ │ ├── 1904_Calendar.xls │ │ ├── CF_Basic_Comparisons.xls │ │ ├── CF_Expression_Comparisons.xls │ │ ├── Colours.xls │ │ ├── DataValidation.xls │ │ ├── DefinedNameTest.xls │ │ ├── HiddenMergeCellsTest.xls │ │ ├── HiddenSheet.xls │ │ ├── PageSetup.xls │ │ ├── RichTextFontSize.xls │ │ ├── WholeRowAndColumn.xls │ │ ├── biff8cover.xls │ │ ├── bug-pr-3734.xls │ │ ├── bug1114.xls │ │ ├── bug1505.xls │ │ ├── bug1592.xls │ │ ├── chartsheet.xls │ │ ├── formulas.database.xls │ │ ├── formulas.other.xls │ │ ├── formulas.xls │ │ ├── isodd.xls │ │ ├── issue.2463.xls │ │ ├── issue.3202.xls │ │ ├── issue.3658.xls │ │ ├── issue2239.xls │ │ ├── maccentraleurope.biff5.xls │ │ ├── maccentraleurope.xls │ │ ├── pr.4687.excel.badendian.xls │ │ ├── pr.4687.excel.xls │ │ ├── pr607.sum_data.xls │ │ ├── pwtest.xls │ │ ├── pwtest2.xls │ │ ├── pwtest3.xls │ │ ├── sample.xls │ │ └── visibility.xls │ ├── XLSX/ │ │ ├── 1900_Calendar.xlsx │ │ ├── 1904_Calendar.xlsx │ │ ├── ChartSheet.xlsx │ │ ├── ConditionalFormat_Ranges.xlsx │ │ ├── HiddenMergeCellsTest.xlsx │ │ ├── HiddenSheet.xlsx │ │ ├── PageSetup.xlsx │ │ ├── RgbTint.xlsx │ │ ├── TableWithoutFilter.xlsx │ │ ├── Zip-Linux-Directory-Separator.xlsx │ │ ├── Zip-Windows-Directory-Separator.xlsx │ │ ├── atsign.choosecols.xlsx │ │ ├── autofilter2.xlsx │ │ ├── autofilterTest.xlsx │ │ ├── blankcell.xlsx │ │ ├── bug1686b.xlsx │ │ ├── colorscale.xlsx │ │ ├── colortabs.xlsx │ │ ├── condfmtnum.xlsx │ │ ├── conditionalFormatting2Test.xlsx │ │ ├── conditionalFormatting3Test.xlsx │ │ ├── conditionalFormattingDataBarTest.xlsx │ │ ├── conditionalFormattingIconSet.xlsx │ │ ├── conditionalFormattingTest.xlsx │ │ ├── dataValidation2Test.xlsx │ │ ├── dataValidationTest.xlsx │ │ ├── data_with_tables.xlsx │ │ ├── double_attr_drawing.xlsx │ │ ├── drawingOneCellAnchor.xlsx │ │ ├── drawing_in_cell.xlsx │ │ ├── ebcdic.dontuse │ │ ├── empty_drawing.xlsx │ │ ├── excel-groupby-one.xlsx │ │ ├── excelChartsTest.xlsx │ │ ├── explicitdate.xlsx │ │ ├── fakewebservice.xlsx │ │ ├── ignoreerror.xlsx │ │ ├── issue.1319.bug2.xlsx │ │ ├── issue.1432b.xlsx │ │ ├── issue.1482.xlsx │ │ ├── issue.1637.xlsx │ │ ├── issue.2246a.xlsx │ │ ├── issue.2246b.xlsx │ │ ├── issue.2301.xlsx │ │ ├── issue.2316.xlsx │ │ ├── issue.2331c.xlsx │ │ ├── issue.2362.xlsx │ │ ├── issue.2387.xlsx │ │ ├── issue.2450.xlsx │ │ ├── issue.2488.xlsx │ │ ├── issue.2490.xlsx │ │ ├── issue.2494.xlsx │ │ ├── issue.2501.b.xlsx │ │ ├── issue.2506.xlsx │ │ ├── issue.2516b.xlsx │ │ ├── issue.2542.xlsx │ │ ├── issue.2581.xlsx │ │ ├── issue.2677.namespace.xlsx │ │ ├── issue.2677.removeformula1.xlsx │ │ ├── issue.2778.xlsx │ │ ├── issue.282.xlsx │ │ ├── issue.2885.xlsx │ │ ├── issue.2965.xlsx │ │ ├── issue.3093.xlsx │ │ ├── issue.3126.xlsx │ │ ├── issue.3143a.xlsx │ │ ├── issue.3145.xlsx │ │ ├── issue.3202.xlsx │ │ ├── issue.3255.xlsx │ │ ├── issue.3277.xlsx │ │ ├── issue.3370.xlsx │ │ ├── issue.3435.xlsx │ │ ├── issue.3453.xlsx │ │ ├── issue.3464.xlsx │ │ ├── issue.3495d.xlsx │ │ ├── issue.3534.xlsx │ │ ├── issue.3552.xlsx │ │ ├── issue.3553.xlsx │ │ ├── issue.3613.xlsx │ │ ├── issue.3654.xlsx │ │ ├── issue.3654c.xlsx │ │ ├── issue.3658.xlsx │ │ ├── issue.3665.xlsx │ │ ├── issue.3679.img.xlsx │ │ ├── issue.3720.xlsx │ │ ├── issue.3730.xlsx │ │ ├── issue.3767.xlsx │ │ ├── issue.3770.xlsx │ │ ├── issue.3807.xlsx │ │ ├── issue.3833.logarithm.xlsx │ │ ├── issue.3833.units.xlsx │ │ ├── issue.3863.xlsx │ │ ├── issue.3909b.xlsx │ │ ├── issue.3982.xlsx │ │ ├── issue.4049.xlsx │ │ ├── issue.4063.xlsx │ │ ├── issue.4248.xlsx │ │ ├── issue.4312c.xlsx │ │ ├── issue.4318.xlsx │ │ ├── issue.4375.small.xlsx │ │ ├── issue.4415.xlsx │ │ ├── issue.4416.smallauto.xlsx │ │ ├── issue.4477.disclaimer.xlsx │ │ ├── issue.4505.namespace.xlsx │ │ ├── issue.4539.xlsx │ │ ├── issue.4629.xlsx │ │ ├── issue.4724.xlsx │ │ ├── issue.4800.xlsx │ │ ├── issue.731.xlsx │ │ ├── issue2109b.xlsx │ │ ├── namespacenonstd.xlsx │ │ ├── namespacepurl.xlsx │ │ ├── namespaces.openpyxl35.xlsx │ │ ├── namespaces.xlsx │ │ ├── namespacestd.xlsx │ │ ├── octo#thorpe.xlsx │ │ ├── outline.xlsx │ │ ├── pageSetupTest.xlsx │ │ ├── pr1769e.xlsx │ │ ├── pr1769g.py.xlsx │ │ ├── pr2050cf-fill.xlsx │ │ ├── pr2225-datavalidation-onezero.xlsx │ │ ├── pr2225-datavalidation-truefalse.xlsx │ │ ├── propertyTest.xlsx │ │ ├── rootZipFiles.xlsx │ │ ├── rowColumnAttributeTest.xlsx │ │ ├── sec-j47r.dontuse │ │ ├── sec-p66w.dontuse │ │ ├── sec-q229.dontuse │ │ ├── sharedformulae.xlsx │ │ ├── sheetprotect.xlsx │ │ ├── sheetsChartsTest.xlsx │ │ ├── splits.xlsx │ │ ├── stylesTest.xlsx │ │ ├── tableTest.xlsx │ │ ├── threesheets.xlsx │ │ ├── urlImage.bad.dontuse │ │ ├── urlImage.notfound.xlsx │ │ ├── urlImage.xlsx │ │ ├── urlImage2.onecell.xlsx │ │ ├── urlImage2.xlsx │ │ ├── utf16be.bom.xlsx │ │ ├── utf16be.xlsx │ │ ├── utf16entity.dontuse │ │ ├── utf7quoteorder.dontuse │ │ ├── utf7white.dontuse │ │ ├── utf8and16.dontuse │ │ ├── utf8and16.entity.dontuse │ │ ├── utf8entity.dontuse │ │ ├── verticalAlignTest.xlsx │ │ ├── visibility.xlsx │ │ └── without_cell_reference.xlsx │ └── Xml/ │ ├── ArrayFormula.xml │ ├── CorruptedXmlFile.xml │ ├── PageSetup.xml │ ├── SecurityScannerWithCallbackExample.xml │ ├── XEETestInvalidSimpleXML.xml │ ├── XEETestInvalidUTF-16.xml │ ├── XEETestInvalidUTF-16BE.xml │ ├── XEETestInvalidUTF-16LE.xml │ ├── XEETestInvalidUTF-7-single-quote.xml │ ├── XEETestInvalidUTF-7-whitespace.xml │ ├── XEETestInvalidUTF-7.xml │ ├── XEETestInvalidUTF-7_DoubleEncoded.xml │ ├── XEETestInvalidUTF-8.xml │ ├── XEETestValidUTF-16.xml │ ├── XEETestValidUTF-16BE.xml │ ├── XEETestValidUTF-16LE.xml │ ├── XEETestValidUTF-8-single-quote.xml │ ├── XEETestValidUTF-8-whitespace.xml │ ├── XEETestValidUTF-8.xml │ ├── bug4669.xml │ ├── datavalidations.wholerow.xml │ ├── datavalidations.xml │ ├── excel2003.iso8859-1.xml │ ├── hyperlinkbase.xml │ ├── issue.2157.small.xml │ ├── issue.3658.xml │ ├── issue.4448.xml │ ├── issue.850.xml │ ├── sec-w24f.dontuse │ └── splits.xml ├── ReferenceHelperFormulaUpdates.php ├── ReferenceHelperFormulaUpdatesMultipleSheet.php ├── Shared/ │ ├── CentimeterSizeToPixels.php │ ├── CodePage.php │ ├── Date/ │ │ ├── DateTimeToExcel.php │ │ ├── ExcelToTimestamp1900.php │ │ ├── ExcelToTimestamp1900Timezone.php │ │ ├── ExcelToTimestamp1904.php │ │ ├── FormatCodes.php │ │ ├── FormattedPHPToExcel1900.php │ │ ├── TimestampToExcel1900.php │ │ └── TimestampToExcel1904.php │ ├── FontSizeToPixels.php │ ├── InchSizeToPixels.php │ ├── OLERead/ │ │ ├── document │ │ ├── summary │ │ └── wrkbook │ ├── PasswordHashes.php │ └── Trend/ │ ├── ExponentialBestFit.php │ └── LinearBestFit.php ├── Style/ │ ├── Color/ │ │ ├── ColorChangeBrightness.php │ │ ├── ColorGetBlue.php │ │ ├── ColorGetGreen.php │ │ └── ColorGetRed.php │ ├── ConditionalFormatting/ │ │ └── CellMatcher.xlsx │ ├── NumberFormat.php │ ├── NumberFormatDates.php │ └── NumberFormatFractions.php ├── Worksheet/ │ ├── Table/ │ │ └── TableFormulae.xlsx │ └── namedRangeTest.xlsx └── Writer/ ├── Ods/ │ ├── content-arrays.xml │ ├── content-empty.xml │ ├── content-hidden-worksheet.xml │ └── content-with-data.xml └── XLSX/ ├── ArrayFunctions2.json ├── drawing_in_comment.xlsx ├── drawing_on_2nd_page.xlsx ├── form_pass_print.xlsm ├── gallerytheme.xlsx ├── grouped_images.xlsx ├── issue.2266f.xlsx ├── issue.2368new.xlsx ├── issue.2396.xlsx ├── issue.2908.xlsx ├── issue.3811b.xlsx ├── issue.3843a.template.xlsx ├── issue.4037.xlsx ├── issue.476.xlsx ├── merge.excel.xlsx ├── purple_square.tiff ├── saving_drawing_with_same_path.xlsx └── wmffile.xlsx ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 indent_size = 4 indent_style = space end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false [*.{yml,yaml}] indent_size = 2 ================================================ FILE: .gitattributes ================================================ *.min.js binary /.editorconfig export-ignore /.gitattributes export-ignore /.github export-ignore /.gitignore export-ignore /.php-cs-fixer.dist.php export-ignore /.phpcs.xml.dist export-ignore /.readthedocs.yaml export-ignore /.scrutinizer.yml export-ignore /CHANGELOG.PHPExcel.md export-ignore /bin export-ignore /composer.lock export-ignore /docs export-ignore /infra export-ignore /mkdocs.yml export-ignore /phpstan-baseline.neon export-ignore /phpstan.neon.dist export-ignore /phpunit.xml.dist export-ignore /samples export-ignore /tests export-ignore ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ This is: ``` - [ ] a bug report - [ ] a feature request - [ ] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet) ``` ### What is the expected behavior? ### What is the current behavior? ### What are the steps to reproduce? Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) of code that exhibits the issue without relying on an external Excel file or a web server: ```php This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue for you, please try to help by debugging it further and sharing your results. Thank you for your contributions. # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false ================================================ FILE: .github/support.yml ================================================ # Label used to mark issues as support requests supportLabel: question # Comment to post on issues marked as support requests. Add a link # to a support page, or set to `false` to disable supportComment: > This looks like a support question. Please ask your support questions on [StackOverflow](https://stackoverflow.com/questions/tagged/phpspreadsheet), or [Gitter](https://gitter.im/PHPOffice/PhpSpreadsheet). Thank you for your contributions. # Whether to close issues marked as support requests close: true # Whether to lock issues marked as support requests lock: false ================================================ FILE: .github/workflows/github-pages.yml ================================================ name: GithHub Pages on: push: tags: - '*' permissions: {} jobs: github-pages: permissions: contents: write # to push pages branch (peaceiris/actions-gh-pages) runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.3 coverage: none # remove xdebug - name: Build API documentation run: | curl -LO https://github.com/phpDocumentor/phpDocumentor/releases/download/v3.8.1/phpDocumentor.phar php phpDocumentor.phar --directory src/ --target docs/api --visibility=public,protected - name: Deploy to GithHub Pages uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs/api ================================================ FILE: .github/workflows/main.yml ================================================ name: main on: [ push, pull_request, merge_group ] permissions: contents: read # to fetch code (actions/checkout) jobs: test: runs-on: ubuntu-latest strategy: matrix: experimental: - false php-version: - '8.1' - '8.2' - '8.3' - '8.4' - '8.5' include: - php-version: 'nightly' experimental: true name: PHP ${{ matrix.php-version }} steps: - name: Checkout uses: actions/checkout@v6 - name: Install locales run: sudo apt-get update && sudo apt-get install -y language-pack-fr language-pack-de - name: Install single-byte locale run: sudo sed -i -e 's/# de_DE@euro/de_DE@euro/g' /etc/locale.gen && sudo locale-gen de_DE@euro - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none - name: Get composer cache directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache composer dependencies uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Delete composer lock file id: composer-lock if: ${{ matrix.php-version == 'nightly' }} run: | rm composer.lock echo "flags=--ignore-platform-reqs" >> $GITHUB_OUTPUT - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} - name: Setup problem matchers for PHP run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" - name: Setup problem matchers for PHPUnit run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" - name: "Run PHPUnit tests (Experimental: ${{ matrix.experimental }})" env: FAILURE_ACTION: "${{ matrix.experimental == true }}" run: vendor/bin/phpunit --display-incomplete --display-skipped --display-deprecations --display-errors --display-notices --display-warnings || $FAILURE_ACTION phpdoc-types: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 with: fetch-depth: 2 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none # This is non-ideal because it only checks for the last commit of the PR, not all of them, but better than nothing - name: Check PHPDoc types run: ./bin/check-phpdoc-types.php php-cs-fixer: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache composer dependencies uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Code style with PHP-CS-Fixer run: (./vendor/bin/php-cs-fixer fix --dry-run --format=checkstyle | cs2pr) || ./vendor/bin/php-cs-fixer fix --diff --dry-run phpcs: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache composer dependencies uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Code style with PHP_CodeSniffer run: ./vendor/bin/phpcs -q --report=checkstyle | cs2pr versions: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache composer dependencies uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Code Version Compatibility check with PHP_CodeSniffer run: ./vendor/bin/phpcs -q --report-width=200 --report=summary,full src/ --standard=PHPCompatibility --runtime-set testVersion 8.1- --exclude=PHPCompatibility.Variables.ForbiddenThisUseContexts phpstan: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache composer dependencies uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Static analysis with PHPStan run: ./vendor/bin/phpstan analyse coverage: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 with: fetch-depth: 0 - name: Install locales run: sudo apt-get update && sudo apt-get install -y language-pack-fr language-pack-de - name: Install single-byte locale run: sudo sed -i -e 's/# de_DE@euro/de_DE@euro/g' /etc/locale.gen && sudo locale-gen de_DE@euro - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: ctype, dom, fileinfo, filter, gd, iconv, intl, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: pcov - name: Get composer cache directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache composer dependencies uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Coverage run: | ./vendor/bin/phpunit --coverage-clover build/clover.xml - name: Upload coverage results to Coveralls uses: coverallsapp/github-action@v2 with: github-token: ${{ secrets.GITHUB_TOKEN }} file: build/clover.xml format: clover fail-on-error: false release: permissions: contents: write # to create a release (actions/create-release) runs-on: ubuntu-latest if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') steps: - uses: actions/checkout@v6 with: ref: ${{ github.ref }} # Otherwise our annotated tag is not fetched and we cannot get correct version - name: Get release info run: git tag --format '%(contents:body)' --points-at > release-body.txt - uses: ncipollo/release-action@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token with: bodyFile: release-body.txt ================================================ FILE: .gitignore ================================================ /tests/codeCoverage /analysis /vendor/ /phpunit.xml .phpunit.result.cache ## IDE support *.buildpath *.project /.settings /.idea ## mkdocs output /site ================================================ FILE: .php-cs-fixer.dist.php ================================================ exclude(['vendor', 'docs', '.git', '.github']) ->notPath('src/PhpSpreadsheet/Writer/ZipStream3.php') ->in(__DIR__); $config = new PhpCsFixer\Config(); $config ->setRiskyAllowed(true) ->setFinder($finder) ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect(null, 600)) ->setCacheFile(sys_get_temp_dir() . '/php-cs-fixer' . preg_replace('~\W~', '-', __DIR__)) ->setRules([ 'align_multiline_comment' => true, 'array_indentation' => true, 'array_syntax' => ['syntax' => 'short'], 'backtick_to_shell_exec' => true, 'binary_operator_spaces' => true, 'blank_line_after_namespace' => true, 'blank_lines_before_namespace' => ['max_line_breaks' => 2, 'min_line_breaks' => 2], // we want 1 blank line before namespace 'blank_line_after_opening_tag' => true, 'blank_line_before_statement' => true, 'cast_spaces' => true, 'class_attributes_separation' => ['elements' => ['method' => 'one', 'property' => 'one']], // const are often grouped with other related const 'class_definition' => false, // phpcs disagree 'combine_consecutive_issets' => true, 'combine_consecutive_unsets' => true, 'combine_nested_dirname' => true, 'comment_to_phpdoc' => false, // interferes with annotations 'compact_nullable_type_declaration' => true, 'concat_space' => ['spacing' => 'one'], 'constant_case' => true, 'date_time_immutable' => false, // Break our unit tests 'declare_equal_normalize' => true, 'declare_strict_types' => false, // Too early to adopt strict types 'dir_constant' => true, 'doctrine_annotation_array_assignment' => true, 'doctrine_annotation_braces' => true, 'doctrine_annotation_indentation' => true, 'doctrine_annotation_spaces' => true, 'elseif' => true, 'empty_loop_body' => true, 'empty_loop_condition' => true, 'encoding' => true, 'ereg_to_preg' => true, 'error_suppression' => false, // it breaks \PhpOffice\PhpSpreadsheet\Helper\Handler 'explicit_indirect_variable' => false, // I feel it makes the code actually harder to read 'explicit_string_variable' => false, // I feel it makes the code actually harder to read 'final_class' => false, // We need non-final classes 'final_internal_class' => true, 'final_public_method_for_abstract_class' => false, // We need non-final methods 'fopen_flag_order' => true, 'fopen_flags' => true, 'full_opening_tag' => true, 'fully_qualified_strict_types' => true, 'function_declaration' => true, 'function_to_constant' => true, 'general_phpdoc_annotation_remove' => ['annotations' => ['access', 'category', 'copyright']], 'general_phpdoc_tag_rename' => true, 'global_namespace_import' => true, 'group_import' => false, // I feel it makes the code actually harder to read 'header_comment' => false, // We don't use common header in all our files 'heredoc_indentation' => true, 'heredoc_to_nowdoc' => false, // Not sure about this one 'implode_call' => true, 'include' => true, 'increment_style' => true, 'indentation_type' => true, 'integer_literal_case' => true, 'is_null' => true, 'lambda_not_used_import' => true, 'line_ending' => true, 'linebreak_after_opening_tag' => true, 'list_syntax' => ['syntax' => 'short'], 'logical_operators' => true, 'lowercase_cast' => true, 'lowercase_keywords' => true, 'lowercase_static_reference' => true, 'magic_constant_casing' => true, 'magic_method_casing' => true, 'mb_str_functions' => false, // No, too dangerous to change that 'method_argument_space' => true, 'method_chaining_indentation' => true, 'modernize_strpos' => true, 'modernize_types_casting' => true, 'modifier_keywords' => ['elements' => ['property', 'method']], // not const 'multiline_comment_opening_closing' => true, 'multiline_whitespace_before_semicolons' => true, 'native_constant_invocation' => false, // Micro optimization that look messy 'native_function_casing' => true, 'native_function_invocation' => false, // I suppose this would be best, but I am still unconvinced about the visual aspect of it 'new_with_parentheses' => ['anonymous_class' => true, 'named_class' => true], 'no_alias_functions' => true, 'no_alias_language_construct_call' => true, 'no_alternative_syntax' => true, 'no_binary_string' => true, 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_break_comment' => true, 'no_closing_tag' => true, 'no_empty_comment' => true, 'no_empty_phpdoc' => true, 'no_empty_statement' => true, 'no_extra_blank_lines' => true, 'no_homoglyph_names' => true, 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_mixed_echo_print' => true, 'no_multiline_whitespace_around_double_arrow' => true, 'no_null_property_initialization' => true, 'no_php4_constructor' => true, 'no_short_bool_cast' => true, 'echo_tag_syntax' => ['format' => 'long'], 'no_singleline_whitespace_before_semicolons' => true, 'no_space_around_double_colon' => true, 'no_spaces_after_function_name' => true, 'no_spaces_around_offset' => true, 'no_superfluous_elseif' => false, // Might be risky on a huge code base 'no_superfluous_phpdoc_tags' => ['allow_mixed' => true], 'no_trailing_comma_in_singleline' => ['elements' => ['arguments', 'array_destructuring', 'array', 'group_import']], 'no_trailing_whitespace' => true, 'no_trailing_whitespace_in_comment' => true, 'no_trailing_whitespace_in_string' => false, // Too dangerous 'no_unneeded_control_parentheses' => true, 'no_unneeded_braces' => true, 'no_unneeded_final_method' => true, 'no_unreachable_default_argument_value' => true, 'no_unset_cast' => true, 'no_unset_on_property' => false, 'no_unused_imports' => true, 'no_useless_else' => true, 'no_useless_return' => true, 'no_useless_sprintf' => true, 'no_whitespace_before_comma_in_array' => true, 'no_whitespace_in_blank_line' => true, 'non_printable_character' => true, 'normalize_index_brace' => true, 'not_operator_with_space' => false, // No we prefer to keep '!' without spaces 'not_operator_with_successor_space' => false, // idem 'nullable_type_declaration_for_default_null_value' => true, 'object_operator_without_whitespace' => true, 'octal_notation' => true, 'operator_linebreak' => true, 'ordered_class_elements' => false, // We prefer to keep some freedom 'ordered_imports' => true, 'ordered_interfaces' => true, 'ordered_traits' => true, 'php_unit_attributes' => ['keep_annotations' => false], 'php_unit_construct' => true, 'php_unit_dedicate_assert' => true, 'php_unit_dedicate_assert_internal_type' => true, 'php_unit_expectation' => true, 'php_unit_fqcn_annotation' => true, 'php_unit_internal_class' => false, // Because tests are excluded from package 'php_unit_method_casing' => true, 'php_unit_mock' => true, 'php_unit_mock_short_will_return' => true, 'php_unit_namespaced' => true, 'php_unit_no_expectation_annotation' => true, 'phpdoc_order_by_value' => ['annotations' => ['covers']], 'php_unit_set_up_tear_down_visibility' => true, 'php_unit_size_class' => false, // That seems extra work to maintain for little benefits 'php_unit_strict' => false, // We sometime actually need assertEquals 'php_unit_test_annotation' => true, 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], 'php_unit_test_class_requires_covers' => false, // We don't care as much as we should about coverage 'phpdoc_add_missing_param_annotation' => false, // Don't add things that bring no value 'phpdoc_align' => false, // Waste of time 'phpdoc_annotation_without_dot' => false, 'phpdoc_indent' => true, 'phpdoc_line_span' => false, // Unfortunately our old comments turn even uglier with this 'phpdoc_no_access' => true, 'phpdoc_no_alias_tag' => true, 'phpdoc_no_empty_return' => true, 'phpdoc_no_package' => true, 'phpdoc_no_useless_inheritdoc' => true, 'phpdoc_order' => true, 'phpdoc_return_self_reference' => true, 'phpdoc_scalar' => true, 'phpdoc_separation' => true, 'phpdoc_single_line_var_spacing' => true, 'phpdoc_summary' => true, 'phpdoc_tag_casing' => true, 'phpdoc_tag_type' => true, 'phpdoc_to_comment' => false, // interferes with annotations 'phpdoc_to_param_type' => false, // Because experimental, but interesting for one shot use 'phpdoc_to_property_type' => false, // Because experimental, but interesting for one shot use 'phpdoc_to_return_type' => false, // Because experimental, but interesting for one shot use 'phpdoc_trim' => true, 'phpdoc_trim_consecutive_blank_line_separation' => true, 'phpdoc_types' => true, 'phpdoc_types_order' => true, 'phpdoc_var_annotation_correct_order' => true, 'phpdoc_var_without_name' => true, 'pow_to_exponentiation' => true, 'protected_to_private' => true, 'psr_autoloading' => true, 'random_api_migration' => true, 'return_assignment' => false, // Sometimes useful for clarity or debug 'return_type_declaration' => true, 'self_accessor' => true, 'self_static_accessor' => true, 'semicolon_after_instruction' => false, // Buggy in `samples/index.php` 'set_type_to_cast' => true, 'short_scalar_cast' => true, 'simple_to_complex_string_variable' => false, // Would differ from TypeScript without obvious advantages 'simplified_if_return' => false, // Even if technically correct we prefer to be explicit 'simplified_null_return' => false, // Even if technically correct we prefer to be explicit 'single_blank_line_at_eof' => true, 'single_class_element_per_statement' => true, 'single_import_per_statement' => true, 'single_line_after_imports' => true, 'single_line_comment_style' => true, 'single_line_throw' => false, // I don't see any reason for having a special case for Exception 'single_quote' => true, 'single_trait_insert_per_statement' => true, 'space_after_semicolon' => true, 'spaces_inside_parentheses' => ['space' => 'none'], 'standardize_increment' => true, 'standardize_not_equals' => true, 'static_lambda' => false, // Risky if we can't guarantee nobody use `bindTo()` 'strict_comparison' => false, // No, too dangerous to change that 'string_implicit_backslashes' => ['single_quoted' => 'unescape', 'double_quoted' => 'escape', 'heredoc' => 'escape'], // was escape_implicit_backslashes 'strict_param' => false, // No, too dangerous to change that 'string_length_to_empty' => true, 'string_line_ending' => true, 'switch_case_semicolon_to_colon' => true, 'switch_case_space' => true, 'switch_continue_to_break' => true, 'ternary_operator_spaces' => true, 'ternary_to_elvis_operator' => true, 'ternary_to_null_coalescing' => true, 'trailing_comma_in_multiline' => true, 'trim_array_spaces' => true, 'type_declaration_spaces' => ['elements' => ['function', 'property']], // was function_typehint_space 'types_spaces' => true, 'unary_operator_spaces' => true, 'use_arrow_functions' => true, 'void_return' => true, 'whitespace_after_comma_in_array' => true, 'yoda_style' => false, ]); return $config; ================================================ FILE: .phpcs.xml.dist ================================================ samples src tests infra bin ================================================ FILE: .readthedocs.yaml ================================================ # Read the Docs configuration file for MkDocs projects # See https://docs.readthedocs.io/en/stable/config-file/v2.html version: 2 build: os: ubuntu-22.04 tools: python: "3" mkdocs: configuration: mkdocs.yml ================================================ FILE: CHANGELOG.PHPExcel.md ================================================ # Changelog for PHPExcel This is the historic changelog of the project when it was still called PHPExcel. It exists only for historical purposes and versions mentioned here should not be confused with PhpSpreadsheet versions. ## [1.8.1] - 2015-04-30 ### Bugfixes - Fix for Writing an Open Document cell with non-numeric formula - @goncons [#397](https://github.com/PHPOffice/PHPExcel/issues/397) - Avoid potential divide by zero in basedrawing - @sarciszewski [#329](https://github.com/PHPOffice/PHPExcel/issues/329) - XML External Entity (XXE) Processing, different behaviour between simplexml_load_string() and simplexml_load_file(). - @ymaerschalck [#405](https://github.com/PHPOffice/PHPExcel/issues/405) - Fix to ensure that current cell is maintained when executing formula calculations - @MarkBaker - Keep/set the value on Reader _loadSheetsOnly as NULL, courtesy of Restless-ET - @MarkBaker [#350](https://github.com/PHPOffice/PHPExcel/issues/350) - Loading an Excel 2007 spreadsheet throws an "Autofilter must be set on a range of cells" exception - @MarkBaker [CodePlex #18105](https://phpexcel.codeplex.com/workitem/18105) - Fix to autoloader registration for backward compatibility with PHP 5.2.0 not accepting the prepend flag - @MarkBaker [#388](https://github.com/PHPOffice/PHPExcel/issues/388) - DOM loadHTMLFile() failing with options flags when using PHP < 5.4.0 - @MarkBaker [#384](https://github.com/PHPOffice/PHPExcel/issues/384) - Fix for percentage operator in formulae for BIFF Writer - @MarkBaker - Fix to getStyle() call for cell object - @MarkBaker - Discard Autofilters in Excel2007 Reader when filter range isn't a valid range - @MarkBaker - Fix invalid NA return in VLOOKUP - @frozenstupidity [#423](https://github.com/PHPOffice/PHPExcel/issues/423) - "No Impact" conditional formatting fix for NumberFormat - @wiseloren [CodePlex #21454](https://phpexcel.codeplex.com/workitem/21454) - Bug in Excel2003XML reader, parsing merged cells - @bobwitlox [#467](https://github.com/PHPOffice/PHPExcel/issues/467) - Fix for CEIL() and FLOOR() when number argument is zero - @MarkBaker [#302](https://github.com/PHPOffice/PHPExcel/issues/302) ### General - Remove cells cleanly when calling RemoveRow() or RemoveColumn() - @MarkBaker - Small performance improvement for autosize columns - @MarkBaker - Change the getter/setter for zeroHeight to camel case - @frost-nzcr4 [#379](https://github.com/PHPOffice/PHPExcel/issues/379) - DefaultValueBinder is too much aggressive when converting string to numeric - @MarkBaker [#394](https://github.com/PHPOffice/PHPExcel/issues/394) - Default precalculate formulas to false for writers - @MarkBaker - Set default Cyclic Reference behaviour to 1 to eliminate exception when using a single cyclic iteration in formulae - @MarkBaker ### Features - Some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE - @MarkBaker [#396](https://github.com/PHPOffice/PHPExcel/issues/396) - Methods to manage most of the existing options for Chart Axis, Major Grid-lines and Minor Grid-lines - @WiktrzGE [#404](https://github.com/PHPOffice/PHPExcel/issues/404) - ODS read/write comments in the cell - @frost-nzcr4 [#403](https://github.com/PHPOffice/PHPExcel/issues/403) - Additional Mac CJK codepage definitions - @CQD [#389](https://github.com/PHPOffice/PHPExcel/issues/389) - Update Worksheet.php getStyleByColumnAndRow() to allow a range of cells rather than just a single cell - @bolovincev [#269](https://github.com/PHPOffice/PHPExcel/issues/269) - New methods added for testing cell status within merge groups - @MarkBaker - Handling merge cells in HTML Reader - @cifren/MBaker [#205](https://github.com/PHPOffice/PHPExcel/issues/205) - Helper to convert basic HTML markup to a Rich Text object - @MarkBaker - Improved Iterators - @MarkBaker - New Column Iterator - Support for row and column ranges - Improved handling for next/prev ### Security - XML filescan in XML-based Readers to prevent XML Entity Expansion (XEE) - @MarkBaker - (see http://projects.webappsec.org/w/page/13247002/XML%20Entity%20Expansion for an explanation of XEE injection) attacks - Reference CVE-2015-3542 - Identification of problem courtesy of Dawid Golunski (Pentest Ltd.) ## [1.8.0] - 2014-03-02 ### Bugfixes - Undefined variable: fileHandle in CSV Reader - @MarkBaker [CodePlex #19830](https://phpexcel.codeplex.com/workitem/19830) - Out of memory in style/supervisor.php - @MarkBaker [CodePlex #19968](https://phpexcel.codeplex.com/workitem/19968) - Style error with merged cells in PDF Writer - @MarkBaker - Problem with cloning worksheets - @MarkBaker - Bug fix reading Open Office files - @tavoarcila [#259](https://github.com/PHPOffice/PHPExcel/issues/259) - Serious bug in absolute cell reference used in shared formula - @MarkBaker [CodePlex #20397](https://phpexcel.codeplex.com/workitem/20397) - Would also have affected insert/delete column/row- CHOOSE() returns "#VALUE!" if the 1st entry is chosen - @RomanSyroeshko [#267](https://github.com/PHPOffice/PHPExcel/issues/267) - When duplicating styles, styles shifted by one column to the right - @Gemorroj [#268](https://github.com/PHPOffice/PHPExcel/issues/268) - Fix also applied to duplicating conditional styles- Fix for formulae that reference a sheet whose name begins with a digit: - @IndrekHaav [#212](https://github.com/PHPOffice/PHPExcel/issues/212) - these were erroneously identified as numeric values, causing the parser to throw an undefined variable error.- Fixed undefined variable error due to $styleArray being used before it's initialised - @IndrekHaav [CodePlex #16208](https://phpexcel.codeplex.com/workitem/16208) - ISTEXT() return wrong result if referencing an empty but formatted cell - @PowerKiKi [#273](https://github.com/PHPOffice/PHPExcel/issues/273) - Binary comparison of strings are case insensitive - @PowerKiKi [#270](https://github.com/PHPOffice/PHPExcel/issues/270), [#31](https://github.com/PHPOffice/PHPExcel/issues/31) - Insert New Row/Column Before is not correctly updating formula references - @MarkBaker [#275](https://github.com/PHPOffice/PHPExcel/issues/275) - Passing an array of cells to _generateRow() in the HTML/PDF Writer causes caching problems with last cell in the range - @MarkBaker [#257](https://github.com/PHPOffice/PHPExcel/issues/257) - Fix to empty worksheet garbage collection when using cell caching - @MarkBaker [#193](https://github.com/PHPOffice/PHPExcel/issues/193) - Excel2007 does not correctly mark rows as hidden - @Jazzo [#248](https://github.com/PHPOffice/PHPExcel/issues/248) - Fixed typo in Chart/Layout set/getYMode() - @Roy Shahbazian [#299](https://github.com/PHPOffice/PHPExcel/issues/299) - Fatal error: Call to a member function cellExists() line: 3327 in calculation.php if referenced worksheet doesn't exist - @EliuFlorez [#279](https://github.com/PHPOffice/PHPExcel/issues/279) - AdvancedValueBinder "Division by zero"-error - @MarkBaker [#290](https://github.com/PHPOffice/PHPExcel/issues/290) - Adding Sheet to Workbook Bug - @MarkBaker [CodePlex #20604](https://phpexcel.codeplex.com/workitem/20604) - Calculation engine incorrectly evaluates empty cells as #VALUE - @MarkBaker [CodePlex #20703](https://phpexcel.codeplex.com/workitem/20703) - Formula references to cell on another sheet in ODS files - @MarkBaker [CodePlex #20760](https://phpexcel.codeplex.com/workitem/20760) ### Features - LibreOffice created XLSX files results in an empty file. - @MarkBaker [#321](https://github.com/PHPOffice/PHPExcel/issues/321), [#158](https://github.com/PHPOffice/PHPExcel/issues/158), [CodePlex #17824](https://phpexcel.codeplex.com/workitem/17824) - Implementation of the Excel HLOOKUP() function - @amerov - Added "Quote Prefix" to style settings (Excel2007 Reader and Writer only) - @MarkBaker - Added Horizontal FILL alignment for Excel5 and Excel2007 Readers/Writers, and Horizontal DISTRIBUTED alignment for Excel2007 Reader/Writer - @MarkBaker - Add support for reading protected (RC4 encrypted) .xls files - @trvrnrth [#261](https://github.com/PHPOffice/PHPExcel/issues/261) ### General - Adding support for macros, Ribbon in Excel 2007 - @LWol [#252](https://github.com/PHPOffice/PHPExcel/issues/252) - Remove array_shift in ReferenceHelper::insertNewBefore improves column or row delete speed - @cdhutch [CodePlex #20055](https://phpexcel.codeplex.com/workitem/20055) - Improve stock chart handling and rendering, with help from Swashata Ghosh - @MarkBaker - Fix to calculation properties for Excel2007 so that the opening application will only recalculate on load if it's actually required - @MarkBaker - Modified Excel2007 Writer to default preCalculateFormulas to false - @MarkBaker - Note that autosize columns will still recalculate affected formulae internally- Functionality to getHighestRow() for a specified column, and getHighestColumn() for a specified row - @dresenhista [#242](https://github.com/PHPOffice/PHPExcel/issues/242) - Modify PHPExcel_Reader_Excel2007 to use zipClass from PHPExcel_Settings::getZipClass() - @adamriyadi [#247](https://github.com/PHPOffice/PHPExcel/issues/247) - This allows the use of PCLZip when reading for people that don't have access to ZipArchive ### Security - Convert properties to string in OOCalc reader - @infojunkie [#276](https://github.com/PHPOffice/PHPExcel/issues/276) - Disable libxml external entity loading by default. - @maartenba [#322](https://github.com/PHPOffice/PHPExcel/issues/322) - This is to prevent XML External Entity Processing (XXE) injection attacks (see https://websec.io/2012/08/27/Preventing-XEE-in-PHP.html for an explanation of XXE injection). - Reference CVE-2014-2054 ## [1.7.9] - 2013-06-02 ### Features - Include charts option for HTML Writer - @MarkBaker - Added composer file - @MarkBaker - cache_in_memory_gzip "eats" last worksheet line, cache_in_memory doesn't - @MarkBaker [CodePlex #18844](https://phpexcel.codeplex.com/workitem/18844) - echo statements in HTML.php - @MarkBaker [#104](https://github.com/PHPOffice/PHPExcel/issues/104) ### Bugfixes - Added getStyle() method to Cell object - @MarkBaker - Error in PHPEXCEL/Calculation.php script on line 2976 (stack pop check) - @Asker [CodePlex #18777](https://phpexcel.codeplex.com/workitem/18777) - CSV files without a file extension being identified as HTML - @MarkBaker [CodePlex #18794](https://phpexcel.codeplex.com/workitem/18794) - Wrong check for maximum number of rows in Excel5 Writer - @AndreKR [#66](https://github.com/PHPOffice/PHPExcel/issues/66) - Cache directory for DiscISAM cache storage cannot be set - @MarkBaker [#67](https://github.com/PHPOffice/PHPExcel/issues/67) - Fix to Excel2007 Reader for hyperlinks with an anchor fragment (following a #), otherwise they were treated as sheet references - @MarkBaker [CodePlex #17976](https://phpexcel.codeplex.com/workitem/17976) - getSheetNames() fails on numeric (floating point style) names with trailing zeroes - @MarkBaker [CodePlex #18963](https://phpexcel.codeplex.com/workitem/18963) - Modify cell's getCalculatedValue() method to return the content of RichText objects rather than the RichText object itself - @MarkBaker - Fixed formula/formatting bug when removing rows - @techhead [#70](https://github.com/PHPOffice/PHPExcel/issues/70) - Fix to cellExists for non-existent namedRanges - @alexgann [#63](https://github.com/PHPOffice/PHPExcel/issues/63) - Sheet View in Excel5 Writer - @Progi1984 [#22](https://github.com/PHPOffice/PHPExcel/issues/22) - PHPExcel_Worksheet::getCellCollection() may not return last cached cell - @amironov [#82](https://github.com/PHPOffice/PHPExcel/issues/82) - Rich Text containing UTF-8 characters creating unreadable content with Excel5 Writer - @teso [CodePlex #18551](https://phpexcel.codeplex.com/workitem/18551) - Work item GH-8/CP11704 : Conditional formatting in Excel 5 Writer - @Progi1984 - canRead() Error for GoogleDocs ODS files: in ODS files from Google Docs there is no mimetype file - @MarkBaker [#113](https://github.com/PHPOffice/PHPExcel/issues/113) - "Sheet index is out of bounds." Exception - @MarkBaker [#80](https://github.com/PHPOffice/PHPExcel/issues/80) - Fixed number format fatal error - @ccorliss [#105](https://github.com/PHPOffice/PHPExcel/issues/105) - Add DROP TABLE in destructor for SQLite and SQLite3 cache controllers - @MarkBaker - Fix merged-cell borders on HTML/PDF output - @alexgann [#154](https://github.com/PHPOffice/PHPExcel/issues/154) - Fix: Hyperlinks break when removing rows - @Shanto [#161](https://github.com/PHPOffice/PHPExcel/issues/161) - Fix Extra Table Row From Images and Charts - @neclimdul [#166](https://github.com/PHPOffice/PHPExcel/issues/166) ### General - Single cell print area - @MarkBaker [#130](https://github.com/PHPOffice/PHPExcel/issues/130) - Improved AdvancedValueBinder for currency - @kea [#69](https://github.com/PHPOffice/PHPExcel/issues/69) - Fix for environments where there is no access to /tmp but to upload_tmp_dir - @MarkBaker - Provided an option to set the sys_get_temp_dir() call to use the upload_tmp_dir; though by default the standard temp directory will still be used- Search style by identity in PHPExcel_Worksheet::duplicateStyle() - @amironov [#84](https://github.com/PHPOffice/PHPExcel/issues/84) - Fill SheetView IO in Excel5 - @karak [#85](https://github.com/PHPOffice/PHPExcel/issues/85) - Memory and Speed improvements in PHPExcel_Reader_Excel5 - @cfhay [CodePlex #18958](https://phpexcel.codeplex.com/workitem/18958) - Modify listWorksheetNames() and listWorksheetInfo to use XMLReader with streamed XML rather than SimpleXML - @MarkBaker [#78](https://github.com/PHPOffice/PHPExcel/issues/78) - Restructuring of PHPExcel Exceptions - @dbonsch - Refactor Calculation Engine from singleton to a Multiton - @MarkBaker - Ensures that calculation cache is maintained independently for different workbooks ## [1.7.8] - 2012-10-12 ### Features - Phar builder script to add phar file as a distribution option - @kkamkou - Refactor PDF Writer to allow use with a choice of PDF Rendering library - @MarkBaker - rather than restricting to tcPDF - Current options are tcPDF, mPDF, DomPDF - tcPDF Library has now been removed from the deployment bundle- Initial version of HTML Reader - @MarkBaker - Implement support for AutoFilter in PHPExcel_Writer_Excel5 - @Progi1984 - Modified ERF and ERFC Engineering functions to accept Excel 2010's modified acceptance of negative arguments - @MarkBaker - Support SheetView `view` attribute (Excel2007) - @k1LoW - Excel compatibility option added for writing CSV files - @MarkBaker - While Excel 2010 can read CSV files with a simple UTF-8 BOM, Excel2007 and earlier require UTF-16LE encoded tab-separated files. - The new setExcelCompatibility(TRUE) option for the CSV Writer will generate files with this formatting for easy import into Excel2007 and below.- Language implementations for Turkish (tr) - @MarkBaker - Added fraction tests to advanced value binder - @MarkBaker ### General - Allow call to font setUnderline() for underline format to specify a simple boolean for UNDERLINE_NONE or UNDERLINE_SINGLE - @MarkBaker - Add Currency detection to the Advanced Value Binder - @alexgann - setCellValueExplicitByColumnAndRow() do not return PHPExcel_Worksheet - @MarkBaker [CodePlex #18404](https://phpexcel.codeplex.com/workitem/18404) - Reader factory doesn't read anymore XLTX and XLT files - @MarkBaker [CodePlex #18324](https://phpexcel.codeplex.com/workitem/18324) - Magic __toString() method added to Cell object to return raw data value as a string - @MarkBaker - Add cell indent to html rendering - @alexgann ### Bugfixes - ZeroHeight for rows in sheet format - @Raghav1981 - OOCalc cells containing inside the tag - @cyberconte - Fix to listWorksheetInfo() method for OOCalc Reader - @schir1964 - Support for "e" (epoch) date format mask - @MarkBaker - Rendered as a 4-digit CE year in non-Excel outputs- Background color cell is always black when editing cell - @MarkBaker - Allow "no impact" to formats on Conditional Formatting - @MarkBaker - OOCalc Reader fix for NULL cells - @wackonline - Fix to excel2007 Chart Writer when a $plotSeriesValues is empty - @seltzlab - Various fixes to Chart handling - @MarkBaker - Error loading xlsx file with column breaks - @MarkBaker [CodePlex #18370](https://phpexcel.codeplex.com/workitem/18370) - OOCalc Reader now handles percentage and currency data types - @MarkBaker - mb_stripos empty delimiter - @MarkBaker - getNestingLevel() Error on Excel5 Read - @takaakik - Fix to Excel5 Reader when cell annotations are defined before their referenced text objects - @MarkBaker - OOCalc Reader modified to process number-rows-repeated - @MarkBaker - Chart Title compatibility on Excel 2007 - @MarkBaker [CodePlex #18377](https://phpexcel.codeplex.com/workitem/18377) - Chart Refresh returning cell reference rather than values - @MarkBaker [CodePlex #18146](https://phpexcel.codeplex.com/workitem/18146) - Autoshape being identified in twoCellAnchor when includeCharts is TRUE triggering load error - @MarkBaker [CodePlex #18145](https://phpexcel.codeplex.com/workitem/18145) - v-type texts for series labels now recognised and parsed correctly - @MarkBaker [CodePlex #18325](https://phpexcel.codeplex.com/workitem/18325) - load file failed if the file has no extensionType - @wolf5x [CodePlex #18492](https://phpexcel.codeplex.com/workitem/18492) - Pattern fill colours in Excel2007 Style Writer - @dverspui - Excel2007 Writer order of font style elements to conform with Excel2003 using compatibility pack - @MarkBaker - Problems with $_activeSheetIndex when decreased below 0. - @MarkBaker [CodePlex #18425](https://phpexcel.codeplex.com/workitem/18425) - PHPExcel_CachedObjectStorage_SQLite3::cacheMethodIsAvailable() uses class_exists - autoloader throws error - @MarkBaker [CodePlex #18597](https://phpexcel.codeplex.com/workitem/18597) - Cannot access private property PHPExcel_CachedObjectStorageFactory::$_cacheStorageMethod - @MarkBaker [CodePlex #18598](https://phpexcel.codeplex.com/workitem/18598) - Data titles for charts - @MarkBaker [CodePlex #18397](https://phpexcel.codeplex.com/workitem/18397) - PHPExcel_Chart_Layout now has methods for getting/setting switches for displaying/hiding chart data labels- Discard single cell merge ranges when reading (stupid that Excel allows them in the first place) - @MarkBaker - Discard hidden autoFilter named ranges - @MarkBaker ## [1.7.7] - 2012-05-19 ### Bugfixes - Support for Rich-Text in PHPExcel_Writer_Excel5 - @Progi1984 [CodePlex #8916](https://phpexcel.codeplex.com/workitem/8916) - Change iterators to implement Iterator rather than extend CachingIterator, as a fix for PHP 5.4. changes in SPL - @MarkBaker - Invalid cell coordinate in Autofilter for Excel2007 Writer - @MarkBaker [CodePlex #15459](https://phpexcel.codeplex.com/workitem/15459) - PCLZip library issue - @MarkBaker [CodePlex #15518](https://phpexcel.codeplex.com/workitem/15518) - Excel2007 Reader canRead function bug - @MarkBaker [CodePlex #15537](https://phpexcel.codeplex.com/workitem/15537) - Support for Excel functions whose return can be used as either a value or as a cell reference depending on its context within a formula - @MarkBaker - ini_set() call in Calculation class destructor - @gilles06 [CodePlex #15707](https://phpexcel.codeplex.com/workitem/15707) - RangeToArray strange array keys - @MarkBaker [CodePlex #15786](https://phpexcel.codeplex.com/workitem/15786) - INDIRECT() function doesn't work with named ranges - @MarkBaker [CodePlex #15762](https://phpexcel.codeplex.com/workitem/15762) - Locale-specific fix to text functions when passing a boolean argument instead of a string - @MarkBaker - reader/CSV fails on this file - @MarkBaker [CodePlex #16246](https://phpexcel.codeplex.com/workitem/16246) - auto_detect_line_endings now set in CSV reader- $arguments improperly used in CachedObjectStorage/PHPTemp.php - @MarkBaker [CodePlex #16212](https://phpexcel.codeplex.com/workitem/16212) - Bug In Cache System (cell reference when throwing caching errors) - @MarkBaker [CodePlex #16643](https://phpexcel.codeplex.com/workitem/16643) - PHP Invalid index notice on writing excel file when active sheet has been deleted - @MarkBaker [CodePlex #16895](https://phpexcel.codeplex.com/workitem/16895) - External links in Excel2010 files cause Fatal error - @MarkBaker [CodePlex #16956](https://phpexcel.codeplex.com/workitem/16956) - Previous calculation engine error conditions trigger cyclic reference errors - @MarkBaker [CodePlex #16960](https://phpexcel.codeplex.com/workitem/16960) - PHPExcel_Style::applyFromArray() returns null rather than style object in advanced mode - @mkopinsky [CodePlex #16266](https://phpexcel.codeplex.com/workitem/16266) - Cell::getFormattedValue returns RichText object instead of string - @fauvel [CodePlex #16958](https://phpexcel.codeplex.com/workitem/16958) - Indexed colors do not refer to Excel's indexed colors? - @MarkBaker [CodePlex #17166](https://phpexcel.codeplex.com/workitem/17166) - Indexed colors should be consistent with Excel and start from 1 (current index starts at 0) - @MarkBaker [CodePlex #17199](https://phpexcel.codeplex.com/workitem/17199) - Named Range definition in .xls when sheet reeference is quote wrapped - @MarkBaker [CodePlex #17262](https://phpexcel.codeplex.com/workitem/17262) - duplicateStyle() method doesn't duplicate conditional formats - @MarkBaker [CodePlex #17403](https://phpexcel.codeplex.com/workitem/17403) - Added an equivalent duplicateConditionalStyle() method for duplicating conditional styles- =sumproduct(A,B) <> =sumproduct(B,A) in xlsx - @bnr [CodePlex #17501](https://phpexcel.codeplex.com/workitem/17501) ### Features - OOCalc cells contain same data bug? - @cyberconte [CodePlex #17471](https://phpexcel.codeplex.com/workitem/17471) - listWorksheetInfo() method added to Readers... courtesy of Christopher Mullins - @schir1964 - Options for cell caching using Igbinary and SQLite/SQlite3. - @MarkBaker - Additional row iterator options: allow a start row to be defined in the constructor; seek(), and prev() methods added. - @MarkBaker - Implement document properties in Excel5 writer - @Progi1984 [CodePlex #9759](https://phpexcel.codeplex.com/workitem/9759) ### General - Implement chart functionality (EXPERIMENTAL) - @MarkBaker [CodePlex #16](https://phpexcel.codeplex.com/workitem/16) - Initial definition of chart objects. - Reading Chart definitions through the Excel2007 Reader - Facility to render charts to images using the 3rd-party jpgraph library - Writing Charts using the Excel2007 Writer- Fix to build to ensure that Examples are included with the documentation - @MarkBaker - Reduce cell caching overhead using dirty flag to ensure that cells are only rewritten to the cache if they have actually been changed - @MarkBaker - Improved memory usage in CSV Writer - @MarkBaker - Improved speed and memory usage in Excel5 Writer - @MarkBaker - Experimental - @MarkBaker - Added getHighestDataColumn(), getHighestDataRow(), getHighestRowAndColumn() and calculateWorksheetDataDimension() methods for the worksheet that return the highest row and column that have cell records- Support for Rich-Text in PHPExcel_Writer_Excel5 - @Progi1984 [CodePlex #8916](https://phpexcel.codeplex.com/workitem/8916) - Two easy to fix Issues concerning PHPExcel_Token_Stack (l10n/UC) - @MarkBaker [CodePlex #15405](https://phpexcel.codeplex.com/workitem/15405) - Locale file paths not fit for windows - @MarkBaker [CodePlex #15461](https://phpexcel.codeplex.com/workitem/15461) - Add file directory as a cache option for cache_to_discISAM - @MarkBaker [CodePlex #16643](https://phpexcel.codeplex.com/workitem/16643) - Datatype.php & constant TYPE_NULL - @MarkBaker [CodePlex #16923](https://phpexcel.codeplex.com/workitem/16923) - Ensure use of system temp directory for all temporary work files, unless explicitly specified - @MarkBaker - [Patch] faster stringFromColumnIndex() - @char101 [CodePlex #16359](https://phpexcel.codeplex.com/workitem/16359) - Fix for projects that still use old autoloaders - @whit1206 [CodePlex #16028](https://phpexcel.codeplex.com/workitem/16028) - Unknown codepage: 10007 - @atz [CodePlex #17024](https://phpexcel.codeplex.com/workitem/17024) - Additional Mac codepages ## [1.7.6] - 2011-02-27 ### Features - Provide option to use PCLZip as an alternative to ZipArchive. - @MarkBaker - This allows the writing of Excel2007 files, even without ZipArchive enabled (it does require zlib), or when php_zip is one of the buggy PHP 5.2.6 or 5.2.8 versions - It can be enabled using PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP); - Note that it is not yet implemented as an alternative to ZipArchive for those Readers that are extracting from zips- Added listWorksheetNames() method to Readers that support multiple worksheets in a workbook, allowing a user to extract a list of all the worksheet names from a file without parsing/loading the whole file. - @MarkBaker [CodePlex #14979](https://phpexcel.codeplex.com/workitem/14979) - Speed boost and memory reduction in the Worksheet toArray() method. - @MarkBaker - Added new rangeToArray() and namedRangeToArray() methods to the PHPExcel_Worksheet object. - @MarkBaker - Functionally, these are identical to the toArray() method, except that they take an additional first parameter of a Range (e.g. 'B2:C3') or a Named Range name. - Modified the toArray() method so that it actually uses rangeToArray().- Added support for cell comments in the OOCalc, Gnumeric and Excel2003XML Readers, and in the Excel5 Reader - @MarkBaker - Improved toFormattedString() handling for Currency and Accounting formats to render currency symbols - @MarkBaker ### Bugfixes - Implement more Excel calculation functions - @MarkBaker - Implemented the DAVERAGE(), DCOUNT(), DCOUNTA(), DGET(), DMAX(), DMIN(), DPRODUCT(), DSTDEV(), DSTDEVP(), DSUM(), DVAR() and DVARP() Database functions- Simple =IF() formula disappears - @MarkBaker [CodePlex #14888](https://phpexcel.codeplex.com/workitem/14888) - PHP Warning: preg_match(): Compilation failed: PCRE does not support \\L, \\l, \\N, \\P, \\p, \\U, \\u, or \\X - @MarkBaker [CodePlex #14898](https://phpexcel.codeplex.com/workitem/14898) - VLOOKUP choking on parameters in PHPExcel.1.7.5/PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #14901](https://phpexcel.codeplex.com/workitem/14901) - PHPExcel_Cell::isInRange() incorrect results - offset by one column - @MarkBaker [CodePlex #14973](https://phpexcel.codeplex.com/workitem/14973) - Treat CodePage of 0 as CP1251 (for .xls files written by applications that don't set the CodePage correctly, such as Apple Numbers) - @MarkBaker - Need method for removing autoFilter - @MarkBaker [CodePlex #11583](https://phpexcel.codeplex.com/workitem/11583) - coordinateFromString throws exception for rows greater than 99,999 - @MarkBaker [CodePlex #15029](https://phpexcel.codeplex.com/workitem/15029) - PHPExcel Excel2007 Reader colour problems with solidfill - @MarkBaker [CodePlex #14999](https://phpexcel.codeplex.com/workitem/14999) - Formatting get lost and edit a template XLSX file - @MarkBaker [CodePlex #13215](https://phpexcel.codeplex.com/workitem/13215) - Excel 2007 Reader /writer lost fontcolor - @MarkBaker [CodePlex #14029](https://phpexcel.codeplex.com/workitem/14029) - file that makes cells go black - @MarkBaker [CodePlex #13374](https://phpexcel.codeplex.com/workitem/13374) - Minor patchfix for Excel2003XML Reader when XML is defined with a charset attribute - @MarkBaker - PHPExcel_Worksheet->toArray() index problem - @MarkBaker [CodePlex #15089](https://phpexcel.codeplex.com/workitem/15089) - Merge cells 'un-merge' when using an existing spreadsheet - @MarkBaker [CodePlex #15094](https://phpexcel.codeplex.com/workitem/15094) - Worksheet fromArray() only working with 2-D arrays - @MarkBaker [CodePlex #15129](https://phpexcel.codeplex.com/workitem/15129) - rangeToarray function modified for non-existent cells - @xkeshav [CodePlex #15172](https://phpexcel.codeplex.com/workitem/15172) - Images not getting copyied with the ->clone function - @MarkBaker [CodePlex #14980](https://phpexcel.codeplex.com/workitem/14980) - AdvancedValueBinder.php: String sometimes becomes a date when it shouldn't - @MarkBaker [CodePlex #11576](https://phpexcel.codeplex.com/workitem/11576) - Fix Excel5 Writer so that it only writes column dimensions for columns that are actually used rather than the full range (A to IV) - @MarkBaker - FreezePane causing damaged or modified error - @MarkBaker [CodePlex #15198](https://phpexcel.codeplex.com/workitem/15198) - The freezePaneByColumnAndRow() method row argument should default to 1 rather than 0. - Default row argument for all __ByColumnAndRow() methods should be 1- Column reference rather than cell reference in Print Area definition - @MarkBaker [CodePlex #15121](https://phpexcel.codeplex.com/workitem/15121) - Fix Excel2007 Writer to handle print areas that are defined as row or column ranges rather than just as cell ranges- Reduced false positives from isDateTimeFormatCode() method by suppressing testing within quoted strings - @MarkBaker - Caching and tmp partition exhaustion - @MarkBaker [CodePlex #15312](https://phpexcel.codeplex.com/workitem/15312) - Writing to Variable No Longer Works. $_tmp_dir Missing in PHPExcel\PHPExcel\Shared\OLE\PPS\Root.php - @MarkBaker [CodePlex #15308](https://phpexcel.codeplex.com/workitem/15308) - Named ranges with dot don't get parsed properly - @MarkBaker [CodePlex #15379](https://phpexcel.codeplex.com/workitem/15379) - insertNewRowBefore fails to consistently update references - @MarkBaker [CodePlex #15096](https://phpexcel.codeplex.com/workitem/15096) - "i" is not a valid character for Excel date format masks (in isDateTimeFormatCode() method) - @MarkBaker - PHPExcel_ReferenceHelper::insertNewBefore() is missing an 'Update worksheet: comments' section - @MKunert [CodePlex #15421](https://phpexcel.codeplex.com/workitem/15421) ### General - Full column/row references in named ranges not supported by updateCellReference() - @MarkBaker [CodePlex #15409](https://phpexcel.codeplex.com/workitem/15409) - Improved performance (speed), for building the Shared Strings table in the Excel2007 Writer. - @MarkBaker - Improved performance (speed), for PHP to Excel date conversions - @MarkBaker - Enhanced SheetViews element structures in the Excel2007 Writer for frozen panes. - @MarkBaker - Removed Serialized Reader/Writer as these no longer work. - @MarkBaker ## [1.7.5] - 2010-12-10 ### Features - Implement Gnumeric File Format - @MarkBaker [CodePlex #8769](https://phpexcel.codeplex.com/workitem/8769) - Initial work on Gnumeric Reader (Worksheet Data, Document Properties and basic Formatting)- Support for Extended Workbook Properties in Excel2007, Excel5 and OOCalc Readers; support for User-defined Workbook Properties in Excel2007 and OOCalc Readers - @MarkBaker - Support for Extended and User-defined Workbook Properties in Excel2007 Writer - @MarkBaker - Provided a setGenerateSheetNavigationBlock(false); option to suppress generation of the sheet navigation block when writing multiple worksheets to HTML - @MarkBaker - Advanced Value Binder now recognises TRUE/FALSE strings (locale-specific) and converts to boolean - @MarkBaker - PHPExcel_Worksheet->toArray() is returning truncated values - @MarkBaker [CodePlex #14301](https://phpexcel.codeplex.com/workitem/14301) - Configure PDF Writer margins based on Excel Worksheet Margin Settings value - @MarkBaker - Added Contiguous flag for the CSV Reader, when working with Read Filters - @MarkBaker - Added getFormattedValue() method for cell object - @MarkBaker - Added strictNullComparison argument to the worksheet fromArray() method - @MarkBaker ### Bugfixes - Fix to toFormattedString() method in PHPExcel_Style_NumberFormat to handle fractions with a # code for the integer part - @MarkBaker - NA() doesn't propagate in matrix calc - quick fix in JAMA/Matrix.php - @MarkBaker [CodePlex #14143](https://phpexcel.codeplex.com/workitem/14143) - Excel5 : Formula : String constant containing double quotation mark - @Progi1984 [CodePlex #7895](https://phpexcel.codeplex.com/workitem/7895) - Excel5 : Formula : Percent - @Progi1984 [CodePlex #7895](https://phpexcel.codeplex.com/workitem/7895) - Excel5 : Formula : Error constant - @Progi1984 [CodePlex #7895](https://phpexcel.codeplex.com/workitem/7895) - Excel5 : Formula : Concatenation operator - @Progi1984 [CodePlex #7895](https://phpexcel.codeplex.com/workitem/7895) - Worksheet clone broken for CachedObjectStorage_Memory - @MarkBaker [CodePlex #14146](https://phpexcel.codeplex.com/workitem/14146) - PHPExcel_Reader_Excel2007 fails when gradient fill without type is present in a file - @MarkBaker [CodePlex #12998](https://phpexcel.codeplex.com/workitem/12998) - @ format for numeric strings in XLSX to CSV conversion - @MarkBaker [CodePlex #14176](https://phpexcel.codeplex.com/workitem/14176) - Advanced Value Binder Not Working? - @MarkBaker [CodePlex #14223](https://phpexcel.codeplex.com/workitem/14223) - unassigned object variable in PHPExcel->removeCellXfByIndex - @MarkBaker [CodePlex #14226](https://phpexcel.codeplex.com/workitem/14226) - problem with getting cell values from another worksheet... (if cell doesn't exist) - @MarkBaker [CodePlex #14236](https://phpexcel.codeplex.com/workitem/14236) - Setting cell values to one char strings & Trouble reading one character string (thanks gorfou) - @MarkBaker - Worksheet title exception when duplicate worksheet is being renamed but exceeds the 31 character limit - @MarkBaker [CodePlex #14256](https://phpexcel.codeplex.com/workitem/14256) - Named range with sheet name that contains the $ throws exception when getting the cell - @MarkBaker [CodePlex #14086](https://phpexcel.codeplex.com/workitem/14086) - Added autoloader to DefaultValueBinder and AdvancedValueBinder - @MarkBaker - Modified PHPExcel_Shared_Date::isDateTimeFormatCode() to return false if format code begins with "_" or with "0 " to prevent false positives - @MarkBaker - These leading characters are most commonly associated with number, currency or accounting (or occasionally fraction) formats- BUG : Excel5 and setReadFilter ? - @MarkBaker [CodePlex #14374](https://phpexcel.codeplex.com/workitem/14374) - Wrong exception message while deleting column - @MarkBaker [CodePlex #14425](https://phpexcel.codeplex.com/workitem/14425) - Formula evaluation fails with Japanese sheet refs - @MarkBaker [CodePlex #14679](https://phpexcel.codeplex.com/workitem/14679) - PHPExcel_Writer_PDF does not handle cell borders correctly - @MarkBaker [CodePlex #13559](https://phpexcel.codeplex.com/workitem/13559) - Style : applyFromArray() for 'allborders' not working - @MarkBaker [CodePlex #14831](https://phpexcel.codeplex.com/workitem/14831) ### General - Using $this when not in object context in Excel5 Reader - @MarkBaker [CodePlex #14837](https://phpexcel.codeplex.com/workitem/14837) - Removes a unnecessary loop through each cell when applying conditional formatting to a range. - @MarkBaker - Removed spurious PHP end tags (?>) - @MarkBaker - Improved performance (speed) and reduced memory overheads, particularly for the Writers, but across the whole library. - @MarkBaker ## [1.7.4] - 2010-08-26 ### Bugfixes - Excel5 : Formula : Power - @Progi1984 [CodePlex #7895](https://phpexcel.codeplex.com/workitem/7895) - Excel5 : Formula : Unary plus - @Progi1984 [CodePlex #7895](https://phpexcel.codeplex.com/workitem/7895) - Excel5 : Just write the Escher stream if necessary in Worksheet - @Progi1984 - Syntax errors in memcache.php 1.7.3c - @MarkBaker [CodePlex #13433](https://phpexcel.codeplex.com/workitem/13433) - Support for row or column ranges in the calculation engine, e.g. =SUM(C:C) or =SUM(1:2) - @MarkBaker - Also support in the calculation engine for absolute row or column ranges e.g. =SUM($C:$E) or =SUM($3:5)- Picture problem with Excel 2003 - @Erik Tilt [CodePlex #13455](https://phpexcel.codeplex.com/workitem/13455) - Wrong variable used in addExternalSheet in PHPExcel.php - @MarkBaker [CodePlex #13484](https://phpexcel.codeplex.com/workitem/13484) - "Invalid cell coordinate" error when formula access data from an other sheet - @MarkBaker [CodePlex #13515](https://phpexcel.codeplex.com/workitem/13515) - (related to Work item 13515) Calculation engine confusing cell range worksheet when referencing cells in a different worksheet to the formula - @MarkBaker - Wrong var naming in Worksheet->garbageCollect() - @MarkBaker [CodePlex #13752](https://phpexcel.codeplex.com/workitem/13752) - PHPExcel_Style_*::__clone() methods cause cloning loops? - @MarkBaker [CodePlex #13764](https://phpexcel.codeplex.com/workitem/13764) - Recent builds causing problems loading xlsx files? (ZipArchive issue?) - @MarkBaker [CodePlex #11488](https://phpexcel.codeplex.com/workitem/11488) - cache_to_apc causes fatal error when processing large data sets - @MarkBaker [CodePlex #13856](https://phpexcel.codeplex.com/workitem/13856) - OOCalc reader misses first line if it's a 'table-header-row' - @MarkBaker [CodePlex #13880](https://phpexcel.codeplex.com/workitem/13880) - using cache with copy or clone bug? - @MarkBaker [CodePlex #14011](https://phpexcel.codeplex.com/workitem/14011) - Fixed $worksheet->copy() or clone $worksheet when using cache_in_memory, cache_in_memory_gzip, cache_in_memory_serialized, cache_to_discISAM, cache_to_phpTemp, cache_to_apc and cache_to_memcache; - Fixed but untested when using cache_to_wincache. ### Features - Standard Deviation functions returning DIV/0 Error when Standard Deviation is zero - @MarkBaker [CodePlex #13450](https://phpexcel.codeplex.com/workitem/13450) - Support for print area with several ranges in the Excel2007 reader, and improved features for editing print area with several ranges - @MarkBaker - Improved Cell Exception Reporting - @MarkBaker [CodePlex #13769](https://phpexcel.codeplex.com/workitem/13769) ### General - Fixed problems with reading Excel2007 Properties - @MarkBaker - PHP Strict Standards: Non-static method PHPExcel_Shared_String::utf16_decode() should not be called statically - @MarkBaker - Array functions were ignored when loading an existing file containing them, and as a result, they would lose their 'cse' status. - @MarkBaker - Minor memory tweaks to Excel2007 Writer - @MarkBaker - Modified ReferenceHelper updateFormulaReferences() method to handle updates to row and column cell ranges (including absolute references e.g. =SUM(A:$E) or =SUM($5:5), and range/cell references that reference a worksheet by name), and to provide both performance and memory improvements. - @MarkBaker - Modified Excel2007 Reader so that ReferenceHelper class is instantiated only once rather than for every shared formula in a workbook. - @MarkBaker - Correct handling for additional (synonym) formula tokens in Excel5 Reader - @MarkBaker - Additional reading of some Excel2007 Extended Properties (Company, Manager) - @MarkBaker ## [1.7.3c] - 2010-06-01 ### Bugfixes - Fatal error: Class 'ZipArchive' not found... ...Reader/Excel2007.php on line 217 - @MarkBaker [CodePlex #13012](https://phpexcel.codeplex.com/workitem/13012) - PHPExcel_Writer_Excel2007 error after 1.7.3b - @MarkBaker [CodePlex #13398](https://phpexcel.codeplex.com/workitem/13398) ## [1.7.3b] - 2010-05-31 ### Bugfixes - Infinite loop when reading - @MarkBaker [CodePlex #12903](https://phpexcel.codeplex.com/workitem/12903) - Wrong method chaining on PHPExcel_Worksheet class - @MarkBaker [CodePlex #13381](https://phpexcel.codeplex.com/workitem/13381) ## [1.7.3] - 2010-05-17 ### General - Applied patch 4990 (modified) - @Erik Tilt - Applied patch 5568 (modified) - @MarkBaker - Applied patch 5943 - @MarkBaker - Upgrade build script to use Phing - @MarkBaker [CodePlex #13042](https://phpexcel.codeplex.com/workitem/13042) - Replacing var with public/private - @Erik Tilt [CodePlex #11586](https://phpexcel.codeplex.com/workitem/11586) - Applied Anthony's Sterling's Class Autoloader to reduce memory overhead by "Lazy Loading" of classes - @MarkBaker - Modification to functions that accept a date parameter to support string values containing ordinals as per Excel (English language only) - @MarkBaker - Modify PHPExcel_Style_NumberFormat::toFormattedString() to handle dates that fall outside of PHP's 32-bit date range - @MarkBaker - Applied patch 5207 - @MarkBaker ### Features - PHPExcel developer documentation: Set page margins - @Erik Tilt [CodePlex #11970](https://phpexcel.codeplex.com/workitem/11970) - Special characters and accents in SYLK reader - @Erik Tilt [CodePlex #11038](https://phpexcel.codeplex.com/workitem/11038) - Implement more Excel calculation functions - @MarkBaker - Implemented the COUPDAYS(), COUPDAYBS(), COUPDAYSNC(), COUPNCD(), COUPPCD() and PRICE() Financial functions - Implemented the N() and TYPE() Information functions - Implemented the HYPERLINK() Lookup and Reference function- Horizontal page break support in PHPExcel_Writer_PDF - @Erik Tilt [CodePlex #11526](https://phpexcel.codeplex.com/workitem/11526) - Introduce method setActiveSheetIndexByName() - @Erik Tilt [CodePlex #11529](https://phpexcel.codeplex.com/workitem/11529) - AdvancedValueBinder.php: Automatically wrap text when there is new line in string (ALT+"Enter") - @Erik Tilt [CodePlex #11550](https://phpexcel.codeplex.com/workitem/11550) - Data validation support in PHPExcel_Reader_Excel5 and PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10300](https://phpexcel.codeplex.com/workitem/10300) - Improve autosize calculation - @MarkBaker [CodePlex #11616](https://phpexcel.codeplex.com/workitem/11616) - Methods to translate locale-specific function names in formulae - @MarkBaker - Language implementations for Czech (cs), Danish (da), German (de), English (uk), Spanish (es), Finnish (fi), French (fr), Hungarian (hu), Italian (it), Dutch (nl), Norwegian (no), Polish (pl), Portuguese (pt), Brazilian Portuguese (pt_br), Russian (ru) and Swedish (sv)- Implement document properties in Excel5 reader/writer - @Erik Tilt [CodePlex #9759](https://phpexcel.codeplex.com/workitem/9759) - Fixed so far for PHPExcel_Reader_Excel5- Show/hide row and column headers in worksheet - @Erik Tilt [CodePlex #11849](https://phpexcel.codeplex.com/workitem/11849) - Can't set font on writing PDF (by key) - @Erik Tilt [CodePlex #11919](https://phpexcel.codeplex.com/workitem/11919) - Thousands scale (1000^n) support in PHPExcel_Style_NumberFormat::toFormattedString - @Erik Tilt [CodePlex #12096](https://phpexcel.codeplex.com/workitem/12096) - Implement repeating rows in PDF and HTML writer - @Erik Tilt - Sheet tabs in PHPExcel_Writer_HTML - @Erik Tilt [CodePlex #12289](https://phpexcel.codeplex.com/workitem/12289) - Add Wincache CachedObjectProvider - @MarkBaker [CodePlex #13041](https://phpexcel.codeplex.com/workitem/13041) - Configure PDF Writer paper size based on Excel Page Settings value, and provided methods to override paper size and page orientation with the writer - @MarkBaker - Note PHPExcel defaults to Letter size, while the previous PDF writer enforced A4 size, so PDF writer will now default to Letter- Initial implementation of cell caching: allowing larger workbooks to be managed, but at a cost in speed - @MarkBaker ### Bugfixes - Added an identify() method to the IO Factory that identifies the reader which will be used to load a particular file without actually loading it. - @MarkBaker - Warning messages with INDEX function having 2 arguments - @MarkBaker [CodePlex #10979](https://phpexcel.codeplex.com/workitem/10979) - setValue('=') should result in string instead of formula - @Erik Tilt [CodePlex #11473](https://phpexcel.codeplex.com/workitem/11473) - method _raiseFormulaError should no be private - @MarkBaker [CodePlex #11471](https://phpexcel.codeplex.com/workitem/11471) - Fatal error: Call to undefined function mb_substr() in ...Classes\PHPExcel\Reader\Excel5.php on line 2903 - @Erik Tilt [CodePlex #11485](https://phpexcel.codeplex.com/workitem/11485) - getBold(), getItallic(), getStrikeThrough() not always working with PHPExcel_Reader_Excel2007 - @Erik Tilt [CodePlex #11487](https://phpexcel.codeplex.com/workitem/11487) - AdvancedValueBinder.php not working correctly for $cell->setValue('hh:mm:ss') - @Erik Tilt [CodePlex #11492](https://phpexcel.codeplex.com/workitem/11492) - Fixed leap year handling for the YEARFRAC() Date/Time function when basis ia 1 (Actual/actual) - @MarkBaker - Warning messages - @MarkBaker [CodePlex #11490](https://phpexcel.codeplex.com/workitem/11490) - Calculation Engine code modified to enforce strict standards for pass by reference- PHPExcel_Cell_AdvancedValueBinder doesnt work for dates in far future - @Erik Tilt [CodePlex #11483](https://phpexcel.codeplex.com/workitem/11483) - MSODRAWING bug with long CONTINUE record in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #11528](https://phpexcel.codeplex.com/workitem/11528) - PHPExcel_Reader_Excel2007 reads print titles as named range when there is more than one sheet - @Erik Tilt [CodePlex #11571](https://phpexcel.codeplex.com/workitem/11571) - missing @return in phpdocblock in reader classes - @Erik Tilt [CodePlex #11561](https://phpexcel.codeplex.com/workitem/11561) - AdvancedValueBinder.php: String sometimes becomes a date when it shouldn't - @Erik Tilt [CodePlex #11576](https://phpexcel.codeplex.com/workitem/11576) - Small numbers escape treatment in PHPExcel_Style_NumberFormat::toFormattedString() - @Erik Tilt [CodePlex #11588](https://phpexcel.codeplex.com/workitem/11588) - Blank styled cells are not blank in output by HTML writer due to   - @Erik Tilt [CodePlex #11590](https://phpexcel.codeplex.com/workitem/11590) - Calculation engine bug: Existing, blank cell + number gives #NUM - @MarkBaker [CodePlex #11587](https://phpexcel.codeplex.com/workitem/11587) - AutoSize only measures length of first line in cell with multiple lines (ALT+Enter) - @Erik Tilt [CodePlex #11608](https://phpexcel.codeplex.com/workitem/11608) - Fatal error running Tests/12serializedfileformat.php (PHPExcel 1.7.2) - @Erik Tilt [CodePlex #11608](https://phpexcel.codeplex.com/workitem/11608) - Fixed various errors in the WORKDAY() and NETWORKDAYS() Date/Time functions (particularly related to holidays) - @MarkBaker - Uncaught exception 'Exception' with message 'Valid scale is between 10 and 400.' in Classes/PHPExcel/Worksheet/SheetView.php:115 - @Erik Tilt [CodePlex #11660](https://phpexcel.codeplex.com/workitem/11660) - "Unrecognized token 39 in formula" with PHPExcel_Reader_Excel5 (occuring with add-in functions) - @Erik Tilt [CodePlex #11551](https://phpexcel.codeplex.com/workitem/11551) - Excel2007 reader not reading PHPExcel_Style_Conditional::CONDITION_EXPRESSION - @Erik Tilt [CodePlex #11668](https://phpexcel.codeplex.com/workitem/11668) - Fix to the BESSELI(), BESSELJ(), BESSELK(), BESSELY() and COMPLEX() Engineering functions to use correct default values for parameters - @MarkBaker - DATEVALUE function not working for pure time values + allow DATEVALUE() function to handle partial dates (e.g. "1-Jun" or "12/2010") - @MarkBaker [CodePlex #11525](https://phpexcel.codeplex.com/workitem/11525) - Fix for empty quoted strings in formulae - @MarkBaker - Trap for division by zero in Bessel functions - @MarkBaker - Fix to OOCalc Reader to convert semi-colon (;) argument separator in formulae to a comma (,) - @MarkBaker - PHPExcel_Writer_Excel5_Parser cannot parse formula like =SUM(C$5:C5) - @Erik Tilt [CodePlex #11693](https://phpexcel.codeplex.com/workitem/11693) - Fix to OOCalc Reader to handle dates that fall outside 32-bit PHP's date range - @MarkBaker - File->sys_get_temp_dir() can fail in safe mode - @Erik Tilt [CodePlex #11692](https://phpexcel.codeplex.com/workitem/11692) - Sheet references in Excel5 writer do not work when referenced sheet title contains non-Latin symbols - @Erik Tilt [CodePlex #11727](https://phpexcel.codeplex.com/workitem/11727) - Bug in HTML writer can result in missing rows in output - @Erik Tilt [CodePlex #11743](https://phpexcel.codeplex.com/workitem/11743) - setShowGridLines(true) not working with PHPExcel_Writer_PDF - @Erik Tilt [CodePlex #11674](https://phpexcel.codeplex.com/workitem/11674) - PHPExcel_Worksheet_RowIterator initial position incorrect - @Erik Tilt [CodePlex #11836](https://phpexcel.codeplex.com/workitem/11836) - PHPExcel_Worksheet_HeaderFooterDrawing Strict Exception thrown (by jshaw86) - @Erik Tilt [CodePlex #11835](https://phpexcel.codeplex.com/workitem/11835) - Parts of worksheet lost when there are embedded charts (Excel5 reader) - @Erik Tilt [CodePlex #11850](https://phpexcel.codeplex.com/workitem/11850) - VLOOKUP() function error when lookup value is passed as a cell reference rather than an absolute value - @MarkBaker - First segment of Rich-Text not read correctly by PHPExcel_Reader_Excel2007 - @Erik Tilt [CodePlex #12041](https://phpexcel.codeplex.com/workitem/12041) - Fatal Error with getCell('name') when name matches the pattern for a cell reference - @MarkBaker [CodePlex #12048](https://phpexcel.codeplex.com/workitem/12048) - excel5 writer appears to be swapping image locations - @Erik Tilt [CodePlex #12039](https://phpexcel.codeplex.com/workitem/12039) - Undefined index: host in ZipStreamWrapper.php, line 94 and line 101 - @Erik Tilt [CodePlex #11954](https://phpexcel.codeplex.com/workitem/11954) - BIFF8 File Format problem (too short COLINFO record) - @Erik Tilt [CodePlex #11672](https://phpexcel.codeplex.com/workitem/11672) - Column width sometimes changed after read/write with Excel2007 reader/writer - @Erik Tilt [CodePlex #12121](https://phpexcel.codeplex.com/workitem/12121) - Worksheet.php throws a fatal error when styling is turned off via setReadDataOnly on the reader - @Erik Tilt [CodePlex #11964](https://phpexcel.codeplex.com/workitem/11964) - Checking for Circular References in Formulae - @MarkBaker [CodePlex #11851](https://phpexcel.codeplex.com/workitem/11851) - Calculation Engine code now traps for cyclic references, raising an error or throwing an exception, or allows 1 or more iterations through cyclic references, based on a configuration setting- PNG transparency using Excel2007 writer - @Erik Tilt [CodePlex #12244](https://phpexcel.codeplex.com/workitem/12244) - Custom readfilter error when cell formulas reference excluded cells (Excel5 reader) - @Erik Tilt [CodePlex #12221](https://phpexcel.codeplex.com/workitem/12221) - Protection problem in XLS - @Erik Tilt [CodePlex #12288](https://phpexcel.codeplex.com/workitem/12288) - getColumnDimension()->setAutoSize() incorrect on cells with Number Formatting - @Erik Tilt [CodePlex #12300](https://phpexcel.codeplex.com/workitem/12300) - Notices reading Excel file with Add-in funcitons (PHPExcel_Reader_Excel5) - @Erik Tilt [CodePlex #12378](https://phpexcel.codeplex.com/workitem/12378) - Excel5 reader not reading formulas with deleted sheet references - @Erik Tilt [CodePlex #12380](https://phpexcel.codeplex.com/workitem/12380) - Named range (defined name) scope problems for in PHPExcel - @Erik Tilt [CodePlex #12404](https://phpexcel.codeplex.com/workitem/12404) - PHP Parse error: syntax error, unexpected T_PUBLIC in PHPExcel/Calculation.php on line 3482 - @Erik Tilt [CodePlex #12423](https://phpexcel.codeplex.com/workitem/12423) - Named ranges don't appear in name box using Excel5 writer - @Erik Tilt [CodePlex #12505](https://phpexcel.codeplex.com/workitem/12505) - Many merged cells + autoSize column -> slows down the writer - @Erik Tilt [CodePlex #12509](https://phpexcel.codeplex.com/workitem/12509) - Incorrect fallback order comment in Shared/Strings.php ConvertEncoding() - @Erik Tilt [CodePlex #12539](https://phpexcel.codeplex.com/workitem/12539) - IBM AIX iconv() will not work, should revert to mbstring etc. instead - @Erik Tilt [CodePlex #12538](https://phpexcel.codeplex.com/workitem/12538) - Excel5 writer and mbstring functions overload - @Erik Tilt [CodePlex #12568](https://phpexcel.codeplex.com/workitem/12568) - OFFSET needs to flattenSingleValue the $rows and $columns args - @MarkBaker [CodePlex #12672](https://phpexcel.codeplex.com/workitem/12672) - Formula with DMAX(): Notice: Undefined offset: 2 in ...\PHPExcel\Calculation.php on line 2365 - @MarkBaker [CodePlex #12546](https://phpexcel.codeplex.com/workitem/12546) - Note that the Database functions have not yet been implemented- Call to a member function getParent() on a non-object in Classes\\PHPExcel\\Calculation.php Title is required - @MarkBaker [CodePlex #12839](https://phpexcel.codeplex.com/workitem/12839) - Cyclic Reference in Formula - @MarkBaker [CodePlex #12935](https://phpexcel.codeplex.com/workitem/12935) - Memory error...data validation? - @MarkBaker [CodePlex #13025](https://phpexcel.codeplex.com/workitem/13025) ## [1.7.2] - 2010-01-11 ### General - Applied patch 4362 - @Erik Tilt - Applied patch 4363 (modified) - @Erik Tilt - 1.7.1 Extremely Slow - Refactored PHPExcel_Calculation_Functions::flattenArray() method and set calculation cache timer default to 2.5 seconds - @MarkBaker [CodePlex #10874](https://phpexcel.codeplex.com/workitem/10874) - Allow formulae to contain line breaks - @MarkBaker - split() function deprecated in PHP 5.3.0 - @Erik Tilt [CodePlex #10910](https://phpexcel.codeplex.com/workitem/10910) - sys_get_temp_dir() requires PHP 5.2.1, not PHP 5.2 [provide fallback function for PHP 5.2.0] - @Erik Tilt - Implementation of the ISPMT() Financial function by Matt Groves - @MarkBaker - Put the example of formula with more arguments in documentation - @MarkBaker [CodePlex #11052](https://phpexcel.codeplex.com/workitem/11052) ### Features - Improved accuracy for the GAMMAINV() Statistical Function - @MarkBaker - XFEXT record support to fix colors change from Excel5 reader, and copy/paste color change with Excel5 writer - @Erik Tilt [CodePlex #10409](https://phpexcel.codeplex.com/workitem/10409) - Excel5 reader reads RGB color information in XFEXT records for borders, font color and fill color- Implement more Excel calculation functions - @MarkBaker - Implemented the FVSCHEDULE(), XNPV(), IRR(), MIRR(), XIRR() and RATE() Financial functions - Implemented the SUMPRODUCT() Mathematical function - Implemented the ZTEST() Statistical Function- Multiple print areas in one sheet - @Erik Tilt [CodePlex #10919](https://phpexcel.codeplex.com/workitem/10919) - Store calculated values in output by PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10930](https://phpexcel.codeplex.com/workitem/10930) - Sheet protection options in Excel5 reader/writer - @Erik Tilt [CodePlex #10939](https://phpexcel.codeplex.com/workitem/10939) - Modification of the COUNT(), AVERAGE(), AVERAGEA(), DEVSQ, AVEDEV(), STDEV(), STDEVA(), STDEVP(), STDEVPA(), VARA() and VARPA() SKEW() and KURT() functions to correctly handle boolean values depending on whether they're passed in as values, values within a matrix or values within a range of cells. - @MarkBaker - Cell range selection - @Erik Tilt - Root-relative path handling - @MarkBaker [CodePlex #10266](https://phpexcel.codeplex.com/workitem/10266) ### Bugfixes - Named Ranges not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #11315](https://phpexcel.codeplex.com/workitem/11315) - Excel2007 Reader fails to load Apache POI generated Excel - @MarkBaker [CodePlex #11206](https://phpexcel.codeplex.com/workitem/11206) - Number format is broken when system's thousands separator is empty - @MarkBaker [CodePlex #11154](https://phpexcel.codeplex.com/workitem/11154) - ReferenceHelper::updateNamedFormulas throws errors if oldName is empty - @MarkBaker [CodePlex #11401](https://phpexcel.codeplex.com/workitem/11401) - parse_url() fails to parse path to an image in xlsx - @MarkBaker [CodePlex #11296](https://phpexcel.codeplex.com/workitem/11296) - Workaround for iconv_substr() bug in PHP 5.2.0 - @Erik Tilt [CodePlex #10876](https://phpexcel.codeplex.com/workitem/10876) - 1 pixel error for image width and height with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10877](https://phpexcel.codeplex.com/workitem/10877) - Fix to GEOMEAN() Statistical function - @MarkBaker - setValue('-') and setValue('.') sets numeric 0 instead of 1-character string - @Erik Tilt [CodePlex #10884](https://phpexcel.codeplex.com/workitem/10884) - Row height sometimes much too low after read with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10885](https://phpexcel.codeplex.com/workitem/10885) - Diagonal border. Miscellaneous missing support. - @Erik Tilt [CodePlex #10888](https://phpexcel.codeplex.com/workitem/10888) - Constant PHPExcel_Style_Borders::DIAGONAL_BOTH added to support double-diagonal (cross) - PHPExcel_Reader_Excel2007 not always reading diagonal borders (only recognizes 'true' and not '1') - PHPExcel_Reader_Excel5 support for diagonal borders - PHPExcel_Writer_Excel5 support for diagonal borders- Session bug: Fatal error: Call to a member function bindValue() on a non-object in ...\Classes\PHPExcel\Cell.php on line 217 - @Erik Tilt [CodePlex #10894](https://phpexcel.codeplex.com/workitem/10894) - Colors messed up saving twice with same instance of PHPExcel_Writer_Excel5 (regression since 1.7.0) - @Erik Tilt [CodePlex #10896](https://phpexcel.codeplex.com/workitem/10896) - Method PHPExcel_Worksheet::setDefaultStyle is not working - @Erik Tilt [CodePlex #10917](https://phpexcel.codeplex.com/workitem/10917) - PHPExcel_Reader_CSV::canRead() sometimes says false when it shouldn't - @Erik Tilt [CodePlex #10897](https://phpexcel.codeplex.com/workitem/10897) - Changes in workbook not picked up between two saves with PHPExcel_Writer_Excel2007 - @Erik Tilt [CodePlex #10922](https://phpexcel.codeplex.com/workitem/10922) - Decimal and thousands separators missing in HTML and PDF output - @Erik Tilt [CodePlex #10913](https://phpexcel.codeplex.com/workitem/10913) - Notices with PHPExcel_Reader_Excel5 and named array constants - @Erik Tilt [CodePlex #10936](https://phpexcel.codeplex.com/workitem/10936) - Calculation engine limitation on 32-bit platform with integers > 2147483647 - @MarkBaker [CodePlex #10938](https://phpexcel.codeplex.com/workitem/10938) - Shared(?) formulae containing absolute cell references not read correctly using Excel5 Reader - @Erik Tilt [CodePlex #10959](https://phpexcel.codeplex.com/workitem/10959) - Warning messages with intersection operator involving single cell - @MarkBaker [CodePlex #10962](https://phpexcel.codeplex.com/workitem/10962) - Infinite loop in Excel5 reader caused by zero-length string in SST - @Erik Tilt [CodePlex #10980](https://phpexcel.codeplex.com/workitem/10980) - Remove unnecessary cell sorting to improve speed by approx. 18% in HTML and PDF writers - @Erik Tilt [CodePlex #10983](https://phpexcel.codeplex.com/workitem/10983) - Cannot read A1 cell content - OO_Reader - @MarkBaker [CodePlex #10977](https://phpexcel.codeplex.com/workitem/10977) - Transliteration failed, invalid encoding - @Erik Tilt [CodePlex #11000](https://phpexcel.codeplex.com/workitem/11000) ## [1.7.1] - 2009-11-02 ### General - ereg() function deprecated in PHP 5.3.0 - @Erik Tilt [CodePlex #10687](https://phpexcel.codeplex.com/workitem/10687) - Writer Interface Inconsequence - setTempDir and setUseDiskCaching - @MarkBaker [CodePlex #10739](https://phpexcel.codeplex.com/workitem/10739) ### Features - Upgrade to TCPDF 4.8.009 - @Erik Tilt - Support for row and column styles (feature request) - @Erik Tilt - Basic implementation for Excel2007/Excel5 reader/writer- Hyperlink to local file in Excel5 reader/writer - @Erik Tilt [CodePlex #10459](https://phpexcel.codeplex.com/workitem/10459) - Color Tab (Color Sheet's name) - @MarkBaker [CodePlex #10472](https://phpexcel.codeplex.com/workitem/10472) - Border style "double" support in PHPExcel_Writer_HTML - @Erik Tilt [CodePlex #10488](https://phpexcel.codeplex.com/workitem/10488) - Multi-section number format support in HTML/PDF/CSV writers - @Erik Tilt [CodePlex #10492](https://phpexcel.codeplex.com/workitem/10492) - Some additional performance tweaks in the calculation engine - @MarkBaker - Fix result of DB() and DDB() Financial functions to 2dp when in Gnumeric Compatibility mode - @MarkBaker - Added AMORDEGRC(), AMORLINC() and COUPNUM() Financial function (no validation of parameters yet) - @MarkBaker - Improved accuracy of TBILLEQ(), TBILLPRICE() and TBILLYIELD() Financial functions when in Excel or Gnumeric mode - @MarkBaker - Added INDIRECT() Lookup/Reference function (only supports full addresses at the moment) - @MarkBaker - PHPExcel_Reader_CSV::canRead() improvements - @MarkBaker [CodePlex #10498](https://phpexcel.codeplex.com/workitem/10498) - Input encoding option for PHPExcel_Reader_CSV - @Erik Tilt [CodePlex #10500](https://phpexcel.codeplex.com/workitem/10500) - Colored number format support, e.g. [Red], in HTML/PDF output - @Erik Tilt [CodePlex #10493](https://phpexcel.codeplex.com/workitem/10493) - Color Tab (Color Sheet's name) [Excel5 reader/writer support] - @Erik Tilt [CodePlex #10559](https://phpexcel.codeplex.com/workitem/10559) - Initial version of SYLK (slk) and Excel 2003 XML Readers (Cell data and basic cell formatting) - @MarkBaker - Initial version of Open Office Calc (ods) Reader (Cell data only) - @MarkBaker - Initial use of "pass by reference" in the calculation engine for ROW() and COLUMN() Lookup/Reference functions - @MarkBaker - COLUMNS() and ROWS() Lookup/Reference functions, and SUBSTITUTE() Text function - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - AdvancedValueBinder(): Re-enable zero-padded string-to-number conversion, e.g '0004' -> 4 - @Erik Tilt [CodePlex #10502](https://phpexcel.codeplex.com/workitem/10502) - Make PHP type match Excel datatype - @Erik Tilt [CodePlex #10600](https://phpexcel.codeplex.com/workitem/10600) - Change first page number on header - @MarkBaker [CodePlex #10630](https://phpexcel.codeplex.com/workitem/10630) - Applied patch 3941 - @MarkBaker - Hidden sheets - @MB,ET [CodePlex #10745](https://phpexcel.codeplex.com/workitem/10745) - mbstring fallback when iconv is broken - @Erik Tilt [CodePlex #10761](https://phpexcel.codeplex.com/workitem/10761) - Note, can't yet handle comparison of two matrices - @MarkBaker - Improved handling for validation and error trapping in a number of functions - @MarkBaker - Improved support for fraction number formatting - @MarkBaker - Support Reading CSV with Byte Order Mark (BOM) - @Erik Tilt [CodePlex #10455](https://phpexcel.codeplex.com/workitem/10455) ### Bugfixes - addExternalSheet() at specified index - @Erik Tilt [CodePlex #10860](https://phpexcel.codeplex.com/workitem/10860) - Named range can no longer be passed to worksheet->getCell() - @MarkBaker [CodePlex #10684](https://phpexcel.codeplex.com/workitem/10684) - RichText HTML entities no longer working in PHPExcel 1.7.0 - @Erik Tilt [CodePlex #10455](https://phpexcel.codeplex.com/workitem/10455) - Fit-to-width value of 1 is lost after read/write of Excel2007 spreadsheet [+ support for simultaneous scale/fitToPage] - @Erik Tilt - Performance issue identified by profiling - @MarkBaker [CodePlex #10469](https://phpexcel.codeplex.com/workitem/10469) - setSelectedCell is wrong - @Erik Tilt [CodePlex #10473](https://phpexcel.codeplex.com/workitem/10473) - Images get squeezed/stretched with (Mac) Verdana 10 Excel files using Excel5 reader/writer - @Erik Tilt [CodePlex #10481](https://phpexcel.codeplex.com/workitem/10481) - Error in argument count for DATEDIF() function - @MarkBaker [CodePlex #10482](https://phpexcel.codeplex.com/workitem/10482) - updateFormulaReferences is buggy - @MarkBaker [CodePlex #10452](https://phpexcel.codeplex.com/workitem/10452) - CellIterator returns null Cell if onlyExistingCells is set and key() is in use - @MarkBaker [CodePlex #10485](https://phpexcel.codeplex.com/workitem/10485) - Wrong RegEx for parsing cell references in formulas - @MarkBaker [CodePlex #10453](https://phpexcel.codeplex.com/workitem/10453) - Optimisation subverted to devastating effect if IterateOnlyExistingCells is clear - @MarkBaker [CodePlex #10486](https://phpexcel.codeplex.com/workitem/10486) - Fatal error: Uncaught exception 'Exception' with message 'Unrecognized token 6C in formula'... with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10494](https://phpexcel.codeplex.com/workitem/10494) - Fractions stored as text are not treated as numbers by PHPExcel's calculation engine - @MarkBaker [CodePlex #10490](https://phpexcel.codeplex.com/workitem/10490) - AutoFit (autosize) row height not working in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10503](https://phpexcel.codeplex.com/workitem/10503) - Fixed problem with null values breaking the calculation stack - @MarkBaker - Date number formats sometimes fail with PHPExcel_Style_NumberFormat::toFormattedString, e.g. [$-40047]mmmm d yyyy - @Erik Tilt [CodePlex #10524](https://phpexcel.codeplex.com/workitem/10524) - Fixed minor problem with DATEDIFF YM calculation - @MarkBaker - Applied patch 3695 - @MarkBaker - setAutosize() and Date cells not working properly - @Erik Tilt [CodePlex #10536](https://phpexcel.codeplex.com/workitem/10536) - Time value hour offset in output by HTML/PDF/CSV writers (system timezone problem) - @Erik Tilt [CodePlex #10556](https://phpexcel.codeplex.com/workitem/10556) - Control characters 0x14-0x1F are not treated by PHPExcel - @Erik Tilt [CodePlex #10558](https://phpexcel.codeplex.com/workitem/10558) - PHPExcel_Writer_Excel5 not working when open_basedir restriction is in effect - @Erik Tilt [CodePlex #10560](https://phpexcel.codeplex.com/workitem/10560) - IF formula calculation problem in PHPExcel 1.7.0 (string comparisons) - @MarkBaker [CodePlex #10563](https://phpexcel.codeplex.com/workitem/10563) - Improved CODE() Text function result for UTF-8 characters - @MarkBaker - Empty rows are collapsed with HTML/PDF writer - @Erik Tilt [CodePlex #10568](https://phpexcel.codeplex.com/workitem/10568) - Gaps between rows in output by PHPExcel_Writer_PDF (Upgrading to TCPDF 4.7.003) - @Erik Tilt [CodePlex #10569](https://phpexcel.codeplex.com/workitem/10569) - Problem reading formulas (Excel5 reader problem with "fake" shared formulas) - @Erik Tilt [CodePlex #10575](https://phpexcel.codeplex.com/workitem/10575) - Error type in formula: "_raiseFormulaError message is Formula Error: An unexpected error occured" - @MarkBaker [CodePlex #10588](https://phpexcel.codeplex.com/workitem/10588) - Miscellaneous column width problems in Excel5/Excel2007 writer - @Erik Tilt [CodePlex #10599](https://phpexcel.codeplex.com/workitem/10599) - Reader/Excel5 'Unrecognized token 2D in formula' in latest version - @Erik Tilt [CodePlex #10615](https://phpexcel.codeplex.com/workitem/10615) - on php 5.3 PHPExcel 1.7 Excel 5 reader fails in _getNextToken, token = 2C, throws exception - @Erik Tilt [CodePlex #10623](https://phpexcel.codeplex.com/workitem/10623) - Fatal error when altering styles after workbook has been saved - @Erik Tilt [CodePlex #10617](https://phpexcel.codeplex.com/workitem/10617) - Images vertically stretched or squeezed when default font size is changed (PHPExcel_Writer_Excel5) - @Erik Tilt [CodePlex #10661](https://phpexcel.codeplex.com/workitem/10661) - Styles not read in "manipulated" Excel2007 workbook - @Erik Tilt [CodePlex #10676](https://phpexcel.codeplex.com/workitem/10676) - Windows 7 says corrupt file by PHPExcel_Writer_Excel5 when opening in Excel - @Erik Tilt [CodePlex #10059](https://phpexcel.codeplex.com/workitem/10059) - Calculations sometimes not working with cell references to other sheets - @MarkBaker [CodePlex #10708](https://phpexcel.codeplex.com/workitem/10708) - Problem with merged cells after insertNewRowBefore() - @Erik Tilt [CodePlex #10706](https://phpexcel.codeplex.com/workitem/10706) - Applied patch 4023 - @MarkBaker - Fix to SUMIF() and COUNTIF() Statistical functions for when condition is a match against a string value - @MarkBaker - PHPExcel_Cell::coordinateFromString should throw exception for bad string parameter - @Erik Tilt [CodePlex #10721](https://phpexcel.codeplex.com/workitem/10721) - EucrosiaUPC (Thai font) not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10723](https://phpexcel.codeplex.com/workitem/10723) - Improved the return of calculated results when the result value is an array - @MarkBaker - Allow calculation engine to support Functions prefixed with @ within formulae - @MarkBaker - Intersection operator (space operator) fatal error with calculation engine - @MarkBaker [CodePlex #10632](https://phpexcel.codeplex.com/workitem/10632) - Chinese, Japanese, Korean characters show as squares in PDF - @Erik Tilt [CodePlex #10742](https://phpexcel.codeplex.com/workitem/10742) - sheet title allows invalid characters - @Erik Tilt [CodePlex #10756](https://phpexcel.codeplex.com/workitem/10756) - Sheet!$A$1 as function argument in formula causes infinite loop in Excel5 writer - @Erik Tilt [CodePlex #10757](https://phpexcel.codeplex.com/workitem/10757) - Cell range involving name not working with calculation engine - Modified calculation parser to handle range operator (:), but doesn't currently handle worksheet references with spaces or other non-alphameric characters, or trap erroneous references - @MarkBaker [CodePlex #10740](https://phpexcel.codeplex.com/workitem/10740) - DATE function problem with calculation engine (says too few arguments given) - @MarkBaker [CodePlex #10798](https://phpexcel.codeplex.com/workitem/10798) - Blank cell can cause wrong calculated value - @MarkBaker [CodePlex #10799](https://phpexcel.codeplex.com/workitem/10799) - Modified ROW() and COLUMN() Lookup/Reference Functions to return an array when passed a cell range, plus some additional work on INDEX() - @MarkBaker - Images not showing in Excel 97 using PHPExcel_Writer_Excel5 (patch by Jordi Gutiérrez Hermoso) - @Erik Tilt [CodePlex #10817](https://phpexcel.codeplex.com/workitem/10817) - When figures are contained in the excel sheet, Reader was stopped - @Erik Tilt [CodePlex #10785](https://phpexcel.codeplex.com/workitem/10785) - Formulas changed after insertNewRowBefore() - @MarkBaker [CodePlex #10818](https://phpexcel.codeplex.com/workitem/10818) - Cell range row offset problem with shared formulas using PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10825](https://phpexcel.codeplex.com/workitem/10825) - Warning: Call-time pass-by-reference has been deprecated - @MarkBaker [CodePlex #10832](https://phpexcel.codeplex.com/workitem/10832) - Image should "Move but don't size with cells" instead of "Move and size with cells" with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10849](https://phpexcel.codeplex.com/workitem/10849) - Opening a Excel5 generated XLS in Excel 2007 results in header/footer entry not showing on input - @Erik Tilt [CodePlex #10856](https://phpexcel.codeplex.com/workitem/10856) - addExternalSheet() not returning worksheet - @Erik Tilt [CodePlex #10859](https://phpexcel.codeplex.com/workitem/10859) - Invalid results in formulas with named ranges - @MarkBaker [CodePlex #10629](https://phpexcel.codeplex.com/workitem/10629) ## [1.7.0] - 2009-08-10 ### General - Expand documentation: Number formats - @Erik Tilt - Class 'PHPExcel_Cell_AdvancedValueBinder' not found - @Erik Tilt ### Features - Change return type of date functions to PHPExcel_Calculation_Functions::RETURNDATE_EXCEL - @MarkBaker - New RPN and stack-based calculation engine for improved performance of formula calculation - @MarkBaker - Faster (anything between 2 and 12 times faster than the old parser, depending on the complexity and nature of the formula) - Significantly more memory efficient when formulae reference cells across worksheets - Correct behaviour when referencing Named Ranges that exist on several worksheets - Support for Excel ^ (Exponential) and % (Percentage) operators - Support for matrices within basic arithmetic formulae (e.g. ={1,2,3;4,5,6;7,8,9}/2) - Better trapping/handling of NaN and infinity results (return #NUM! error) - Improved handling of empty parameters for Excel functions - Optional logging of calculation steps- New calculation engine can be accessed independently of workbooks (for use as a standalone calculator) - @MarkBaker - Implement more Excel calculation functions - @MarkBaker - Initial implementation of the COUNTIF() and SUMIF() Statistical functions - Added ACCRINT() Financial function- Modifications to number format handling for dddd and ddd masks in dates, use of thousand separators even when locale only implements it for money, and basic fraction masks (0 ?/? and ?/?) - @MarkBaker - Support arbitrary fixed number of decimals in PHPExcel_Style_NumberFormat::toFormattedString() - @Erik Tilt - Improving performance and memory on data dumps - @Erik Tilt - Various style optimizations (merging from branch wi6857-memory) - Moving hyperlink and dataValidation properties from cell to worksheet for lower PHP memory usage- Provide fluent interfaces where possible - @MarkBaker - Make easy way to apply a border to a rectangular selection - @Erik Tilt - Support for system window colors in PHPExcel_Reader_Excel5 - @Erik Tilt - Horizontal center across selection - @Erik Tilt - Merged cells record, write to full record size in PHPExcel_Writer_Excel5 - @Erik Tilt - Add page break between sheets in exported PDF - @MarkBaker - Sanitization of UTF-8 input for cell values - @Erik Tilt - Read cached calculated value with PHPExcel_Reader_Excel5 - @Erik Tilt - Miscellaneous CSS improvements for PHPExcel_Writer_HTML - @Erik Tilt - getProperties: setCompany feature request - @Erik Tilt - Insert worksheet at a specified index - @MarkBaker - Change worksheet index - @MarkBaker - Readfilter for CSV reader - @MarkBaker - Check value of mbstring.func_overload when saving with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10172](https://phpexcel.codeplex.com/workitem/10172) - Eliminate dependency of an include path pointing to class directory - @Erik Tilt [CodePlex #10251](https://phpexcel.codeplex.com/workitem/10251) - Method for getting the correct reader for a certain file (contribution) - @Erik Tilt [CodePlex #10292](https://phpexcel.codeplex.com/workitem/10292) - Choosing specific row in fromArray method - @Erik Tilt [CodePlex #10287](https://phpexcel.codeplex.com/workitem/10287) - Shared formula support in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10319](https://phpexcel.codeplex.com/workitem/10319) ### Bugfixes - Right-to-left column direction in worksheet - @MB,ET [CodePlex #10345](https://phpexcel.codeplex.com/workitem/10345) - PHPExcel_Reader_Excel5 not reading PHPExcel_Style_NumberFormat::FORMAT_NUMBER ('0') - @Erik Tilt - Fractional row height in locale other than English results in corrupt output using PHPExcel_Writer_Excel2007 - @Erik Tilt - Fractional (decimal) numbers not inserted correctly when locale is other than English - @Erik Tilt - Fractional calculated value in locale other than English results in corrupt output using PHPExcel_Writer_Excel2007 - @Erik Tilt - Locale aware decimal and thousands separator in exported formats HTML, CSV, PDF - @Erik Tilt - Cannot Add Image with Space on its Name - @MarkBaker - Black line at top of every page in output by PHPExcel_Writer_PDF - @Erik Tilt - Border styles and border colors not showing in HTML output (regression since 1.6.4) - @Erik Tilt - Hidden screen gridlines setting in worksheet not read by PHPExcel_Reader_Excel2007 - @Erik Tilt - Some valid sheet names causes corrupt output using PHPExcel_Writer_Excel2007 - @MarkBaker - More than 32,767 characters in a cell gives corrupt Excel file - @Erik Tilt - Images not getting copyied with the ->copy() function - @Erik Tilt - Bad calculation of column width setAutoSize(true) function - @Erik Tilt - Dates are sometimes offset by 1 day in output by HTML and PDF writers depending on system timezone setting - @Erik Tilt - Wingdings symbol fonts not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10003](https://phpexcel.codeplex.com/workitem/10003) - White space string prefix stripped by PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #10010](https://phpexcel.codeplex.com/workitem/10010) - The name of the Workbook stream MUST be "Workbook", not "Book" - @Erik Tilt [CodePlex #10023](https://phpexcel.codeplex.com/workitem/10023) - Avoid message "Microsoft Excel recalculates formulas..." when closing xls file from Excel - @Erik Tilt [CodePlex #10030](https://phpexcel.codeplex.com/workitem/10030) - Non-unique newline representation causes problems with LEN formula - @Erik Tilt [CodePlex #10031](https://phpexcel.codeplex.com/workitem/10031) - Newline in cell not showing with PHPExcel_Writer_HTML and PHPExcel_Writer_PDF - @Erik Tilt [CodePlex #10033](https://phpexcel.codeplex.com/workitem/10033) - Rich-Text strings get prefixed by   when output by HTML writer - @Erik Tilt [CodePlex #10046](https://phpexcel.codeplex.com/workitem/10046) - Leading spaces do not appear in output by HTML/PDF writers - @Erik Tilt [CodePlex #10052](https://phpexcel.codeplex.com/workitem/10052) - Empty Apache POI-generated file can not be read - @MarkBaker [CodePlex #10061](https://phpexcel.codeplex.com/workitem/10061) - Column width not scaling correctly with font size in HTML and PDF writers - @Erik Tilt [CodePlex #10068](https://phpexcel.codeplex.com/workitem/10068) - Inaccurate row heights with HTML writer - @Erik Tilt [CodePlex #10069](https://phpexcel.codeplex.com/workitem/10069) - Reference helper - @MarkBaker - Excel 5 Named ranges should not be local to the worksheet, but accessible from all worksheets - @MarkBaker - Row heights are ignored by PHPExcel_Writer_PDF - @Erik Tilt [CodePlex #10088](https://phpexcel.codeplex.com/workitem/10088) - Write raw XML - @MarkBaker - removeRow(), removeColumn() not always clearing cell values - @Erik Tilt [CodePlex #10098](https://phpexcel.codeplex.com/workitem/10098) - Problem reading certain hyperlink records with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10142](https://phpexcel.codeplex.com/workitem/10142) - Hyperlink cell range read failure with PHPExcel_Reader_Excel2007 - @Erik Tilt [CodePlex #10143](https://phpexcel.codeplex.com/workitem/10143) - 'Column string index can not be empty.' - @MarkBaker [CodePlex #10149](https://phpexcel.codeplex.com/workitem/10149) - getHighestColumn() sometimes says there are 256 columns with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10204](https://phpexcel.codeplex.com/workitem/10204) - extractSheetTitle fails when sheet title contains exclamation mark (!) - @Erik Tilt [CodePlex #10220](https://phpexcel.codeplex.com/workitem/10220) - setTitle() sometimes erroneously appends integer to sheet name - @Erik Tilt [CodePlex #10221](https://phpexcel.codeplex.com/workitem/10221) - Mac BIFF5 Excel file read failure (missing support for Mac OS Roman character set) - @Erik Tilt [CodePlex #10229](https://phpexcel.codeplex.com/workitem/10229) - BIFF5 header and footer incorrectly read by PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10230](https://phpexcel.codeplex.com/workitem/10230) - iconv notices when reading hyperlinks with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10259](https://phpexcel.codeplex.com/workitem/10259) - Excel5 reader OLE read failure with small Mac BIFF5 Excel files - @Erik Tilt [CodePlex #10252](https://phpexcel.codeplex.com/workitem/10252) - Problem in reading formula : IF( IF ) with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10272](https://phpexcel.codeplex.com/workitem/10272) - Error reading formulas referencing external sheets with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10274](https://phpexcel.codeplex.com/workitem/10274) - Image horizontally stretched when default font size is increased (PHPExcel_Writer_Excel5) - @Erik Tilt [CodePlex #10291](https://phpexcel.codeplex.com/workitem/10291) - Undefined offset in Reader\Excel5.php on line 3572 - @Erik Tilt [CodePlex #10333](https://phpexcel.codeplex.com/workitem/10333) - PDF output different then XLS (copied data) - @MarkBaker [CodePlex #10340](https://phpexcel.codeplex.com/workitem/10340) - Internal hyperlinks with UTF-8 sheet names not working in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #10352](https://phpexcel.codeplex.com/workitem/10352) - String shared formula result read error with PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #10361](https://phpexcel.codeplex.com/workitem/10361) - Uncaught exception 'Exception' with message 'Valid scale is between 10 and 400.' in Classes/PHPExcel/Worksheet/PageSetup.php:338 - @Erik Tilt [CodePlex #10363](https://phpexcel.codeplex.com/workitem/10363) - Using setLoadSheetsOnly fails if you do not use setReadDataOnly(true) and sheet is not the first sheet - @Erik Tilt [CodePlex #10355](https://phpexcel.codeplex.com/workitem/10355) - getCalculatedValue() sometimes incorrect with IF formula and 0-values - @MarkBaker [CodePlex #10362](https://phpexcel.codeplex.com/workitem/10362) - Excel Reader 2007 problem with "shared" formulae when "master" is an error - @MarkBaker - Named Range Bug, using the same range name on different worksheets - @MarkBaker - Java code in JAMA classes - @MarkBaker - getCalculatedValue() not working with some formulas involving error types - @MarkBaker - evaluation of both return values in an IF() statement returning an error if either result was an error, irrespective of the IF evaluation - @MarkBaker - Power in formulas: new calculation engine no longer treats ^ as a bitwise XOR operator - @MarkBaker - Bugfixes and improvements to many of the Excel functions in PHPExcel - @MarkBaker - Added optional "places" parameter in the BIN2HEX(), BIN2OCT, DEC2BIN(), DEC2OCT(), DEC2HEX(), HEX2BIN(), HEX2OCT(), OCT2BIN() and OCT2HEX() Engineering Functions - Trap for unbalanced matrix sizes in MDETERM() and MINVERSE() Mathematic and Trigonometric functions - Fix for default characters parameter value for LEFT() and RIGHT() Text functions - Fix for GCD() and LCB() Mathematical functions when the parameters include a zero (0) value - Fix for BIN2OCT() Engineering Function for 2s complement values (which were returning hex values) - Fix for BESSELK() and BESSELY() Engineering functions - Fix for IMDIV() Engineering Function when result imaginary component is positive (wasn't setting the sign) - Fix for ERF() Engineering Function when called with an upper limit value for the integration - Fix to DATE() Date/Time Function for year value of 0 - Set ISPMT() function as category FINANCIAL - Fix for DOLLARDE() and DOLLARFR() Financial functions - Fix to EFFECT() Financial function (treating $nominal_rate value as a variable name rather than a value) - Fix to CRITBINOM() Statistical function (CurrentValue and EssentiallyZero treated as constants rather than variables) - Note that an Error in the function logic can still lead to a permanent loop - Fix to MOD() Mathematical function to work with floating point results - Fix for QUOTIENT() Mathematical function - Fix to HOUR(), MINUTE() and SECOND() Date/Time functions to return an error when passing in a floating point value of 1.0 or greater, or less than 0 - LOG() Function now correctly returns base-10 log when called with only one parameter, rather than the natural log as the default base - Modified text functions to handle multibyte character set (UTF-8). ## [1.6.7] - 2009-04-22 ### BREAKING CHANGE In previous versions of PHPExcel up to and including 1.6.6, when a cell had a date-like number format code, it was possible to enter a date directly using an integer PHP-time without converting to Excel date format. Starting with PHPExcel 1.6.7 this is no longer supported. Refer to the developer documentation for more information on entering dates into a cell. ### General - Deprecate misspelled setStriketrough() and getStriketrough() methods - @MarkBaker [CodePlex #9416](https://phpexcel.codeplex.com/workitem/9416) ### Features - Performance improvement when saving file - @MarkBaker [CodePlex #9526](https://phpexcel.codeplex.com/workitem/9526) - Check that sheet title has maximum 31 characters - @MarkBaker [CodePlex #9598](https://phpexcel.codeplex.com/workitem/9598) - True support for Excel built-in number format codes - @MB, ET [CodePlex #9631](https://phpexcel.codeplex.com/workitem/9631) - Ability to read defect BIFF5 Excel file without CODEPAGE record - @Erik Tilt [CodePlex #9683](https://phpexcel.codeplex.com/workitem/9683) - Auto-detect which reader to invoke - @MarkBaker [CodePlex #9701](https://phpexcel.codeplex.com/workitem/9701) - Deprecate insertion of dates using PHP-time (Unix time) [request for removal of feature] - @Erik Tilt [CodePlex #9214](https://phpexcel.codeplex.com/workitem/9214) - Support for entering time values like '9:45', '09:45' using AdvancedValueBinder - @Erik Tilt [CodePlex #9747](https://phpexcel.codeplex.com/workitem/9747) ### Bugfixes - DataType dependent horizontal alignment in HTML and PDF writer - @Erik Tilt [CodePlex #9797](https://phpexcel.codeplex.com/workitem/9797) - Cloning data validation object causes script to stop - @MarkBaker [CodePlex #9375](https://phpexcel.codeplex.com/workitem/9375) - Simultaneous repeating rows and repeating columns not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #9400](https://phpexcel.codeplex.com/workitem/9400) - Simultaneous repeating rows and repeating columns not working with PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #9399](https://phpexcel.codeplex.com/workitem/9399) - Row outline level not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #9437](https://phpexcel.codeplex.com/workitem/9437) - Occasional notices with PHPExcel_Reader_Excel5 when Excel file contains drawing elements - @Erik Tilt [CodePlex #9452](https://phpexcel.codeplex.com/workitem/9452) - PHPExcel_Reader_Excel5 fails as a whole when workbook contains images other than JPEG/PNG - @Erik Tilt [CodePlex #9453](https://phpexcel.codeplex.com/workitem/9453) - Excel5 writer checks for iconv but does not necessarily use it - @Erik Tilt [CodePlex #9444](https://phpexcel.codeplex.com/workitem/9444) - Altering a style on copied worksheet alters also the original - @Erik Tilt [CodePlex #9463](https://phpexcel.codeplex.com/workitem/9463) - Formulas are incorrectly updated when a sheet is renamed - @MarkBaker [CodePlex #9480](https://phpexcel.codeplex.com/workitem/9480) - PHPExcel_Worksheet::extractSheetTitle not treating single quotes correctly - @MarkBaker [CodePlex #9513](https://phpexcel.codeplex.com/workitem/9513) - PHP Warning raised in function array_key_exists - @MarkBaker [CodePlex #9477](https://phpexcel.codeplex.com/workitem/9477) - getAlignWithMargins() gives wrong value when using PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #9599](https://phpexcel.codeplex.com/workitem/9599) - getScaleWithDocument() gives wrong value when using PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #9600](https://phpexcel.codeplex.com/workitem/9600) - PHPExcel_Reader_Excel2007 not reading the first user-defined number format - @MarkBaker [CodePlex #9630](https://phpexcel.codeplex.com/workitem/9630) - Print area converted to uppercase after read with PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #9647](https://phpexcel.codeplex.com/workitem/9647) - Incorrect reading of scope for named range using PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #9661](https://phpexcel.codeplex.com/workitem/9661) - Error with pattern (getFillType) and rbg (getRGB) - @MarkBaker [CodePlex #9690](https://phpexcel.codeplex.com/workitem/9690) - AdvancedValueBinder affected by system timezone setting when inserting date values - @Erik Tilt [CodePlex #9712](https://phpexcel.codeplex.com/workitem/9712) - PHPExcel_Reader_Excel2007 not reading value of active sheet index - @Erik Tilt [CodePlex #9743](https://phpexcel.codeplex.com/workitem/9743) - getARGB() sometimes returns SimpleXMLElement object instead of string with PHPExcel_Reader_Excel2007 - @Erik Tilt [CodePlex #9742](https://phpexcel.codeplex.com/workitem/9742) - Negative image offset causes defects in 14excel5.xls and 20readexcel5.xlsx - @Erik Tilt [CodePlex #9731](https://phpexcel.codeplex.com/workitem/9731) - HTML & PDF Writer not working with mergeCells (regression since 1.6.5) - @Erik Tilt [CodePlex #9758](https://phpexcel.codeplex.com/workitem/9758) - Too wide columns with HTML and PDF writer - @Erik Tilt [CodePlex #9774](https://phpexcel.codeplex.com/workitem/9774) - PDF and cyrillic fonts - @MarkBaker [CodePlex #9775](https://phpexcel.codeplex.com/workitem/9775) - Percentages not working correctly with HTML and PDF writers (shows 0.25% instead of 25%) - @Erik Tilt [CodePlex #9793](https://phpexcel.codeplex.com/workitem/9793) - PHPExcel_Writer_HTML creates extra borders around cell contents using setUseInlineCss(true) - @Erik Tilt [CodePlex #9791](https://phpexcel.codeplex.com/workitem/9791) - Problem with text wrap + merged cells in HTML and PDF writer - @Erik Tilt [CodePlex #9784](https://phpexcel.codeplex.com/workitem/9784) - Adjacent path separators in include_path causing IOFactory to violate open_basedir restriction - @Erik Tilt [CodePlex #9814](https://phpexcel.codeplex.com/workitem/9814) ## [1.6.6] - 2009-03-02 ### General - Improve support for built-in number formats in PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #9102](https://phpexcel.codeplex.com/workitem/9102) - Source files are in both UNIX and DOS formats - changed to UNIX - @Erik Tilt [CodePlex #9281](https://phpexcel.codeplex.com/workitem/9281) ### Features - Update documentation: Which language to write formulas in? - @MarkBaker [CodePlex #9338](https://phpexcel.codeplex.com/workitem/9338) - Ignore DEFCOLWIDTH records with value 8 in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #8817](https://phpexcel.codeplex.com/workitem/8817) - Support for width, height, offsetX, offsetY for images in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #8847](https://phpexcel.codeplex.com/workitem/8847) - Disk Caching in specific folder - @MarkBaker [CodePlex #8870](https://phpexcel.codeplex.com/workitem/8870) - Added SUMX2MY2, SUMX2PY2, SUMXMY2, MDETERM and MINVERSE Mathematical and Trigonometric Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added CONVERT Engineering Function - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added DB, DDB, DISC, DOLLARDE, DOLLARFR, INTRATE, IPMT, PPMT, PRICEDISC, PRICEMAT and RECEIVED Financial Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added ACCRINTM, CUMIPMT, CUMPRINC, TBILLEQ, TBILLPRICE, TBILLYIELD, YIELDDISC and YIELDMAT Financial Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added DOLLAR Text Function - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added CORREL, COVAR, FORECAST, INTERCEPT, RSQ, SLOPE and STEYX Statistical Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added PEARSON Statistical Functions as a synonym for CORREL - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added LINEST, LOGEST (currently only valid for stats = false), TREND and GROWTH Statistical Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added RANK and PERCENTRANK Statistical Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Added ROMAN Mathematical Function (Classic form only) - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Update documentation to show example of getCellByColumnAndRow($col, $row) - @MarkBaker [CodePlex #8931](https://phpexcel.codeplex.com/workitem/8931) - Implement worksheet, row and cell iterators - @MarkBaker [CodePlex #8770](https://phpexcel.codeplex.com/workitem/8770) - Support for arbitrary defined names (named range) - @MarkBaker [CodePlex #9001](https://phpexcel.codeplex.com/workitem/9001) - Update formulas when sheet title / named range title changes - @MB, ET [CodePlex #9016](https://phpexcel.codeplex.com/workitem/9016) - Ability to read cached calculated value - @MarkBaker [CodePlex #9103](https://phpexcel.codeplex.com/workitem/9103) - Support for Excel 1904 calendar date mode (Mac) - @MBaker, ET [CodePlex #8483](https://phpexcel.codeplex.com/workitem/8483) - PHPExcel_Writer_Excel5 improvements writing shared strings table - @Erik Tilt [CodePlex #9194](https://phpexcel.codeplex.com/workitem/9194) - PHPExcel_Writer_Excel5 iconv fallback when mbstring extension is not enabled - @Erik Tilt [CodePlex #9248](https://phpexcel.codeplex.com/workitem/9248) - UTF-8 support in font names in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #9253](https://phpexcel.codeplex.com/workitem/9253) - Implement value binding architecture - @MarkBaker [CodePlex #9215](https://phpexcel.codeplex.com/workitem/9215) - PDF writer not working with UTF-8 - @MarkBaker [CodePlex #6742](https://phpexcel.codeplex.com/workitem/6742) ### Bugfixes - Eliminate duplicate style entries in multisheet workbook written by PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #9355](https://phpexcel.codeplex.com/workitem/9355) - Redirect to client browser fails due to trailing white space in class definitions - @Erik Tilt [CodePlex #8810](https://phpexcel.codeplex.com/workitem/8810) - Spurious column dimension element introduced in blank worksheet after using PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #8816](https://phpexcel.codeplex.com/workitem/8816) - Image gets slightly narrower than expected when using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8830](https://phpexcel.codeplex.com/workitem/8830) - Image laid over non-visible row gets squeezed in height when using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8831](https://phpexcel.codeplex.com/workitem/8831) - PHPExcel_Reader_Excel5 fails when there are 10 or more images in the workbook - @Erik Tilt [CodePlex #8860](https://phpexcel.codeplex.com/workitem/8860) - Different header/footer images in different sheets not working with PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #8909](https://phpexcel.codeplex.com/workitem/8909) - Fractional seconds disappear when using PHPExcel_Reader_Excel2007 and PHPExcel_Reader_Excel5 - @MB, ET [CodePlex #8924](https://phpexcel.codeplex.com/workitem/8924) - Images not showing in OpenOffice when using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7994](https://phpexcel.codeplex.com/workitem/7994) - Images not showing on print using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #9047](https://phpexcel.codeplex.com/workitem/9047) - PHPExcel_Writer_Excel5 maximum allowed record size 4 bytes too short - @Erik Tilt [CodePlex #9085](https://phpexcel.codeplex.com/workitem/9085) - Not numeric strings are formatted as dates and numbers using worksheet's toArray method - @MarkBaker [CodePlex #9119](https://phpexcel.codeplex.com/workitem/9119) - Excel5 simple formula parsing error - @Erik Tilt [CodePlex #9132](https://phpexcel.codeplex.com/workitem/9132) - Problems writing dates with CSV - @Erik Tilt [CodePlex #9206](https://phpexcel.codeplex.com/workitem/9206) - PHPExcel_Reader_Excel5 reader fails with fatal error when reading group shapes - @Erik Tilt [CodePlex #9203](https://phpexcel.codeplex.com/workitem/9203) - PHPExcel_Writer_Excel5 fails completely when workbook contains more than 57 colors - @Erik Tilt [CodePlex #9231](https://phpexcel.codeplex.com/workitem/9231) - PHPExcel_Writer_PDF not compatible with autoload - @Erik Tilt [CodePlex #9244](https://phpexcel.codeplex.com/workitem/9244) - Fatal error: Call to a member function getNestingLevel() on a non-object in PHPExcel/Reader/Excel5.php on line 690 - @Erik Tilt [CodePlex #9250](https://phpexcel.codeplex.com/workitem/9250) - Notices when running test 04printing.php on PHP 5.2.8 - @MarkBaker [CodePlex #9246](https://phpexcel.codeplex.com/workitem/9246) - insertColumn() spawns creation of spurious RowDimension - @MarkBaker [CodePlex #9294](https://phpexcel.codeplex.com/workitem/9294) - Fix declarations for methods in extended Trend classes - @MarkBaker [CodePlex #9296](https://phpexcel.codeplex.com/workitem/9296) - Fix to parameters for the FORECAST Statistical Function - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - PDF writer problems with cell height and text wrapping - @MarkBaker [CodePlex #7083](https://phpexcel.codeplex.com/workitem/7083) - Fix test for calculated value in case the returned result is an array - @MarkBaker - Column greater than 256 results in corrupt Excel file using PHPExcel_Writer_Excel5 - @Erik Tilt - Excel Numberformat 0.00 results in non internal decimal places values in toArray() Method - @MarkBaker [CodePlex #9351](https://phpexcel.codeplex.com/workitem/9351) - setAutoSize not taking into account text rotation - @MB,ET [CodePlex #9356](https://phpexcel.codeplex.com/workitem/9356) - Call to undefined method PHPExcel_Worksheet_MemoryDrawing::getPath() in PHPExcel/Writer/HTML.php - @Erik Tilt [CodePlex #9372](https://phpexcel.codeplex.com/workitem/9372) ## [1.6.5] - 2009-01-05 ### General - Applied patch 2063 - @MarkBaker - Optimise Shared Strings - @MarkBaker - Optimise Cell Sorting - @MarkBaker - Optimise Style Hashing - @MarkBaker - UTF-8 enhancements - @Erik Tilt - PHPExcel_Writer_HTML validation errors against strict HTML 4.01 / CSS 2.1 - @Erik Tilt - Documented work items 6203 and 8110 in manual - @MarkBaker - Restructure package hierachy so classes can be found more easily in auto-generated API (from work item 8468) - @Erik Tilt ### Features - Redirect output to a client's browser: Update recommendation in documentation - @MarkBaker [CodePlex #8806](https://phpexcel.codeplex.com/workitem/8806) - PHPExcel_Reader_Excel5 support for print gridlines - @Erik Tilt [CodePlex #7897](https://phpexcel.codeplex.com/workitem/7897) - Screen gridlines support in Excel5 reader/writer - @Erik Tilt [CodePlex #7899](https://phpexcel.codeplex.com/workitem/7899) - Option for adding image to spreadsheet from image resource in memory - @MB, ET [CodePlex #7552](https://phpexcel.codeplex.com/workitem/7552) - PHPExcel_Reader_Excel5 style support for BIFF5 files (Excel 5.0 - Excel 95) - @Erik Tilt [CodePlex #7862](https://phpexcel.codeplex.com/workitem/7862) - PHPExcel_Reader_Excel5 support for user-defined colors and special built-in colors - @Erik Tilt [CodePlex #7918](https://phpexcel.codeplex.com/workitem/7918) - Support for freeze panes in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7992](https://phpexcel.codeplex.com/workitem/7992) - Support for header and footer margins in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7996](https://phpexcel.codeplex.com/workitem/7996) - Support for active sheet index in Excel5 reader/writer - @Erik Tilt [CodePlex #7997](https://phpexcel.codeplex.com/workitem/7997) - Freeze panes not read by PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #7991](https://phpexcel.codeplex.com/workitem/7991) - Support for screen zoom level (feature request) - @MB, ET [CodePlex #7993](https://phpexcel.codeplex.com/workitem/7993) - Support for default style in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #8012](https://phpexcel.codeplex.com/workitem/8012) - Apple iWork / Numbers.app incompatibility - @MarkBaker [CodePlex #8094](https://phpexcel.codeplex.com/workitem/8094) - Support "between rule" in conditional formatting - @MarkBaker [CodePlex #7931](https://phpexcel.codeplex.com/workitem/7931) - Comment size, width and height control (feature request) - @MarkBaker [CodePlex #8308](https://phpexcel.codeplex.com/workitem/8308) - Improve method for storing MERGEDCELLS records in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8418](https://phpexcel.codeplex.com/workitem/8418) - Support for protectCells() in Excel5 reader/writer - @Erik Tilt [CodePlex #8435](https://phpexcel.codeplex.com/workitem/8435) - Support for fitToWidth and fitToHeight pagesetup properties in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #8472](https://phpexcel.codeplex.com/workitem/8472) - Support for setShowSummaryBelow() and setShowSummaryRight() in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8489](https://phpexcel.codeplex.com/workitem/8489) - Support for Excel 1904 calendar date mode (Mac) - @MarkBaker [CodePlex #8483](https://phpexcel.codeplex.com/workitem/8483) - Excel5 reader: Support for reading images (bitmaps) - @Erik Tilt [CodePlex #7538](https://phpexcel.codeplex.com/workitem/7538) - Support for default style in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8787](https://phpexcel.codeplex.com/workitem/8787) - Modified calculate() method to return either an array or the first value from the array for those functions that return arrays rather than single values (e.g the MMULT and TRANSPOSE function). This performance can be modified based on the $returnArrayAsType which can be set/retrieved by calling the setArrayReturnType() and getArrayReturnType() methods of the PHPExcel_Calculation class. - @MarkBaker ### Bugfixes - Added ERROR.TYPE Information Function, MMULT Mathematical and Trigonometry Function, and TRANSPOSE Lookup and Reference Function - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - setPrintGridlines(true) not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7896](https://phpexcel.codeplex.com/workitem/7896) - Incorrect mapping of fill patterns in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7907](https://phpexcel.codeplex.com/workitem/7907) - setShowGridlines(false) not working with PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #7898](https://phpexcel.codeplex.com/workitem/7898) - getShowGridlines() gives inverted value when reading sheet with PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #7905](https://phpexcel.codeplex.com/workitem/7905) - User-defined column width becomes slightly larger after read/write with Excel5 - @Erik Tilt [CodePlex #7944](https://phpexcel.codeplex.com/workitem/7944) - Incomplete border style support in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7949](https://phpexcel.codeplex.com/workitem/7949) - Conditional formatting "containsText" read/write results in MS Office Excel 2007 crash - @MarkBaker [CodePlex #7928](https://phpexcel.codeplex.com/workitem/7928) - All sheets are always selected in output when using PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #7995](https://phpexcel.codeplex.com/workitem/7995) - COLUMN function warning message during plain read/write - @MarkBaker [CodePlex #8013](https://phpexcel.codeplex.com/workitem/8013) - setValue(0) results in string data type '0' - @MarkBaker [CodePlex #8155](https://phpexcel.codeplex.com/workitem/8155) - Styles not removed when removing rows from sheet - @MarkBaker [CodePlex #8226](https://phpexcel.codeplex.com/workitem/8226) - =IF formula causes fatal error during $objWriter->save() in Excel2007 format - @MarkBaker [CodePlex #8301](https://phpexcel.codeplex.com/workitem/8301) - Exception thrown reading valid xls file: "Excel file is corrupt. Didn't find CONTINUE record while reading shared strings" - @Erik Tilt [CodePlex #8333](https://phpexcel.codeplex.com/workitem/8333) - MS Outlook corrupts files generated by PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8320](https://phpexcel.codeplex.com/workitem/8320) - Undefined method PHPExcel_Worksheet::setFreezePane() in ReferenceHelper.php on line 271 - @MarkBaker [CodePlex #8351](https://phpexcel.codeplex.com/workitem/8351) - Ampersands (&), left and right angles (<, >) in Rich-Text strings leads to corrupt output using PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #8401](https://phpexcel.codeplex.com/workitem/8401) - Print header and footer not supporting UTF-8 in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8408](https://phpexcel.codeplex.com/workitem/8408) - Vertical page breaks not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8463](https://phpexcel.codeplex.com/workitem/8463) - Missing support for accounting underline types in PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8476](https://phpexcel.codeplex.com/workitem/8476) - Infinite loops when reading corrupt xls file using PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #8482](https://phpexcel.codeplex.com/workitem/8482) - Sheet protection password not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8566](https://phpexcel.codeplex.com/workitem/8566) - PHPExcel_Style_NumberFormat::FORMAT_NUMBER ignored by PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8596](https://phpexcel.codeplex.com/workitem/8596) - PHPExcel_Reader_Excel5 fails a whole when workbook contains a chart - @Erik Tilt [CodePlex #8781](https://phpexcel.codeplex.com/workitem/8781) - Occasional loss of column widths using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #8788](https://phpexcel.codeplex.com/workitem/8788) - Notices while reading formulas with deleted sheet references using PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #8795](https://phpexcel.codeplex.com/workitem/8795) - Default style not read by PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #8807](https://phpexcel.codeplex.com/workitem/8807) - Blank rows occupy too much space in file generated by PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #9341](https://phpexcel.codeplex.com/workitem/9341) ## [1.6.4] - 2008-10-27 ### Features - RK record number error in MS developer documentation: 0x007E should be 0x027E - @Erik Tilt [CodePlex #7882](https://phpexcel.codeplex.com/workitem/7882) - getHighestColumn() returning "@" for blank worksheet causes corrupt output - @MarkBaker [CodePlex #7878](https://phpexcel.codeplex.com/workitem/7878) - Implement ROW and COLUMN Lookup/Reference Functions (when specified with a parameter) - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Implement initial work on OFFSET Lookup/Reference Function (returning address rather than value at address) - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Excel5 reader: Page margins - @Erik Tilt [CodePlex #7416](https://phpexcel.codeplex.com/workitem/7416) - Excel5 reader: Header & Footer - @Erik Tilt [CodePlex #7417](https://phpexcel.codeplex.com/workitem/7417) - Excel5 reader support for page setup (paper size etc.) - @Erik Tilt [CodePlex #7449](https://phpexcel.codeplex.com/workitem/7449) - Improve speed and memory consumption of PHPExcel_Writer_CSV - @MarkBaker [CodePlex #7445](https://phpexcel.codeplex.com/workitem/7445) - Better recognition of number format in HTML, CSV, and PDF writer - @MarkBaker [CodePlex #7432](https://phpexcel.codeplex.com/workitem/7432) - Font support: Superscript and Subscript - @MarkBaker [CodePlex #7485](https://phpexcel.codeplex.com/workitem/7485) - Excel5 reader font support: Super- and subscript - @Erik Tilt [CodePlex #7509](https://phpexcel.codeplex.com/workitem/7509) - Excel5 reader style support: Text rotation and stacked text - @Erik Tilt [CodePlex #7521](https://phpexcel.codeplex.com/workitem/7521) - Excel5 reader: Support for hyperlinks - @Erik Tilt [CodePlex #7530](https://phpexcel.codeplex.com/workitem/7530) - Import sheet by request - @MB, ET [CodePlex #7557](https://phpexcel.codeplex.com/workitem/7557) - PHPExcel_Reader_Excel5 support for page breaks - @Erik Tilt [CodePlex #7607](https://phpexcel.codeplex.com/workitem/7607) - PHPExcel_Reader_Excel5 support for shrink-to-fit - @Erik Tilt [CodePlex #7622](https://phpexcel.codeplex.com/workitem/7622) - Support for error types - @MB, ET [CodePlex #7675](https://phpexcel.codeplex.com/workitem/7675) - Excel5 reader true formula support - @Erik Tilt [CodePlex #7388](https://phpexcel.codeplex.com/workitem/7388) - Support for named ranges (defined names) in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7701](https://phpexcel.codeplex.com/workitem/7701) - Support for repeating rows and repeating columns (print titles) in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7781](https://phpexcel.codeplex.com/workitem/7781) - Support for print area in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7783](https://phpexcel.codeplex.com/workitem/7783) - Excel5 reader and writer support for horizontal and vertical centering of page - @Erik Tilt [CodePlex #7795](https://phpexcel.codeplex.com/workitem/7795) - Applied patch 1962 - @MarkBaker - Excel5 reader and writer support for hidden cells (formulas) - @Erik Tilt [CodePlex #7866](https://phpexcel.codeplex.com/workitem/7866) - Support for indentation in cells (feature request) - @MB, ET [CodePlex #7612](https://phpexcel.codeplex.com/workitem/7612) ### Bugfixes - Option for reading only specified interval of rows in a sheet - @MB, ET [CodePlex #7828](https://phpexcel.codeplex.com/workitem/7828) - PHPExcel_Calculation_Functions::DATETIMENOW() and PHPExcel_Calculation_Functions::DATENOW() to force UTC - @MarkBaker [CodePlex #7367](https://phpexcel.codeplex.com/workitem/7367) - Modified PHPExcel_Shared_Date::FormattedPHPToExcel() and PHPExcel_Shared_Date::ExcelToPHP to force datatype for return values - @MarkBaker [CodePlex #7395](https://phpexcel.codeplex.com/workitem/7395) - Excel5 reader not producing UTF-8 strings with BIFF5 files - @Erik Tilt [CodePlex #7450](https://phpexcel.codeplex.com/workitem/7450) - Array constant in formula gives run-time notice with Excel2007 writer - @MarkBaker [CodePlex #7470](https://phpexcel.codeplex.com/workitem/7470) - PHPExcel_Reader_Excel2007 setReadDataOnly(true) returns Rich-Text - @MarkBaker [CodePlex #7494](https://phpexcel.codeplex.com/workitem/7494) - PHPExcel_Reader_Excel5 setReadDataOnly(true) returns Rich-Text - @Erik Tilt [CodePlex #7496](https://phpexcel.codeplex.com/workitem/7496) - Characters before superscript or subscript losing style - @MarkBaker [CodePlex #7497](https://phpexcel.codeplex.com/workitem/7497) - Subscript not working with HTML writer - @MarkBaker [CodePlex #7507](https://phpexcel.codeplex.com/workitem/7507) - DefaultColumnDimension not working on first column (A) - @MarkBaker [CodePlex #7508](https://phpexcel.codeplex.com/workitem/7508) - Negative numbers are stored as text in PHPExcel_Writer_2007 - @MarkBaker [CodePlex #7527](https://phpexcel.codeplex.com/workitem/7527) - Text rotation and stacked text not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7531](https://phpexcel.codeplex.com/workitem/7531) - PHPExcel_Shared_Date::isDateTimeFormatCode erroneously says true - @MarkBaker [CodePlex #7536](https://phpexcel.codeplex.com/workitem/7536) - Different images with same filename in separate directories become duplicates - @MarkBaker [CodePlex #7559](https://phpexcel.codeplex.com/workitem/7559) - PHPExcel_Reader_Excel5 not returning sheet names as UTF-8 using for Excel 95 files - @Erik Tilt [CodePlex #7568](https://phpexcel.codeplex.com/workitem/7568) - setAutoSize(true) on empty column gives column width of 10 using PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #7575](https://phpexcel.codeplex.com/workitem/7575) - setAutoSize(true) on empty column gives column width of 255 using PHPExcel_Writer_Excel5 - @MB, ET [CodePlex #7573](https://phpexcel.codeplex.com/workitem/7573) - Worksheet_Drawing bug - @MarkBaker [CodePlex #7514](https://phpexcel.codeplex.com/workitem/7514) - getCalculatedValue() with REPT function causes script to stop - @MarkBaker [CodePlex #7593](https://phpexcel.codeplex.com/workitem/7593) - getCalculatedValue() with LEN function causes script to stop - @MarkBaker [CodePlex #7594](https://phpexcel.codeplex.com/workitem/7594) - Explicit fit-to-width (page setup) results in fit-to-height becoming 1 - @MarkBaker [CodePlex #7600](https://phpexcel.codeplex.com/workitem/7600) - Fit-to-width value of 1 is lost after read/write of Excel2007 spreadsheet - @MarkBaker [CodePlex #7610](https://phpexcel.codeplex.com/workitem/7610) - Conditional styles not read properly using PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #7516](https://phpexcel.codeplex.com/workitem/7516) - PHPExcel_Writer_2007: Default worksheet style works only for first sheet - @MarkBaker [CodePlex #7611](https://phpexcel.codeplex.com/workitem/7611) - Cannot Lock Cells using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #6940](https://phpexcel.codeplex.com/workitem/6940) - Incorrect cell protection values found when using Excel5 reader - @Erik Tilt [CodePlex #7621](https://phpexcel.codeplex.com/workitem/7621) - Default row height not working above highest row using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7623](https://phpexcel.codeplex.com/workitem/7623) - Default column width does not get applied when using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7637](https://phpexcel.codeplex.com/workitem/7637) - Broken support for UTF-8 string formula results in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7642](https://phpexcel.codeplex.com/workitem/7642) - UTF-8 sheet names not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7643](https://phpexcel.codeplex.com/workitem/7643) - getCalculatedValue() with ISNONTEXT function causes script to stop - @MarkBaker [CodePlex #7631](https://phpexcel.codeplex.com/workitem/7631) - Missing BIFF3 functions in PHPExcel_Writer_Excel5: USDOLLAR (YEN), FINDB, SEARCHB, REPLACEB, LEFTB, RIGHTB, MIDB, LENB, ASC, DBCS (JIS) - @Erik Tilt [CodePlex #7652](https://phpexcel.codeplex.com/workitem/7652) - Excel5 reader doesn't read numbers correctly in 64-bit systems - @Erik Tilt [CodePlex #7663](https://phpexcel.codeplex.com/workitem/7663) - Missing BIFF5 functions in PHPExcel_Writer_Excel5: ISPMT, DATEDIF, DATESTRING, NUMBERSTRING - @Erik Tilt [CodePlex #7667](https://phpexcel.codeplex.com/workitem/7667) - Missing BIFF8 functions in PHPExcel_Writer_Excel5: GETPIVOTDATA, HYPERLINK, PHONETIC, AVERAGEA, MAXA, MINA, STDEVPA, VARPA, STDEVA, VARA - @Erik Tilt [CodePlex #7668](https://phpexcel.codeplex.com/workitem/7668) - Wrong host value in PHPExcel_Shared_ZipStreamWrapper::stream_open() - @MarkBaker [CodePlex #7657](https://phpexcel.codeplex.com/workitem/7657) - PHPExcel_Reader_Excel5 not reading explicitly entered error types in cells - @Erik Tilt [CodePlex #7676](https://phpexcel.codeplex.com/workitem/7676) - Boolean and error data types not preserved for formula results in PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7678](https://phpexcel.codeplex.com/workitem/7678) - PHPExcel_Reader_Excel2007 ignores cell data type - @MarkBaker [CodePlex #7695](https://phpexcel.codeplex.com/workitem/7695) - PHPExcel_Reader_Excel5 ignores cell data type - @Erik Tilt [CodePlex #7712](https://phpexcel.codeplex.com/workitem/7712) - PHPExcel_Writer_Excel5 not aware of data type - @Erik Tilt [CodePlex #7587](https://phpexcel.codeplex.com/workitem/7587) - Long strings sometimes truncated when using PHPExcel_Reader_Excel5 - @Erik Tilt [CodePlex #7713](https://phpexcel.codeplex.com/workitem/7713) - Direct entry of boolean or error type in cell not supported by PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7727](https://phpexcel.codeplex.com/workitem/7727) - PHPExcel_Reader_Excel2007: Error reading cell with data type string, date number format, and numeric-like cell value - @MarkBaker [CodePlex #7714](https://phpexcel.codeplex.com/workitem/7714) - Row and column outlines (group indent level) not showing after using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7735](https://phpexcel.codeplex.com/workitem/7735) - Missing UTF-8 support in number format codes for PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7737](https://phpexcel.codeplex.com/workitem/7737) - Missing UTF-8 support with PHPExcel_Writer_Excel5 for explicit string in formula - @Erik Tilt [CodePlex #7750](https://phpexcel.codeplex.com/workitem/7750) - Problem with class constants in PHPExcel_Style_NumberFormat - @MarkBaker [CodePlex #7726](https://phpexcel.codeplex.com/workitem/7726) - Sometimes errors with PHPExcel_Reader_Excel5 reading hyperlinks - @Erik Tilt [CodePlex #7758](https://phpexcel.codeplex.com/workitem/7758) - Hyperlink in cell always results in string data type when using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7759](https://phpexcel.codeplex.com/workitem/7759) - Excel file with blank sheet seen as broken in MS Office Excel 2007 when created by PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7771](https://phpexcel.codeplex.com/workitem/7771) - PHPExcel_Reader_Excel5: Incorrect reading of formula with explicit string containing (escaped) double-quote - @Erik Tilt [CodePlex #7785](https://phpexcel.codeplex.com/workitem/7785) - getCalculatedValue() fails on formula with sheet name containing (escaped) single-quote - @MarkBaker [CodePlex #7787](https://phpexcel.codeplex.com/workitem/7787) - getCalculatedValue() fails on formula with explicit string containing (escaped) double-quote - @MarkBaker [CodePlex #7786](https://phpexcel.codeplex.com/workitem/7786) - Problems with simultaneous repeatRowsAtTop and repeatColumnsAtLeft using Excel2007 reader and writer - @MarkBaker [CodePlex #7780](https://phpexcel.codeplex.com/workitem/7780) - PHPExcel_Reader_Excel5: Error reading formulas with sheet reference containing special characters - @Erik Tilt [CodePlex #7802](https://phpexcel.codeplex.com/workitem/7802) - Off-sheet references sheet!A1 not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7831](https://phpexcel.codeplex.com/workitem/7831) - Repeating rows/columns (print titles), print area not working with PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7834](https://phpexcel.codeplex.com/workitem/7834) - Formula having datetime number format shows as text when using PHPExcel_Writer_Excel5 - @Erik Tilt [CodePlex #7849](https://phpexcel.codeplex.com/workitem/7849) - Cannot set formula to hidden using applyFromArray() - @MarkBaker [CodePlex #7863](https://phpexcel.codeplex.com/workitem/7863) - HTML/PDF Writers limited to 26 columns by calculateWorksheetDimension (erroneous comparison in getHighestColumn() method) - @MarkBaker [CodePlex #7805](https://phpexcel.codeplex.com/workitem/7805) - Formula returning error type is lost when read by PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #7873](https://phpexcel.codeplex.com/workitem/7873) - PHPExcel_Reader_Excel5: Cell style lost for last column in group of blank cells - @Erik Tilt [CodePlex #7883](https://phpexcel.codeplex.com/workitem/7883) - Column width sometimes collapses to auto size using Excel2007 reader/writer - @MarkBaker [CodePlex #7886](https://phpexcel.codeplex.com/workitem/7886) - Data Validation Formula = 0 crashes Excel - @MarkBaker [CodePlex #9343](https://phpexcel.codeplex.com/workitem/9343) ## [1.6.3] - 2008-08-25 ### General - Modified PHPExcel_Shared_Date::PHPToExcel() to force UTC - @MarkBaker [CodePlex #7367](https://phpexcel.codeplex.com/workitem/7367) - Applied patch 1629 - @MarkBaker - Applied patch 1644 - @MarkBaker - Implement repeatRow and repeatColumn in Excel5 writer - @MarkBaker [CodePlex #6485](https://phpexcel.codeplex.com/workitem/6485) ### Features - Remove scene3d filter in Excel2007 drawing - @MarkBaker [CodePlex #6838](https://phpexcel.codeplex.com/workitem/6838) - Implement CHOOSE and INDEX Lookup/Reference Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Implement CLEAN Text Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Implement YEARFRAC Date/Time Functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Implement 2 options for print/show gridlines - @MarkBaker [CodePlex #6508](https://phpexcel.codeplex.com/workitem/6508) - Add VLOOKUP function (contribution) - @MarkBaker [CodePlex #7270](https://phpexcel.codeplex.com/workitem/7270) - Implemented: ShrinkToFit - @MarkBaker [CodePlex #7182](https://phpexcel.codeplex.com/workitem/7182) - Row heights not updated correctly when inserting new rows - @MarkBaker [CodePlex #7218](https://phpexcel.codeplex.com/workitem/7218) - Copy worksheets within the same workbook - @MarkBaker [CodePlex #7157](https://phpexcel.codeplex.com/workitem/7157) - Excel5 reader style support: horizontal and vertical alignment plus text wrap - @Erik Tilt [CodePlex #7290](https://phpexcel.codeplex.com/workitem/7290) - Excel5 reader support for merged cells - @Erik Tilt [CodePlex #7294](https://phpexcel.codeplex.com/workitem/7294) - Excel5 reader: Sheet Protection - @Erik Tilt [CodePlex #7296](https://phpexcel.codeplex.com/workitem/7296) - Excel5 reader: Password for sheet protection - @Erik Tilt [CodePlex #7297](https://phpexcel.codeplex.com/workitem/7297) - Excel5 reader: Column width - @Erik Tilt [CodePlex #7299](https://phpexcel.codeplex.com/workitem/7299) - Excel5 reader: Row height - @Erik Tilt [CodePlex #7301](https://phpexcel.codeplex.com/workitem/7301) - Excel5 reader: Font support - @Erik Tilt [CodePlex #7304](https://phpexcel.codeplex.com/workitem/7304) - Excel5 reader: support for locked cells - @Erik Tilt [CodePlex #7324](https://phpexcel.codeplex.com/workitem/7324) - Excel5 reader style support: Fill (background colors and patterns) - @Erik Tilt [CodePlex #7330](https://phpexcel.codeplex.com/workitem/7330) - Excel5 reader style support: Borders (style and color) - @Erik Tilt [CodePlex #7332](https://phpexcel.codeplex.com/workitem/7332) - Excel5 reader: Rich-Text support - @Erik Tilt [CodePlex #7346](https://phpexcel.codeplex.com/workitem/7346) - Read Excel built-in number formats with Excel 2007 reader - @MarkBaker [CodePlex #7313](https://phpexcel.codeplex.com/workitem/7313) - Excel5 reader: Number format support - @Erik Tilt [CodePlex #7317](https://phpexcel.codeplex.com/workitem/7317) - Creating a copy of PHPExcel object - @MarkBaker [CodePlex #7362](https://phpexcel.codeplex.com/workitem/7362) - Excel5 reader: support for row / column outline (group) - @Erik Tilt [CodePlex #7373](https://phpexcel.codeplex.com/workitem/7373) - Implement default row/column sizes - @MarkBaker [CodePlex #7380](https://phpexcel.codeplex.com/workitem/7380) - Writer HTML - option to return styles and table separately - @MarkBaker [CodePlex #7364](https://phpexcel.codeplex.com/workitem/7364) ### Bugfixes - Excel5 reader: Support for remaining built-in number formats - @Erik Tilt [CodePlex #7393](https://phpexcel.codeplex.com/workitem/7393) - Fixed rounding in HOUR MINUTE and SECOND Time functions, and improved performance for these - @MarkBaker - Fix to TRIM function - @MarkBaker - Fixed range validation in TIME Functions.php - @MarkBaker - EDATE and EOMONTH functions now return date values based on the returnDateType flag - @MarkBaker - Write date values that are the result of a calculation function correctly as Excel serialized dates rather than PHP serialized date values - @MarkBaker - Excel2007 reader not always reading boolean correctly - @MarkBaker [CodePlex #6690](https://phpexcel.codeplex.com/workitem/6690) - Columns above IZ - @MarkBaker [CodePlex #6275](https://phpexcel.codeplex.com/workitem/6275) - Other locale than English causes Excel2007 writer to produce broken xlsx - @MarkBaker [CodePlex #6853](https://phpexcel.codeplex.com/workitem/6853) - Typo: Number_fromat in NumberFormat.php - @MarkBaker [CodePlex #7061](https://phpexcel.codeplex.com/workitem/7061) - Bug in Worksheet_BaseDrawing setWidth() - @MarkBaker [CodePlex #6865](https://phpexcel.codeplex.com/workitem/6865) - PDF writer collapses column width for merged cells - @MarkBaker [CodePlex #6891](https://phpexcel.codeplex.com/workitem/6891) - Issues with drawings filenames - @MarkBaker [CodePlex #6867](https://phpexcel.codeplex.com/workitem/6867) - fromArray() local variable isn't defined - @MarkBaker [CodePlex #7073](https://phpexcel.codeplex.com/workitem/7073) - PHPExcel_Writer_Excel5->setTempDir() not passed to all classes involved in writing to a file - @MarkBaker [CodePlex #7276](https://phpexcel.codeplex.com/workitem/7276) - Excel5 reader not handling UTF-8 properly - @MarkBaker [CodePlex #7277](https://phpexcel.codeplex.com/workitem/7277) - If you write a 0 value in cell, cell shows as empty - @MarkBaker [CodePlex #7327](https://phpexcel.codeplex.com/workitem/7327) - Excel2007 writer: Row height ignored for empty rows - @MarkBaker [CodePlex #7302](https://phpexcel.codeplex.com/workitem/7302) - Excel2007 (comments related error) - @MarkBaker [CodePlex #7281](https://phpexcel.codeplex.com/workitem/7281) - Column width in other locale - @MarkBaker [CodePlex #7345](https://phpexcel.codeplex.com/workitem/7345) - Excel2007 reader not reading underlined Rich-Text - @MarkBaker [CodePlex #7347](https://phpexcel.codeplex.com/workitem/7347) - Excel5 reader converting booleans to strings - @Erik Tilt [CodePlex #7357](https://phpexcel.codeplex.com/workitem/7357) - Recursive Object Memory Leak - @MarkBaker [CodePlex #7365](https://phpexcel.codeplex.com/workitem/7365) - Excel2007 writer ignoring row dimensions without cells - @MarkBaker [CodePlex #7372](https://phpexcel.codeplex.com/workitem/7372) - Excel5 reader is converting formatted numbers / dates to strings - @Erik Tilt [CodePlex #7382](https://phpexcel.codeplex.com/workitem/7382) ## [1.6.2] - 2008-06-23 ### General - Document style array values - @MarkBaker [CodePlex #6088](https://phpexcel.codeplex.com/workitem/6088) - Applied patch 1195 - @MarkBaker - Redirecting output to a client’s web browser - http headers - @MarkBaker [CodePlex #6178](https://phpexcel.codeplex.com/workitem/6178) - Improve worksheet garbage collection - @MarkBaker [CodePlex #6187](https://phpexcel.codeplex.com/workitem/6187) - Functions that return date values can now be configured to return as Excel serialized date/time, PHP serialized date/time, or a PHP date/time object. - @MarkBaker - Functions that explicitly accept dates as parameters now permit values as Excel serialized date/time, PHP serialized date/time, a valid date string, or a PHP date/time object. - @MarkBaker - Implement ACOSH, ASINH and ATANH functions for those operating platforms/PHP versions that don't include these functions - @MarkBaker - Implement ATAN2 logic reversing the arguments as per Excel - @MarkBaker - Additional validation of parameters for COMBIN - @MarkBaker ### Features - Fixed validation for CEILING and FLOOR when the value and significance parameters have different signs; and allowed default value of 1 or -1 for significance when in GNUMERIC compatibility mode - @MarkBaker - Implement ADDRESS, ISLOGICAL, ISTEXT and ISNONTEXT functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Implement COMPLEX, IMAGINARY, IMREAL, IMARGUMENT, IMCONJUGATE, IMABS, IMSUB, IMDIV, IMSUM, IMPRODUCT, IMSQRT, IMEXP, IMLN, IMLOG10, IMLOG2, IMPOWER IMCOS and IMSIN Engineering functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Implement NETWORKDAYS and WORKDAY Date/Time functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Make cell column AAA available - @MarkBaker [CodePlex #6100](https://phpexcel.codeplex.com/workitem/6100) - Mark particular cell as selected when opening Excel - @MarkBaker [CodePlex #6095](https://phpexcel.codeplex.com/workitem/6095) - Multiple sheets in PDF and HTML - @MarkBaker [CodePlex #6120](https://phpexcel.codeplex.com/workitem/6120) - Implement PHPExcel_ReaderFactory and PHPExcel_WriterFactory - @MarkBaker [CodePlex #6227](https://phpexcel.codeplex.com/workitem/6227) - Set image root of PHPExcel_Writer_HTML - @MarkBaker [CodePlex #6249](https://phpexcel.codeplex.com/workitem/6249) - Enable/disable calculation cache - @MarkBaker [CodePlex #6264](https://phpexcel.codeplex.com/workitem/6264) - PDF writer and multi-line text - @MarkBaker [CodePlex #6259](https://phpexcel.codeplex.com/workitem/6259) - Feature request - setCacheExpirationTime() - @MarkBaker [CodePlex #6350](https://phpexcel.codeplex.com/workitem/6350) - Implement late-binding mechanisms to reduce memory footprint - @JB [CodePlex #6370](https://phpexcel.codeplex.com/workitem/6370) - Implement shared styles - @JB [CodePlex #6430](https://phpexcel.codeplex.com/workitem/6430) - Copy sheet from external Workbook to active Workbook - @MarkBaker [CodePlex #6391](https://phpexcel.codeplex.com/workitem/6391) ### Bugfixes - Functions in Conditional Formatting - @MarkBaker [CodePlex #6428](https://phpexcel.codeplex.com/workitem/6428) - Default Style in Excel5 - @MarkBaker [CodePlex #6096](https://phpexcel.codeplex.com/workitem/6096) - Numbers starting with '+' cause Excel 2007 errors - @MarkBaker [CodePlex #6150](https://phpexcel.codeplex.com/workitem/6150) - ExcelWriter5 is not PHP5 compatible, using it with E_STRICT results in a bunch of errors (applied patches) - @MarkBaker [CodePlex #6092](https://phpexcel.codeplex.com/workitem/6092) - Error Reader Excel2007 line 653 foreach ($relsDrawing->Relationship as $ele) - @MarkBaker [CodePlex #6179](https://phpexcel.codeplex.com/workitem/6179) - Worksheet toArray() screws up DATE - @MarkBaker [CodePlex #6229](https://phpexcel.codeplex.com/workitem/6229) - References to a Richtext cell in a formula - @MarkBaker [CodePlex #6253](https://phpexcel.codeplex.com/workitem/6253) - insertNewColumnBefore Bug - @MarkBaker [CodePlex #6285](https://phpexcel.codeplex.com/workitem/6285) - Error reading Excel2007 file with shapes - @MarkBaker [CodePlex #6319](https://phpexcel.codeplex.com/workitem/6319) - Determine whether date values need conversion from PHP dates to Excel dates before writing to file, based on the data type (float or integer) - @MarkBaker [CodePlex #6302](https://phpexcel.codeplex.com/workitem/6302) - Fixes to DATE function when it is given negative input parameters - @MarkBaker - PHPExcel handles empty cells other than Excel - @MarkBaker [CodePlex #6347](https://phpexcel.codeplex.com/workitem/6347) - PHPExcel handles 0 and "" as being the same - @MarkBaker [CodePlex #6348](https://phpexcel.codeplex.com/workitem/6348) - Problem Using Excel2007 Reader for Spreadsheets containing images - @MarkBaker [CodePlex #6357](https://phpexcel.codeplex.com/workitem/6357) - ShowGridLines ignored when reading/writing Excel 2007 - @MarkBaker [CodePlex #6359](https://phpexcel.codeplex.com/workitem/6359) - Bug With Word Wrap in Excel 2007 Reader - @MarkBaker [CodePlex #6426](https://phpexcel.codeplex.com/workitem/6426) ## [1.6.1] - 2008-04-28 ### General - Fix documentation printing - @MarkBaker [CodePlex #5532](https://phpexcel.codeplex.com/workitem/5532) - Memory usage improvements - @MarkBaker [CodePlex #5586](https://phpexcel.codeplex.com/workitem/5586) - Applied patch 990 - @MarkBaker ### Features - Applied patch 991 - @MarkBaker - Implement PHPExcel_Reader_Excel5 - @BM [CodePlex #2841](https://phpexcel.codeplex.com/workitem/2841) - Implement "toArray" and "fromArray" method - @MarkBaker [CodePlex #5564](https://phpexcel.codeplex.com/workitem/5564) - Read shared formula - @MarkBaker [CodePlex #5665](https://phpexcel.codeplex.com/workitem/5665) - Read image twoCellAnchor - @MarkBaker [CodePlex #5681](https://phpexcel.codeplex.com/workitem/5681) - &G Image as bg for headerfooter - @MarkBaker [CodePlex #4446](https://phpexcel.codeplex.com/workitem/4446) - Implement page layout functionality for Excel5 format - @MarkBaker [CodePlex #5834](https://phpexcel.codeplex.com/workitem/5834) ### Bugfixes - Feature request: PHPExcel_Writer_PDF - @MarkBaker [CodePlex #6039](https://phpexcel.codeplex.com/workitem/6039) - DefinedNames null check - @MarkBaker [CodePlex #5517](https://phpexcel.codeplex.com/workitem/5517) - Hyperlinks should not always have trailing slash - @MarkBaker [CodePlex #5463](https://phpexcel.codeplex.com/workitem/5463) - Saving Error - Uncaught exception (#REF! named range) - @MarkBaker [CodePlex #5592](https://phpexcel.codeplex.com/workitem/5592) - Error when creating Zip file on Linux System (Not Windows) - @MarkBaker [CodePlex #5634](https://phpexcel.codeplex.com/workitem/5634) - Time incorrecly formated - @MarkBaker [CodePlex #5876](https://phpexcel.codeplex.com/workitem/5876) - Conditional formatting - second rule not applied - @MarkBaker [CodePlex #5914](https://phpexcel.codeplex.com/workitem/5914) - PHPExcel_Reader_Excel2007 cannot load PHPExcel_Shared_File - @MarkBaker [CodePlex #5978](https://phpexcel.codeplex.com/workitem/5978) - Output redirection to web browser - @MarkBaker [CodePlex #6020](https://phpexcel.codeplex.com/workitem/6020) ## [1.6.0] - 2008-02-14 ### Features - Use PHPExcel datatypes in formula calculation - @MarkBaker [CodePlex #3156](https://phpexcel.codeplex.com/workitem/3156) - Center on page when printing - @MarkBaker [CodePlex #5019](https://phpexcel.codeplex.com/workitem/5019) - Hyperlink to other spreadsheet - @MarkBaker [CodePlex #5099](https://phpexcel.codeplex.com/workitem/5099) - Set the print area of a worksheet - @MarkBaker [CodePlex #5104](https://phpexcel.codeplex.com/workitem/5104) - Read "definedNames" property of worksheet - @MarkBaker [CodePlex #5118](https://phpexcel.codeplex.com/workitem/5118) - Set default style for all cells - @MarkBaker [CodePlex #5338](https://phpexcel.codeplex.com/workitem/5338) - Named Ranges - @MarkBaker [CodePlex #4216](https://phpexcel.codeplex.com/workitem/4216) ### Bugfixes - Implement worksheet references (Sheet1!A1) - @MarkBaker [CodePlex #5398](https://phpexcel.codeplex.com/workitem/5398) - Redirect output to a client's web browser - @MarkBaker [CodePlex #4967](https://phpexcel.codeplex.com/workitem/4967) - "File Error: data may have been lost." seen in Excel 2007 and Excel 2003 SP3 when opening XLS file - @MarkBaker [CodePlex #5008](https://phpexcel.codeplex.com/workitem/5008) - Bug in style's getHashCode() - @MarkBaker [CodePlex #5165](https://phpexcel.codeplex.com/workitem/5165) - PHPExcel_Reader not correctly reading numeric values - @MarkBaker [CodePlex #5165](https://phpexcel.codeplex.com/workitem/5165) - Text rotation is read incorrectly - @MarkBaker [CodePlex #5324](https://phpexcel.codeplex.com/workitem/5324) - Enclosure " and data " result a bad data : \" instead of "" - @MarkBaker [CodePlex #5326](https://phpexcel.codeplex.com/workitem/5326) - Formula parser - IF statement returning array instead of scalar - @MarkBaker [CodePlex #5332](https://phpexcel.codeplex.com/workitem/5332) - setFitToWidth(nbpage) & setFitToWidth(nbpage) work partially - @MarkBaker [CodePlex #5351](https://phpexcel.codeplex.com/workitem/5351) - Worksheet::setTitle() causes unwanted renaming - @MarkBaker [CodePlex #5361](https://phpexcel.codeplex.com/workitem/5361) - Hyperlinks not working. Results in broken xlsx file. - @MarkBaker [CodePlex #5407](https://phpexcel.codeplex.com/workitem/5407) ## [1.5.5] - 2007-12-24 ### General - Grouping Rows - @MarkBaker [CodePlex #4135](https://phpexcel.codeplex.com/workitem/4135) ### Features - Semi-nightly builds - @MarkBaker [CodePlex #4427](https://phpexcel.codeplex.com/workitem/4427) - Implement "date" datatype - @MarkBaker [CodePlex #3155](https://phpexcel.codeplex.com/workitem/3155) - Date format not honored in CSV writer - @MarkBaker [CodePlex #4150](https://phpexcel.codeplex.com/workitem/4150) - RichText and sharedStrings - @MarkBaker [CodePlex #4199](https://phpexcel.codeplex.com/workitem/4199) - Implement more Excel calculation functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Addition of DATE, DATEDIF, DATEVALUE, DAY, DAYS360- Implement more Excel calculation functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Addition of AVEDEV, HARMEAN and GEOMEAN - Addition of the BINOMDIST (Non-cumulative only), COUNTBLANK, EXPONDIST, FISHER, FISHERINV, NORMDIST, NORMSDIST, PERMUT, POISSON (Non-cumulative only) and STANDARDIZE Statistical Functions - Addition of the CEILING, COMBIN, EVEN, FACT, FACTDOUBLE, FLOOR, MULTINOMIAL, ODD, ROUNDDOWN, ROUNDUP, SIGN, SQRTPI and SUMSQ Mathematical Functions - Addition of the NORMINV, NORMSINV, CONFIDENCE and SKEW Statistical Functions - Addition of the CRITBINOM, HYPGEOMDIST, KURT, LOGINV, LOGNORMDIST, NEGBINOMDIST and WEIBULL Statistical Functions - Addition of the LARGE, PERCENTILE, QUARTILE, SMALL and TRIMMEAN Statistical Functions - Addition of the BIN2HEX, BIN2OCT, DELTA, ERF, ERFC, GESTEP, HEX2BIN, HEX2DEC, HEX2OCT, OCT2BIN and OCT2HEX Engineering Functions - Addition of the CHIDIST, GAMMADIST and GAMMALN Statistical Functions - Addition of the GCD, LCM, MROUND and SUBTOTAL Mathematical Functions - Addition of the LOWER, PROPER and UPPER Text Functions - Addition of the BETADIST and BETAINV Statistical Functions - Addition of the CHIINV and GAMMAINV Statistical Functions - Addition of the SERIESSUM Mathematical Function - Addition of the CHAR, CODE, FIND, LEN, REPT, SEARCH, T, TRIM Text Functions - Addition of the FALSE and TRUE Boolean Functions - Addition of the TDIST and TINV Statistical Functions - Addition of the EDATE, EOMONTH, YEAR, MONTH, TIME, TIMEVALUE, HOUR, MINUTE, SECOND, WEEKDAY, WEEKNUM, NOW, TODAY and Date/Time Function - Addition of the BESSELI, BESSELJ, BESSELK and BESSELY Engineering Functions - Addition of the SLN and SYD Financial Functions - reworked MODE calculation to handle floating point numbers - Improved error trapping for invalid input values - Fix to SMALL, LARGE, PERCENTILE and TRIMMEAN to eliminate non-numeric values - Added CDF to BINOMDIST and POISSON - Fix to a potential endless loop in CRITBINOM, together with other bugfixes to the algorithm - Fix to SQRTPI so that it will work with a real value parameter rather than just integers - Trap for passing negative values to FACT - Improved accuracy of the NORMDIST cumulative function, and of the ERF and ERFC functions - Replicated Excel data-type and error handling for BIN, DEC, OCT and HEX conversion functions - Replicated Excel data-type and error handling for AND and OR Boolean functions - Bugfix to MROUND - Rework of the DATE, DATEVALUE, DAY, DAYS360 and DATEDIF date/Time functions to use Excel dates rather than straight PHP dates - Rework of the AND, OR Boolean functions to ignore string values - Rework of the BIN2DEC, BIN2HEX, BIN2OCT, DEC2BIN, DEC2HEX, DEC2OCT Engineering functions to handle two's complement - Excel, Gnumeric and OpenOffice Calc compatibility flag for functions - Note, not all functions have yet been written to work with the Gnumeric and OpenOffice Calc compatibility flags - 1900 or 1904 Calendar flag for date functions - Reworked ExcelToPHP date method to handle the Excel 1900 leap year - Note that this will not correctly return values prior to 13-Dec-1901 20:45:52 as this is the minimum value that PHP date serial values can handle. If you need to work with dates prior to this, then an ExcelToPHPObject method has been added which will work correctly with values between Excel's 1900 calendar base date of 1-Jan-1900, and 13-Dec-1901 - Addition of ExcelToPHPObject date method to return a PHP DateTime object from an Excel date serial value - PHPToExcel method modified to accept either PHP date serial numbers or PHP DateTime objects - Addition of FormattedPHPToExcel which will accept a date and time broken to into year, month, day, hour, minute, second and return an Excel date serial value- Control characters in Excel 2007 - @MarkBaker [CodePlex #4485](https://phpexcel.codeplex.com/workitem/4485) - BaseDrawing::setWidthAndHeight method request - @MarkBaker [CodePlex #4796](https://phpexcel.codeplex.com/workitem/4796) - Page Setup -> Print Titles -> Sheet -> 'Rows to repeat at top' - @MarkBaker [CodePlex #4798](https://phpexcel.codeplex.com/workitem/4798) ### Bugfixes - Comment functionality - @MarkBaker [CodePlex #4433](https://phpexcel.codeplex.com/workitem/4433) - Undefined variable in PHPExcel_Writer_Serialized - @MarkBaker [CodePlex #4124](https://phpexcel.codeplex.com/workitem/4124) - Notice: Object of class PHPExcel_RichText could not be converted to int - @MarkBaker [CodePlex #4125](https://phpexcel.codeplex.com/workitem/4125) - Excel5Writer: utf8 string not converted to utf16 - @MarkBaker [CodePlex #4126](https://phpexcel.codeplex.com/workitem/4126) - PHPExcel_RichText and autosize - @MarkBaker [CodePlex #4180](https://phpexcel.codeplex.com/workitem/4180) - Excel5Writer produces broken xls files after change mentioned in work item 4126 - @MarkBaker [CodePlex #4574](https://phpexcel.codeplex.com/workitem/4574) - Small bug in PHPExcel_Reader_Excel2007 function _readStyle - @MarkBaker [CodePlex #4797](https://phpexcel.codeplex.com/workitem/4797) ## [1.5.0] - 2007-10-23 ### Features - Refactor PHPExcel Drawing - @MarkBaker [CodePlex #3265](https://phpexcel.codeplex.com/workitem/3265) - Update Shared/OLE.php to latest version from PEAR - @CS [CodePlex #3079](https://phpexcel.codeplex.com/workitem/3079) - Excel2007 vs Excel2003 compatibility pack - @MarkBaker [CodePlex #3217](https://phpexcel.codeplex.com/workitem/3217) - Cell protection (lock/unlock) - @MarkBaker [CodePlex #3234](https://phpexcel.codeplex.com/workitem/3234) - Create clickable links (hyperlinks) - @MarkBaker [CodePlex #3543](https://phpexcel.codeplex.com/workitem/3543) - Additional page setup parameters - @MarkBaker [CodePlex #3241](https://phpexcel.codeplex.com/workitem/3241) - Make temporary file path configurable (Excel5) - @MarkBaker [CodePlex #3300](https://phpexcel.codeplex.com/workitem/3300) - Small addition to applyFromArray for font - @MarkBaker [CodePlex #3306](https://phpexcel.codeplex.com/workitem/3306) ### Bugfixes - Better feedback when save of file is not possible - @MarkBaker [CodePlex #3373](https://phpexcel.codeplex.com/workitem/3373) - Text Rotation - @MarkBaker [CodePlex #3181](https://phpexcel.codeplex.com/workitem/3181) - Small bug in Page Orientation - @MarkBaker [CodePlex #3237](https://phpexcel.codeplex.com/workitem/3237) - insertNewColumnBeforeByColumn undefined - @MarkBaker [CodePlex #3812](https://phpexcel.codeplex.com/workitem/3812) - Sheet references not working in formula (Excel5 Writer) - @MarkBaker [CodePlex #3893](https://phpexcel.codeplex.com/workitem/3893) ## [1.4.5] - 2007-08-23 ### General - Class file endings - @MarkBaker [CodePlex #3003](https://phpexcel.codeplex.com/workitem/3003) - Different calculation engine improvements - @MarkBaker [CodePlex #3081](https://phpexcel.codeplex.com/workitem/3081) - Different improvements in PHPExcel_Reader_Excel2007 - @MarkBaker [CodePlex #3082](https://phpexcel.codeplex.com/workitem/3082) ### Features - Set XML indentation in PHPExcel_Writer_Excel2007 - @MarkBaker [CodePlex #3146](https://phpexcel.codeplex.com/workitem/3146) - Optionally store temporary Excel2007 writer data in file instead of memory - @MarkBaker [CodePlex #3159](https://phpexcel.codeplex.com/workitem/3159) - Implement show/hide gridlines - @MarkBaker [CodePlex #3063](https://phpexcel.codeplex.com/workitem/3063) - Implement option to read only data - @MarkBaker [CodePlex #3064](https://phpexcel.codeplex.com/workitem/3064) - Optionally disable formula precalculation - @MarkBaker [CodePlex #3080](https://phpexcel.codeplex.com/workitem/3080) - Explicitly set cell datatype - @MarkBaker [CodePlex #3154](https://phpexcel.codeplex.com/workitem/3154) ### Bugfixes - Implement more Excel calculation functions - @MarkBaker [CodePlex #2346](https://phpexcel.codeplex.com/workitem/2346) - Addition of MINA, MAXA, COUNTA, AVERAGEA, MEDIAN, MODE, DEVSQ, STDEV, STDEVA, STDEVP, STDEVPA, VAR, VARA, VARP and VARPA Excel Functions - Fix to SUM, PRODUCT, QUOTIENT, MIN, MAX, COUNT and AVERAGE functions when cell contains a numeric value in a string datatype, bringing it in line with MS Excel behaviour- File_exists on ZIP fails on some installations - @MarkBaker [CodePlex #2881](https://phpexcel.codeplex.com/workitem/2881) - Argument in textRotation should be -90..90 - @MarkBaker [CodePlex #2879](https://phpexcel.codeplex.com/workitem/2879) - Excel2007 reader/writer not implementing OpenXML/SpreadsheetML styles 100% correct - @MarkBaker [CodePlex #2883](https://phpexcel.codeplex.com/workitem/2883) - Active sheet index not read/saved - @MarkBaker [CodePlex #2513](https://phpexcel.codeplex.com/workitem/2513) - Print and print preview of generated XLSX causes Excel2007 to crash - @MarkBaker [CodePlex #2935](https://phpexcel.codeplex.com/workitem/2935) - Error in Calculations - COUNT() function - @MarkBaker [CodePlex #2952](https://phpexcel.codeplex.com/workitem/2952) - HTML and CSV writer not writing last row - @MarkBaker [CodePlex #3002](https://phpexcel.codeplex.com/workitem/3002) - Memory leak in Excel5 writer - @MarkBaker [CodePlex #3017](https://phpexcel.codeplex.com/workitem/3017) - Printing (PHPExcel_Writer_Excel5) - @MarkBaker [CodePlex #3044](https://phpexcel.codeplex.com/workitem/3044) - Problems reading zip:// - @MarkBaker [CodePlex #3046](https://phpexcel.codeplex.com/workitem/3046) - Error reading conditional formatting - @MarkBaker [CodePlex #3047](https://phpexcel.codeplex.com/workitem/3047) - Bug in Excel5 writer (storePanes) - @MarkBaker [CodePlex #3067](https://phpexcel.codeplex.com/workitem/3067) - Memory leak in PHPExcel_Style_Color - @MarkBaker [CodePlex #3077](https://phpexcel.codeplex.com/workitem/3077) ## [1.4.0] - 2007-07-23 ### General - Coding convention / code cleanup - @MarkBaker [CodePlex #2687](https://phpexcel.codeplex.com/workitem/2687) - Use set_include_path in tests - @MarkBaker [CodePlex #2717](https://phpexcel.codeplex.com/workitem/2717) ### Features - Move PHPExcel_Writer_Excel5 OLE to PHPExcel_Shared_OLE - @MarkBaker [CodePlex #2812](https://phpexcel.codeplex.com/workitem/2812) - Hide/Unhide Column or Row - @MarkBaker [CodePlex #2679](https://phpexcel.codeplex.com/workitem/2679) - Implement multi-cell styling - @MarkBaker [CodePlex #2271](https://phpexcel.codeplex.com/workitem/2271) - Implement CSV file format (reader/writer) - @MarkBaker [CodePlex #2720](https://phpexcel.codeplex.com/workitem/2720) ### Bugfixes - Implement HTML file format - @MarkBaker [CodePlex #2845](https://phpexcel.codeplex.com/workitem/2845) - Active sheet index not read/saved - @MarkBaker [CodePlex #2513](https://phpexcel.codeplex.com/workitem/2513) - Freeze Panes with PHPExcel_Writer_Excel5 - @MarkBaker [CodePlex #2678](https://phpexcel.codeplex.com/workitem/2678) - OLE.php - @MarkBaker [CodePlex #2680](https://phpexcel.codeplex.com/workitem/2680) - Copy and pasting multiple drop-down list cells breaks reader - @MarkBaker [CodePlex #2736](https://phpexcel.codeplex.com/workitem/2736) - Function setAutoFilterByColumnAndRow takes wrong arguments - @MarkBaker [CodePlex #2775](https://phpexcel.codeplex.com/workitem/2775) - Simplexml_load_file fails on ZipArchive - @MarkBaker [CodePlex #2858](https://phpexcel.codeplex.com/workitem/2858) ## [1.3.5] - 2007-06-27 ### Features - Documentation - @MarkBaker [CodePlex #15](https://phpexcel.codeplex.com/workitem/15) - PHPExcel_Writer_Excel5 - @JV - PHPExcel_Reader_Excel2007: Image shadows - @JV - Data validation - @MarkBaker [CodePlex #2385](https://phpexcel.codeplex.com/workitem/2385) ### Bugfixes - Implement richtext strings - @MarkBaker - Empty relations when adding image to any sheet but the first one - @MarkBaker [CodePlex #2443](https://phpexcel.codeplex.com/workitem/2443) - Excel2007 crashes on print preview - @MarkBaker [CodePlex #2536](https://phpexcel.codeplex.com/workitem/2536) ## [1.3.0] - 2007-06-05 ### General - Create PEAR package - @MarkBaker [CodePlex #1942](https://phpexcel.codeplex.com/workitem/1942) ### Features - Replace *->duplicate() by __clone() - @MarkBaker [CodePlex #2331](https://phpexcel.codeplex.com/workitem/2331) - PHPExcel_Reader_Excel2007: Column auto-size, Protection, Merged cells, Wrap text, Page breaks, Auto filter, Images - @JV - Implement "freezing" panes - @MarkBaker [CodePlex #245](https://phpexcel.codeplex.com/workitem/245) - Cell addressing alternative - @MarkBaker [CodePlex #2273](https://phpexcel.codeplex.com/workitem/2273) - Implement cell word-wrap attribute - @MarkBaker [CodePlex #2270](https://phpexcel.codeplex.com/workitem/2270) - Auto-size column - @MarkBaker [CodePlex #2282](https://phpexcel.codeplex.com/workitem/2282) - Implement formula calculation - @MarkBaker [CodePlex #241](https://phpexcel.codeplex.com/workitem/241) ### Bugfixes - Insert/remove row/column - @MarkBaker [CodePlex #2375](https://phpexcel.codeplex.com/workitem/2375) - PHPExcel_Worksheet::getCell() should not accept absolute coordinates - @MarkBaker [CodePlex #1931](https://phpexcel.codeplex.com/workitem/1931) - Cell reference without row number - @MarkBaker [CodePlex #2272](https://phpexcel.codeplex.com/workitem/2272) - Styles with same coordinate but different worksheet - @MarkBaker [CodePlex #2276](https://phpexcel.codeplex.com/workitem/2276) - PHPExcel_Worksheet->getCellCollection() usort error - @MarkBaker [CodePlex #2290](https://phpexcel.codeplex.com/workitem/2290) - Bug in PHPExcel_Cell::stringFromColumnIndex - @SS [CodePlex #2353](https://phpexcel.codeplex.com/workitem/2353) - Reader: numFmts can be missing, use cellStyleXfs instead of cellXfs in styles - @JV [CodePlex #2353](https://phpexcel.codeplex.com/workitem/2353) ## [1.2.0] - 2007-04-26 ### General - Stringtable attribute "count" not necessary, provides wrong info to Excel sometimes... - @MarkBaker - Updated tests to address more document properties - @MarkBaker - Some refactoring in PHPExcel_Writer_Excel2007_Workbook - @MarkBaker - New package: PHPExcel_Shared - @MarkBaker - Password hashing algorithm implemented in PHPExcel_Shared_PasswordHasher - @MarkBaker - Moved pixel conversion functions to PHPExcel_Shared_Drawing - @MarkBaker - Switch over to LGPL license - @MarkBaker [CodePlex #244](https://phpexcel.codeplex.com/workitem/244) ### Features - Include PHPExcel version in file headers - @MarkBaker [CodePlex #5](https://phpexcel.codeplex.com/workitem/5) - Autofilter - @MarkBaker [CodePlex #6](https://phpexcel.codeplex.com/workitem/6) - Extra document property: keywords - @MarkBaker [CodePlex #7](https://phpexcel.codeplex.com/workitem/7) - Extra document property: category - @MarkBaker [CodePlex #8](https://phpexcel.codeplex.com/workitem/8) - Document security - @MarkBaker [CodePlex #9](https://phpexcel.codeplex.com/workitem/9) - PHPExcel_Writer_Serialized and PHPExcel_Reader_Serialized - @MarkBaker [CodePlex #10](https://phpexcel.codeplex.com/workitem/10) - Alternative syntax: Addressing a cell - @MarkBaker [CodePlex #11](https://phpexcel.codeplex.com/workitem/11) - Merge cells - @MarkBaker [CodePlex #12](https://phpexcel.codeplex.com/workitem/12) ### Bugfixes - Protect ranges of cells with a password - @MarkBaker [CodePlex #13](https://phpexcel.codeplex.com/workitem/13) - (style/fill/patternFill/fgColor or bgColor can be empty) - @JV [CodePlex #14](https://phpexcel.codeplex.com/workitem/14) ## [1.1.1] - 2007-03-26 ### General - Syntax error in "Classes/PHPExcel/Writer/Excel2007.php" on line 243 - @MarkBaker [CodePlex #1250](https://phpexcel.codeplex.com/workitem/1250) - Reader should check if file exists and throws an exception when it doesn't - @MarkBaker [CodePlex #1282](https://phpexcel.codeplex.com/workitem/1282) ## [1.1.0] - 2007-03-22 ### Bugfixes - Style information lost after passing trough Excel2007_Reader - @MarkBaker [CodePlex #836](https://phpexcel.codeplex.com/workitem/836) ### General - Number of columns > AZ fails fixed in PHPExcel_Cell::columnIndexFromString - @MarkBaker [CodePlex #913](https://phpexcel.codeplex.com/workitem/913) ### Features - Added a brief file with installation instructions - @MarkBaker - Page breaks (horizontal and vertical) - @MarkBaker - Image shadows - @MarkBaker ## [1.0.0] - 2007-02-22 ### Bugfixes - PHPExcel->removeSheetByIndex now re-orders sheets after deletion, so no array indexes are lost - @JV - PHPExcel_Writer_Excel2007_Worksheet::_writeCols() used direct assignment to $pSheet->getColumnDimension('A')->Width instead of $pSheet->getColumnDimension('A')->setWidth() - @JV - DocumentProperties used $this->LastModifiedBy instead of $this->_lastModifiedBy. - @JV ### General - Only first = should be removed when writing formula in PHPExcel_Writer_Excel2007_Worksheet. - @JV - Consistency of method names to camelCase - @JV - Updated tests to match consistency changes - @JV - Detection of mime-types now with image_type_to_mime_type() - @JV - Constants now hold string value used in Excel 2007 - @JV ### Features - Fixed folder name case (WorkSheet -> Worksheet) - @MarkBaker - PHPExcel classes (not the Writer classes) can be duplicated, using a duplicate() method. - @MarkBaker - Cell styles can now be duplicated to a range of cells using PHPExcel_Worksheet->duplicateStyle() - @MarkBaker - Conditional formatting - @MarkBaker - Reader for Excel 2007 (not supporting full specification yet!) - @JV ## [1.0.0 RC] - 2007-01-31 - Project name has been changed to PHPExcel - Project homepage is now http://www.codeplex.com/PHPExcel - Started versioning at number: PHPExcel 1.0.0 RC ## 2007-01-22 - Fixed some performance issues on large-scale worksheets (mainly loops vs. indexed arrays) - Performance on creating StringTable has been increased - Performance on writing Excel2007 worksheet has been increased ## 2007-01-18 - Images can now be rotated - Fixed bug: When drawings have full path specified, no mime type can be deducted - Fixed bug: Only one drawing can be added to a worksheet ## 2007-01-12 - Refactoring of some classes to use ArrayObject instead of array() - Cell style now has support for number format (i.e. #,##0) - Implemented embedding images ## 2007-01-02 - Cell style now has support for fills, including gradient fills - Cell style now has support for fonts - Cell style now has support for border colors - Cell style now has support for font colors - Cell style now has support for alignment ## 2006-12-21 - Support for cell style borders - Support for cell styles - Refactoring of Excel2007 Writer into multiple classes in package SpreadSheet_Writer_Excel2007 - Refactoring of all classes, changed public members to public properties using getter/setter - Worksheet names are now unique. On duplicate worksheet names, a number is appended. - Worksheet now has parent SpreadSheet object - Worksheet now has support for page header and footer - Worksheet now has support for page margins - Worksheet now has support for page setup (only Paper size and Orientation) - Worksheet properties now accessible by using getProperties() - Worksheet now has support for row and column dimensions (height / width) - Exceptions thrown have a more clear description ## Initial version - Create a Spreadsheet object - Add one or more Worksheet objects - Add cells to Worksheet objects - Export Spreadsheet object to Excel 2007 OpenXML format - Each cell supports the following data formats: string, number, formula, boolean. ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com) and this project adheres to [Semantic Versioning](https://semver.org). Thia is always true of the master branch. Some earlier branches remain supported and security fixes are applied to them; if the security fix represents a breaking change, it may have to be applied as a minor or patch version. ## TBD - 5.6.0 ### Added - Nothing yet. ### Removed - Nothing yet. ### Changed - Nothing yet. ### Moved - Nothing yet. ### Deprecated - Collection/Cells::MAX_COLUMN_ID - use Cell/AddressRange::MAX_COLUMN_INT. - Writer/Xls/Worksheet constants MAX_XLS_COLUMN, MAX_XLS_COLUMN_STRING, MAX_XLS_ROW - use Cell/AddressRange MAX_COLUMN_INT_XLS, MAX_COLUMN_XLS, MAX_ROW_XLS ### Fixed - Consistent handling of row and column limits. [PR #4820](https://github.com/PHPOffice/PhpSpreadsheet/pull/4820) ## 2026-02-28 - 5.5.0 ### Added - Much improved handling of Styles by Ods Reader. The relevant changes are listed at the end of the "Fixed" section below. - Option to use OldCalculatedValue in ToArray and Relatives. [Issue #1810](https://github.com/PHPOffice/PhpSpreadsheet/issues/1810) [PR #4787](https://github.com/PHPOffice/PhpSpreadsheet/pull/4787) - Add checkbox style (Xlsx and Html). [PR #4781](https://github.com/PHPOffice/PhpSpreadsheet/pull/4781) - Option to whitelist external images. [PR #4793](https://github.com/PHPOffice/PhpSpreadsheet/pull/4793) - Writer/Html add ability to set line ending. [PR #4779](https://github.com/PHPOffice/PhpSpreadsheet/pull/4779) - Writer/Html optionally save formulas as data attributes. [PR #4783](https://github.com/PHPOffice/PhpSpreadsheet/pull/4783) - User-supplied headers and footers in PDF. [Issue #3159](https://github.com/PHPOffice/PhpSpreadsheet/issues/3159) [PR #4789](https://github.com/PHPOffice/PhpSpreadsheet/pull/4789) ### Deprecated - Writer/Html constant BODY_LINE no longer makes sense with a configurable line ending. No replacement. - Calculation classes FormulaParser and FormulaToken are unused. No replacement. - Writer/Xls/Worksheet methods insertBitMap, positionImage, writeObjPicture, processBitmapGd, and processBitmap are unused. No replacement. ### Fixed - Improve performance in value binders. [PR #4780](https://github.com/PHPOffice/PhpSpreadsheet/pull/4780) - Handle Unions as Function Arguments. [Issue #4656](https://github.com/PHPOffice/PhpSpreadsheet/issues/4656) [Issue #316](https://github.com/PHPOffice/PhpSpreadsheet/issues/316) [Issue #503](https://github.com/PHPOffice/PhpSpreadsheet/issues/503) [PR #4657](https://github.com/PHPOffice/PhpSpreadsheet/pull/4657) - Unexpected Behavior of CONCATENATE. [Issue #4061](https://github.com/PHPOffice/PhpSpreadsheet/issues/4061) [PR #4797](https://github.com/PHPOffice/PhpSpreadsheet/pull/4797) - Image Css size in millimeters. [Issue #4800](https://github.com/PHPOffice/PhpSpreadsheet/issues/4800) [PR #4801](https://github.com/PHPOffice/PhpSpreadsheet/pull/4801) - Ods Reader column misalignment. [Issue #4802](https://github.com/PHPOffice/PhpSpreadsheet/issues/4802) [PR #4803](https://github.com/PHPOffice/PhpSpreadsheet/pull/4803) - Ods improved handling of number formats. [Issue #3961](https://github.com/PHPOffice/PhpSpreadsheet/issues/3961) [Issue #4798](https://github.com/PHPOffice/PhpSpreadsheet/issues/4798) [PR #4806](https://github.com/PHPOffice/PhpSpreadsheet/pull/4806) - Ods Reader fonts and fills. [Issue #2622](https://github.com/PHPOffice/PhpSpreadsheet/issues/2622) [Issue #1191](https://github.com/PHPOffice/PhpSpreadsheet/issues/1191) [PR #4810](https://github.com/PHPOffice/PhpSpreadsheet/pull/4810) - Ods Reader alignment and cell protection. [PR #4813](https://github.com/PHPOffice/PhpSpreadsheet/pull/4813) - Ods Reader borders. [PR #4814](https://github.com/PHPOffice/PhpSpreadsheet/pull/4814) - Ods Reader column styles (partial). [PR #4815](https://github.com/PHPOffice/PhpSpreadsheet/pull/4815) ## 2026-01-10 - 5.4.0 ### Added - Store image in cell (Xlsx only). [Issue #4014](https://github.com/PHPOffice/PhpSpreadsheet/issues/4014) [Issue #4034](https://github.com/PHPOffice/PhpSpreadsheet/issues/4034) [Issue #913](https://github.com/PHPOffice/PhpSpreadsheet/issues/913) [PR #4677](https://github.com/PHPOffice/PhpSpreadsheet/pull/4677) - Passthrough support (with some restrictions) for otherwise unsupported drawing elements. [Issue #4037](https://github.com/PHPOffice/PhpSpreadsheet/issues/4037) [Issue #4704](https://github.com/PHPOffice/PhpSpreadsheet/issues/4704) [PR #4712](https://github.com/PHPOffice/PhpSpreadsheet/pull/4712) - Set all locale variables at once in a threadsafe manner. [Issue #954](https://github.com/PHPOffice/PhpSpreadsheet/issues/954) [PR #4760](https://github.com/PHPOffice/PhpSpreadsheet/pull/4760) - Reader/Html add ability to suppress warning messages from loadhtml. [Issue #647](https://github.com/PHPOffice/PhpSpreadsheet/issues/647) [Issue #849](https://github.com/PHPOffice/PhpSpreadsheet/issues/849) [PR #4761](https://github.com/PHPOffice/PhpSpreadsheet/pull/4761) ### Changed - Evaluation of WEBSERVICE no longer requires external client, but will use oldCalculatedValue unless the request is for a domain in a user-supplied whitelist. [PR #4751](https://github.com/PHPOffice/PhpSpreadsheet/pull/4751) ### Moved - Code to merge cell base style with table and conditional styles moved from Html Writer to its own class. [Issue #1058](https://github.com/PHPOffice/PhpSpreadsheet/issues/1058) [PR #4763](https://github.com/PHPOffice/PhpSpreadsheet/pull/4763) ### Deprecated - Settings methods setHttpClient, unsetHttpClient, getHttpClient, and getRequestFactory are no longer used. No replacement. - Reader/Html protected property dataArray, described as used only for testing, is not used for testing. No replacement. ### Fixed - Slightly better support for escaped characters in Xlsx Reader/Writer. [Discussion #4724](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4724) [PR #4726](https://github.com/PHPOffice/PhpSpreadsheet/pull/4726) - CODE/UNICODE and CHAR/UNICHAR. [PR #4727](https://github.com/PHPOffice/PhpSpreadsheet/pull/4727) - Minor changes to TextGrid. [PR #4735](https://github.com/PHPOffice/PhpSpreadsheet/pull/4735) [PR #4743](https://github.com/PHPOffice/PhpSpreadsheet/pull/4743) - Single-character table names. [Issue #4739](https://github.com/PHPOffice/PhpSpreadsheet/issues/4739) [PR #4740](https://github.com/PHPOffice/PhpSpreadsheet/pull/4740) - Improvements to SORT and SORTBY. [PR #4743](https://github.com/PHPOffice/PhpSpreadsheet/pull/4743) - Coverage-related changes in Shared. [PR #4745](https://github.com/PHPOffice/PhpSpreadsheet/pull/4745) - ListWorksheetInfo improvements for Xlsx and Ods. [Issue #3255](https://github.com/PHPOffice/PhpSpreadsheet/issues/3255) [PR #4746](https://github.com/PHPOffice/PhpSpreadsheet/pull/4746) - Fix functions related to Student-T distribution. [Issue #4167](https://github.com/PHPOffice/PhpSpreadsheet/issues/4167) [PR #4748](https://github.com/PHPOffice/PhpSpreadsheet/pull/4748) - Fix drawing hyperlinks. [Issue #993](https://github.com/PHPOffice/PhpSpreadsheet/issues/993) [PR #4764](https://github.com/PHPOffice/PhpSpreadsheet/pull/4764) - Fix clone spreadsheet with defined names. [PR #4753](https://github.com/PHPOffice/PhpSpreadsheet/pull/4753) - Changes to WEBSERVICE. [PR #4751](https://github.com/PHPOffice/PhpSpreadsheet/pull/4751) - More consistent handling of unsupported functions. [Issue #606](https://github.com/PHPOffice/PhpSpreadsheet/issues/606) [PR #4772](https://github.com/PHPOffice/PhpSpreadsheet/pull/4772) - Chart shadow `kx` and `ky`. [PR #4770](https://github.com/PHPOffice/PhpSpreadsheet/pull/4770) - SUBTOTAL and hidden rows. [Issue #820](https://github.com/PHPOffice/PhpSpreadsheet/issues/820) [PR #4765](https://github.com/PHPOffice/PhpSpreadsheet/pull/4765) - Fix some hyperlink problems. [Issue #3889](https://github.com/PHPOffice/PhpSpreadsheet/issues/3889) [Issue #2464](https://github.com/PHPOffice/PhpSpreadsheet/issues/2464) [PR #4771](https://github.com/PHPOffice/PhpSpreadsheet/pull/4771) - Xls Writer and empty RichText. [Issue #918](https://github.com/PHPOffice/PhpSpreadsheet/issues/918) [PR #4769](https://github.com/PHPOffice/PhpSpreadsheet/pull/4769) - Strings that look like huge floating-point numbers. [Issue #4766](https://github.com/PHPOffice/PhpSpreadsheet/issues/4766) [PR #4768](https://github.com/PHPOffice/PhpSpreadsheet/pull/4768) - Rowspan in Html. [Issue #1319](https://github.com/PHPOffice/PhpSpreadsheet/issues/1319) [PR #4767](https://github.com/PHPOffice/PhpSpreadsheet/pull/4767) - Mpdf styling of multi-line strings. [Issue #4773](https://github.com/PHPOffice/PhpSpreadsheet/issues/4773) [PR #4775](https://github.com/PHPOffice/PhpSpreadsheet/pull/4775) ## 2025-11-24 - 5.3.0 ### Added - Formal support for Php8.5. - Limited Printarea support for Html/Pdf. [Issue #3941](https://github.com/PHPOffice/PhpSpreadsheet/issues/3941) [PR #4711](https://github.com/PHPOffice/PhpSpreadsheet/pull/4711) - Implement missing `INFO` function. [PR #4709](https://github.com/PHPOffice/PhpSpreadsheet/pull/4709) - Implement missing `BAHTTEXT` function. [PR #4715](https://github.com/PHPOffice/PhpSpreadsheet/pull/4715) ### Deprecated - $dataType, the second parameter of Cell::setValueExplicit, is currently optional. Omitting it is deprecated, and it will be required in a future release. ### Fixed - Protected ranges and insert/delete rows/columns. [Issue #4695](https://github.com/PHPOffice/PhpSpreadsheet/issues/4695) [PR #4702](https://github.com/PHPOffice/PhpSpreadsheet/pull/4702) - Unexpected Exception in Php DateTime. [Issue #4696](https://github.com/PHPOffice/PhpSpreadsheet/issues/4696) [Issue #917](https://github.com/PHPOffice/PhpSpreadsheet/issues/917) [PR #4697](https://github.com/PHPOffice/PhpSpreadsheet/pull/4697) - Add missing Dutch translation to translation file. [PR #4707](https://github.com/PHPOffice/PhpSpreadsheet/pull/4707) - Fix lots of typos throughout codebase. [PR #4705](https://github.com/PHPOffice/PhpSpreadsheet/pull/4705) - Apply small code style improvements. [PR #4708](https://github.com/PHPOffice/PhpSpreadsheet/pull/4708) ## 2025-10-25 - 5.2.0 ### Added - This release should be usable with Php8.5 Release Candidates without deprecation messages. - Option to display numbers with less precision. [Issue #4626](https://github.com/PHPOffice/PhpSpreadsheet/issues/4626) [PR #4640](https://github.com/PHPOffice/PhpSpreadsheet/pull/4640) - Offer Tcpdf Interface which throws exception rather than die. [PR #4666](https://github.com/PHPOffice/PhpSpreadsheet/pull/4666) - Xls Reader ListWorksheetDimensions method. [PR #4689](https://github.com/PHPOffice/PhpSpreadsheet/pull/4689) ### Deprecated - Worksheet::getHashInt serves no useful purpose. No replacement. - Spreadsheet::getId serves no useful purpose. No replacement. ### Fixed - Performance improvement when working with large amounts of cells. [Issue #4607](https://github.com/PHPOffice/PhpSpreadsheet/issues/4607) [PR #4609](https://github.com/PHPOffice/PhpSpreadsheet/pull/4609) - Minor improvements to Calculation coverage. [PR #4624](https://github.com/PHPOffice/PhpSpreadsheet/pull/4624) - Conditional formatting in extLst. [Issue #4629](https://github.com/PHPOffice/PhpSpreadsheet/issues/4629) [PR #4633](https://github.com/PHPOffice/PhpSpreadsheet/pull/4633) - Php8.5 deprecates use of null as array index. [PR #4634](https://github.com/PHPOffice/PhpSpreadsheet/pull/4634) - Wrapped cells and default row height. [Issue #4584](https://github.com/PHPOffice/PhpSpreadsheet/issues/4584) [PR #4645](https://github.com/PHPOffice/PhpSpreadsheet/pull/4645) - For Php8.5, replace one of our two uses of `__wakeup` with `__unserialize`, and eliminate the other. [PR #4639](https://github.com/PHPOffice/PhpSpreadsheet/pull/4639) - Use prefix _xlfn for BASE function. [Issue #4638](https://github.com/PHPOffice/PhpSpreadsheet/issues/4638) [PR #4641](https://github.com/PHPOffice/PhpSpreadsheet/pull/4641) - Warning messages with corrupt Xls file. [Issue #4647](https://github.com/PHPOffice/PhpSpreadsheet/issues/4647) [PR #4648](https://github.com/PHPOffice/PhpSpreadsheet/pull/4648) - Additional support for union and intersection. [PR #4596](https://github.com/PHPOffice/PhpSpreadsheet/pull/4596) - Missing array keys x,o,v for Xml Reader. [Issue #4668](https://github.com/PHPOffice/PhpSpreadsheet/issues/4668) [PR #4669](https://github.com/PHPOffice/PhpSpreadsheet/pull/4669) - Missing array key x for Xlsx Reader VML. [Issue #4505](https://github.com/PHPOffice/PhpSpreadsheet/issues/4505) [PR #4676](https://github.com/PHPOffice/PhpSpreadsheet/pull/4676) - Better support for Style Alignment Read Order. [Issue #850](https://github.com/PHPOffice/PhpSpreadsheet/issues/850) [PR #4655](https://github.com/PHPOffice/PhpSpreadsheet/pull/4655) - More sophisticated workbook password algorithms (Xlsx only). [Issue #4673](https://github.com/PHPOffice/PhpSpreadsheet/issues/4673) [PR #4675](https://github.com/PHPOffice/PhpSpreadsheet/pull/4675) - Xls Writer fix DIMENSIONS record. [Issue #4682](https://github.com/PHPOffice/PhpSpreadsheet/issues/4682) [PR #4687](https://github.com/PHPOffice/PhpSpreadsheet/pull/4687) - Xls Reader listWorksheetInfo process MULRK records. [PR #4689](https://github.com/PHPOffice/PhpSpreadsheet/pull/4689) - Make Reader Xls Escher generic. [PR #4690](https://github.com/PHPOffice/PhpSpreadsheet/pull/4690) ## 2025-09-03 - 5.1.0 ### Added - Add Conditional Formatting with IconSet (Xlsx only). [Issue #4560](https://github.com/PHPOffice/PhpSpreadsheet/issues/4560) [PR #4574](https://github.com/PHPOffice/PhpSpreadsheet/pull/4574) - Copy cell adjusting formula. [Issue #1203](https://github.com/PHPOffice/PhpSpreadsheet/issues/1203) [PR #4577](https://github.com/PHPOffice/PhpSpreadsheet/pull/4577) - splitRange and ProtectedRange. [Issue #1457](https://github.com/PHPOffice/PhpSpreadsheet/issues/1457) [PR #4580](https://github.com/PHPOffice/PhpSpreadsheet/pull/4580) - Option to create Blank Sheet if LoadSheetsOnly doesn't find any. [PR #4618](https://github.com/PHPOffice/PhpSpreadsheet/pull/4618) ### Fixed - Google-only formulas exported from Google Sheets. [Issue #1637](https://github.com/PHPOffice/PhpSpreadsheet/issues/1637) [PR #4579](https://github.com/PHPOffice/PhpSpreadsheet/pull/4579) - Maximum column width. [PR #4581](https://github.com/PHPOffice/PhpSpreadsheet/pull/4581) - PrintArea after row/column delete. [Issue #2912](https://github.com/PHPOffice/PhpSpreadsheet/issues/2912) [PR #4598](https://github.com/PHPOffice/PhpSpreadsheet/pull/4598) - Remove deprecated imagedestroy call. [PR #4625](https://github.com/PHPOffice/PhpSpreadsheet/pull/4625) - Excel 2007 problem with newlines. [Issue #4619](https://github.com/PHPOffice/PhpSpreadsheet/issues/4619) [PR #4620](https://github.com/PHPOffice/PhpSpreadsheet/pull/4620) - Compatibility changes for Php 8.5. [PR #4601](https://github.com/PHPOffice/PhpSpreadsheet/pull/4601) [PR #4611](https://github.com/PHPOffice/PhpSpreadsheet/pull/4611) ## 2025-08-10 - 5.0.0 ### Breaking Changes - Images will be loaded from an external source (e.g. http://example.com/img.png) only if the reader is explicitly set to allow it via `$reader->setAllowExternalImages(true)`. We do not believe that loading of external images is a widely used feature. - Deletion of items deprecated in Release 4. See "removed" below. - Move some properties from Base Reader to Html Reader. [PR #4551](https://github.com/PHPOffice/PhpSpreadsheet/pull/4551) - DefaultValueBinder will treat integers with more than 15 digits as strings. [Issue #4522](https://github.com/PHPOffice/PhpSpreadsheet/issues/4522) [PR #4527](https://github.com/PHPOffice/PhpSpreadsheet/pull/4527) ### Removed - Theme public constants COLOR_SCHEME_2013_PLUS_NAME (use COLOR_SCHEME_2013_2022_NAME) and COLOR_SCHEME_2013_PLUS (use COLOR_SCHEME_2013_2022). ### Fixed - Additional floating-point precision changes. [Issue #1324](https://github.com/PHPOffice/PhpSpreadsheet/issues/1324) [PR #4575](https://github.com/PHPOffice/PhpSpreadsheet/pull/4575) - Header/Footer images expand location. [Issue #484](https://github.com/PHPOffice/PhpSpreadsheet/issues/484) [Issue #1318](https://github.com/PHPOffice/PhpSpreadsheet/issues/1318) [PR #4572](https://github.com/PHPOffice/PhpSpreadsheet/pull/4572) - Create uninitialized cell if used in calculation. [Issue #4558](https://github.com/PHPOffice/PhpSpreadsheet/issues/4558) [Issue #4530](https://github.com/PHPOffice/PhpSpreadsheet/issues/4530) [PR #4565](https://github.com/PHPOffice/PhpSpreadsheet/pull/4565) - Shared/Date::isDateTime handle cells which calculate as arrays. [Issue #4557](https://github.com/PHPOffice/PhpSpreadsheet/issues/4557) [PR #4562](https://github.com/PHPOffice/PhpSpreadsheet/pull/4562) - Xlsx Writer eliminate xml:space from non-text nodes. [Issue #4542](https://github.com/PHPOffice/PhpSpreadsheet/issues/4542) [PR #4556](https://github.com/PHPOffice/PhpSpreadsheet/pull/4556) ## 2025-07-23 - 4.5.0 ### Added - Add to all readers the option to allow or forbid fetching external images. This is unconditionally allowed now. The default will be set to "allow", so no code changes are necessary. However, we are giving consideration to changing the default. [PR #4543](https://github.com/PHPOffice/PhpSpreadsheet/pull/4543) - Address Excel Inappropriate Number Format Substitution. [PR #4532](https://github.com/PHPOffice/PhpSpreadsheet/pull/4532) ### Fixed - Html Writer Conditional Formatting Inline Css. [Issue #4539](https://github.com/PHPOffice/PhpSpreadsheet/issues/4539) [PR #4541](https://github.com/PHPOffice/PhpSpreadsheet/pull/4541) - Do not use htmlspecialchars when formatting XML. [Issue #4537](https://github.com/PHPOffice/PhpSpreadsheet/issues/4537) [PR #4540](https://github.com/PHPOffice/PhpSpreadsheet/pull/4540) - Writer Html/Pdf support RTL alignment of tables. [Issue #1104](https://github.com/PHPOffice/PhpSpreadsheet/issues/1104) [PR #4535](https://github.com/PHPOffice/PhpSpreadsheet/pull/4535) - Xlsx Reader use dynamic arrays if spreadsheet did so. [PR #4533](https://github.com/PHPOffice/PhpSpreadsheet/pull/4533) - Ods Reader Nested table-row. [Issue #4528](https://github.com/PHPOffice/PhpSpreadsheet/issues/4528) [Issue #2507](https://github.com/PHPOffice/PhpSpreadsheet/issues/2507) [PR #4531](https://github.com/PHPOffice/PhpSpreadsheet/pull/4531) - Recognize application/x-empty mimetype. [Issue #4521](https://github.com/PHPOffice/PhpSpreadsheet/issues/4521) [PR #4524](https://github.com/PHPOffice/PhpSpreadsheet/pull/4524) - Micro-optimization in getSheetByName. [PR #4499](https://github.com/PHPOffice/PhpSpreadsheet/pull/4499) - Bug in resizeMatricesExtend. [Issue #4451](https://github.com/PHPOffice/PhpSpreadsheet/issues/4451) [PR #4474](https://github.com/PHPOffice/PhpSpreadsheet/pull/4474) - Allow Replace of Dummy Function with Custom Function. [PR #4544](https://github.com/PHPOffice/PhpSpreadsheet/pull/4544) - Preserve 0x0a in Strings if Desired. [Issue #347](https://github.com/PHPOffice/PhpSpreadsheet/issues/347) [PR #4536](https://github.com/PHPOffice/PhpSpreadsheet/pull/4536) ## 2025-06-22 - 4.4.0 ### Added - VSTACK and HSTACK. [Issue #4485](https://github.com/PHPOffice/PhpSpreadsheet/issues/4485) [PR #4492](https://github.com/PHPOffice/PhpSpreadsheet/pull/4492) - TOCOL and TOROW. [PR #4493](https://github.com/PHPOffice/PhpSpreadsheet/pull/4493) - Support Current Office Theme. [PR #4500](https://github.com/PHPOffice/PhpSpreadsheet/pull/4500) ### Deprecated - Theme constants COLOR_SCHEME_2013_PLUS_NAME (use COLOR_SCHEME_2013_2022_NAME) and COLOR_SCHEME_2013_PLUS (use COLOR_SCHEME_2013_2022). ### Fixed - Various Writers RichText TextElement Should Inherit Cell Style. [Issue #1154](https://github.com/PHPOffice/PhpSpreadsheet/issues/1154) [PR #4487](https://github.com/PHPOffice/PhpSpreadsheet/pull/4487) - Minor Changes to FILTER function. [PR #4491](https://github.com/PHPOffice/PhpSpreadsheet/pull/4491) - Allow Xlsx Reader/Writer to support Font Charset. [Issue #2760](https://github.com/PHPOffice/PhpSpreadsheet/issues/2760) [PR #4501](https://github.com/PHPOffice/PhpSpreadsheet/pull/4501) - AutoColor for LibreOffice Dark Mode [Discussion 4502](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4502) [PR #4503](https://github.com/PHPOffice/PhpSpreadsheet/pull/4503) - Xlsx Style Writer Minor Refactoring. [PR #4508](https://github.com/PHPOffice/PhpSpreadsheet/pull/4508) - Allow Xlsx Reader to Specify ParseHuge. [Issue #4260](https://github.com/PHPOffice/PhpSpreadsheet/issues/4260) [PR #4515](https://github.com/PHPOffice/PhpSpreadsheet/pull/4515) ## 2025-05-26 - 4.3.1 ### Fixed - Regression in Date::stringToExcel. [Issue #4488](https://github.com/PHPOffice/PhpSpreadsheet/issues/4488) [PR #4489](https://github.com/PHPOffice/PhpSpreadsheet/pull/4489) ## 2025-05-25 - 4.3.0 ### Added - Xml Reader recognize indents. [Issue #4448](https://github.com/PHPOffice/PhpSpreadsheet/issues/4448) [PR #4449](https://github.com/PHPOffice/PhpSpreadsheet/pull/4449) ### Changed - Phpstan Level 10. ### Fixed - Micro-optimization for excelToDateTimeObject. [Issue #4438](https://github.com/PHPOffice/PhpSpreadsheet/issues/4438) [PR #4442](https://github.com/PHPOffice/PhpSpreadsheet/pull/4442) - Removing Columns/Rows Containing Merged Cells. [Issue #282](https://github.com/PHPOffice/PhpSpreadsheet/issues/282) [PR #4465](https://github.com/PHPOffice/PhpSpreadsheet/pull/4465) - Print Area and Row Break. [Issue #1275](https://github.com/PHPOffice/PhpSpreadsheet/issues/1275) [PR #4450](https://github.com/PHPOffice/PhpSpreadsheet/pull/4450) - Copy Styles after insertNewColumnBefore. [Issue #1425](https://github.com/PHPOffice/PhpSpreadsheet/issues/1425) [PR #4468](https://github.com/PHPOffice/PhpSpreadsheet/pull/4468) - Xls Writer Treat Hyperlink Starting with # as Internal. [Issue #56](https://github.com/PHPOffice/PhpSpreadsheet/issues/56) [PR #4453](https://github.com/PHPOffice/PhpSpreadsheet/pull/4453) - More Precision for Float to String Casts. [Issue #3899](https://github.com/PHPOffice/PhpSpreadsheet/issues/3899) [PR #4479](https://github.com/PHPOffice/PhpSpreadsheet/pull/4479) - Hyperlink Styles. [Issue #1632](https://github.com/PHPOffice/PhpSpreadsheet/issues/1632) [PR #4478](https://github.com/PHPOffice/PhpSpreadsheet/pull/4478) - ODS Handling of Ceiling and Floor. [Issue #477](https://github.com/PHPOffice/PhpSpreadsheet/issues/407) [PR #4466](https://github.com/PHPOffice/PhpSpreadsheet/pull/4466) - Xlsx Reader Do Not Process Printer Settings for Dataonly. [Issue #4477](https://github.com/PHPOffice/PhpSpreadsheet/issues/4477) [PR #4480](https://github.com/PHPOffice/PhpSpreadsheet/pull/4480) ## 2025-04-16 - 4.2.0 ### Added - Add ability to add custom functions to Calculation. [PR #4390](https://github.com/PHPOffice/PhpSpreadsheet/pull/4390) - Add FormulaRange to IgnoredErrors. [PR #4393](https://github.com/PHPOffice/PhpSpreadsheet/pull/4393) - TextGrid improvements. [PR #4418](https://github.com/PHPOffice/PhpSpreadsheet/pull/4418) - Permit read to class which extends Spreadsheet. [Discussion #4402](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4402) [PR #4404](https://github.com/PHPOffice/PhpSpreadsheet/pull/4404) - Conditional and table formatting support for html writer [PR #4412](https://github.com/PHPOffice/PhpSpreadsheet/pull/4412) ### Changed - Phpstan Version 2. [PR #4384](https://github.com/PHPOffice/PhpSpreadsheet/pull/4384) - Start migration to Phpstan level 9. [PR #4396](https://github.com/PHPOffice/PhpSpreadsheet/pull/4396) - Calculation locale logic moved to separate class. [PR #4398](https://github.com/PHPOffice/PhpSpreadsheet/pull/4398) - TREND_POLYNOMIAL_* and TREND_BEST_FIT do not work, and are changed to throw Exceptions if attempted. (TREND_BEST_FIT_NO_POLY works.) An attempt to use an unknown trend type will now also throw an exception. [Issue #4400](https://github.com/PHPOffice/PhpSpreadsheet/issues/4400) [PR #4339](https://github.com/PHPOffice/PhpSpreadsheet/pull/4339) - Month parameter of DATE function will now return VALUE if an ordinal string (e.g. '3rd') is used, but will accept bool or null. [PR #4420](https://github.com/PHPOffice/PhpSpreadsheet/pull/4420) ### Fixed - Ignore fractional part of Drawing Shadow Alpha. [Issue #4415](https://github.com/PHPOffice/PhpSpreadsheet/issues/4415) [PR #4417](https://github.com/PHPOffice/PhpSpreadsheet/pull/4417) - BIN2DEC, OCT2DEC, and HEX2DEC return numbers rather than strings. [Issue #4383](https://github.com/PHPOffice/PhpSpreadsheet/issues/4383) [PR #4389](https://github.com/PHPOffice/PhpSpreadsheet/pull/4389) - Fix TREND_BEST_FIT_NO_POLY. [Issue #4400](https://github.com/PHPOffice/PhpSpreadsheet/issues/4400) [PR #4339](https://github.com/PHPOffice/PhpSpreadsheet/pull/4339) - Ods Reader No DataType for Null Value. [Issue #4435](https://github.com/PHPOffice/PhpSpreadsheet/issues/4435) [PR #4436](https://github.com/PHPOffice/PhpSpreadsheet/pull/4436) - Column widths not preserved when using read filter. [Issue #4416](https://github.com/PHPOffice/PhpSpreadsheet/issues/4416) [PR #4423](https://github.com/PHPOffice/PhpSpreadsheet/pull/4423) - Fix typo in Style exportArray quotePrefix. [Issue #4422](https://github.com/PHPOffice/PhpSpreadsheet/issues/4422) [PR #4424](https://github.com/PHPOffice/PhpSpreadsheet/pull/4424) - Tweak Spreadsheet clone. [PR #4419](https://github.com/PHPOffice/PhpSpreadsheet/pull/4419) - Better handling of Chart DisplayBlanksAs. [Issue #4411](https://github.com/PHPOffice/PhpSpreadsheet/issues/4411) [PR #4414](https://github.com/PHPOffice/PhpSpreadsheet/pull/4414) ## 2025-03-02 - 4.1.0 ### Added - Support Justify Last Line. [Issue #4374](https://github.com/PHPOffice/PhpSpreadsheet/issues/4374) [PR #4373](https://github.com/PHPOffice/PhpSpreadsheet/pull/4373) - Allow Spreadsheet clone. [PR #4370](https://github.com/PHPOffice/PhpSpreadsheet/pull/4370) ### Changed - ListWorksheetInfo will now return sheetState (visible, hidden, veryHidden). [Issue #4345](https://github.com/PHPOffice/PhpSpreadsheet/issues/4345) [PR #4366](https://github.com/PHPOffice/PhpSpreadsheet/pull/4366) - Start migration to Phpstan 2. [PR #4359](https://github.com/PHPOffice/PhpSpreadsheet/pull/4359) - IOFactory identify can return, and createReader and CreateWriter can accept, a class name rather than a file type. [Issue #4357](https://github.com/PHPOffice/PhpSpreadsheet/issues/4357) [PR #4361](https://github.com/PHPOffice/PhpSpreadsheet/pull/4361) ### Fixed - Refactor Helper/Html. [PR #4359](https://github.com/PHPOffice/PhpSpreadsheet/pull/4359) - Handle #REF! as Argument to AVERAGEIF/COUNTIF/SUMIF. [Issue #4381](https://github.com/PHPOffice/PhpSpreadsheet/issues/4381) [PR #4382](https://github.com/PHPOffice/PhpSpreadsheet/pull/4382) - Ignore ignoredErrors when not applicable. [Issue #4375](https://github.com/PHPOffice/PhpSpreadsheet/issues/4375) [PR #4377](https://github.com/PHPOffice/PhpSpreadsheet/pull/4377) - Better handling of defined names on sheets whose titles include apostrophes. [Issue #4356](https://github.com/PHPOffice/PhpSpreadsheet/issues/4356) [Issue #4362](https://github.com/PHPOffice/PhpSpreadsheet/issues/4362) [Issue #4376](https://github.com/PHPOffice/PhpSpreadsheet/issues/4376) [PR #4360](https://github.com/PHPOffice/PhpSpreadsheet/pull/4360) - Partial solution for removing rows or columns that include edge ranges. [Issue #1449](https://github.com/PHPOffice/PhpSpreadsheet/issues/1449) [PR #3528](https://github.com/PHPOffice/PhpSpreadsheet/pull/3528) - Prefer mb_str_split to str_split. [PR #3341](https://github.com/PHPOffice/PhpSpreadsheet/pull/3341) ## 2025-02-08 - 4.0.0 ### BREAKING CHANGES - Data Validations will be stored by worksheet, not cell. Index can be one or more cells or cell ranges. [Issue #797](https://github.com/PHPOffice/PhpSpreadsheet/issues/797) [Issue #4091](https://github.com/PHPOffice/PhpSpreadsheet/issues/4091) [Issue #4206](https://github.com/PHPOffice/PhpSpreadsheet/issues/4206) [PR #4240](https://github.com/PHPOffice/PhpSpreadsheet/pull/4240) - Conditional Formatting adds Priority property and handles overlapping ranges better. [Issue #4312](https://github.com/PHPOffice/PhpSpreadsheet/issues/4312) [Issue #4318](https://github.com/PHPOffice/PhpSpreadsheet/issues/4318) [PR #4314](https://github.com/PHPOffice/PhpSpreadsheet/pull/4314) - Csv Reader will no longer auto-detect Mac line endings by default. Prior behavior can be explicitly enabled via `setTestAutoDetect(true)`, and it will not be possible at all with Php9+. [Issue #4092](https://github.com/PHPOffice/PhpSpreadsheet/issues/4092) [PR #4340](https://github.com/PHPOffice/PhpSpreadsheet/pull/4340) - Html Writer will now use "better boolean" logic. Booleans will now be output by default as TRUE/FALSE rather than 1/null-string. Prior behavior can be explicitly enabled via `setBetterBoolean(false)`. [PR #4340](https://github.com/PHPOffice/PhpSpreadsheet/pull/4340) - Xlsx Writer will now use false as the default for `forceFullCalc`. This affects writes with `preCalculateFormulas` set to false. Prior behavior can be explicitly enabled via `setForceFullCalc(null)`.[PR #4340](https://github.com/PHPOffice/PhpSpreadsheet/pull/4340) - Deletion of items deprecated in Release 3. See "removed" below. ### Added - Pdf Charts and Drawings. [Discussion #4129](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4129) [Discussion #4168](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4168) [PR #4327](https://github.com/PHPOffice/PhpSpreadsheet/pull/4327) - Allow spreadsheet serialization. [Discussion #4324](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4324) [Issue #1741](https://github.com/PHPOffice/PhpSpreadsheet/issues/1741) [Issue #1757](https://github.com/PHPOffice/PhpSpreadsheet/issues/1757) [PR #4326](https://github.com/PHPOffice/PhpSpreadsheet/pull/4326) ### Removed - Worksheet::getStyles - no replacement. [PR #4330](https://github.com/PHPOffice/PhpSpreadsheet/pull/4330) - The following items were deprecated in release 3 and are now removed. - Drawing::setIsUrl - no replacement. - Settings::setLibXmlLoaderOptions() and Settings::getLibXmlLoaderOptions() - no replacement. - Worksheet::getHashCode - no replacement. - IReader::SKIP_EMPTY_CELLS - use its alias IGNORE_EMPTY_CELLS instead. - Worksheet::getProtectedCells - use getProtectedCellRanges instead. - Writer/Html::isMpdf property - use instanceof Mpdf instead. ### Changed - Nothing yet. ### Moved - Nothing yet. ### Deprecated - Nothing yet. ### Fixed - Xls writer Parser Mishandling True/False Argument. [Issue #4331](https://github.com/PHPOffice/PhpSpreadsheet/issues/4331) [PR #4333](https://github.com/PHPOffice/PhpSpreadsheet/pull/4333) - Xls writer Parser Parse By Character Not Byte. [PR #4344](https://github.com/PHPOffice/PhpSpreadsheet/pull/4344) - Minor changes to dynamic array calculations exposed by using explicit array return types in some tests. [PR #4328](https://github.com/PHPOffice/PhpSpreadsheet/pull/4328) ## 2025-01-26 - 3.9.0 ### Added - Methods to get style for row or column. [PR #4317](https://github.com/PHPOffice/PhpSpreadsheet/pull/4317) - Method for duplicating worksheet in spreadsheet. [PR #4315](https://github.com/PHPOffice/PhpSpreadsheet/pull/4315) ### Fixed - Security patch for control characters in protocol. - Ods Reader Sheet Names with Period. [Issue #4311](https://github.com/PHPOffice/PhpSpreadsheet/issues/4311) [PR #4313](https://github.com/PHPOffice/PhpSpreadsheet/pull/4313) - Mpdf and Tcpdf Hidden Columns and Merged Cells. [Issue #4319](https://github.com/PHPOffice/PhpSpreadsheet/issues/4319) [PR #4320](https://github.com/PHPOffice/PhpSpreadsheet/pull/4320) - Html Writer Allow mailto. [Issue #4316](https://github.com/PHPOffice/PhpSpreadsheet/issues/4316) [PR #4322](https://github.com/PHPOffice/PhpSpreadsheet/pull/4322) - Use composer/pcre rather than preg_* in Writer. [PR #4323](https://github.com/PHPOffice/PhpSpreadsheet/pull/4323) ## 2025-01-11 - 3.8.0 ### Added - CHOOSECOLS, CHOOSEROWS, DROP, TAKE, and EXPAND. [PR #4286](https://github.com/PHPOffice/PhpSpreadsheet/pull/4286) ### Fixed - Security patch for Html navigation. - Xlsx Reader Shared Formula with Boolean Result. Partial solution for [Issue #4280](https://github.com/PHPOffice/PhpSpreadsheet/issues/4280) [PR #4281](https://github.com/PHPOffice/PhpSpreadsheet/pull/4281) - Retitling cloned Worksheets. [Issue #641](https://github.com/PHPOffice/PhpSpreadsheet/issues/641) [PR #4302](https://github.com/PHPOffice/PhpSpreadsheet/pull/4302) - Extremely limited support for GROUPBY function. Partial response to [Issue #4282](https://github.com/PHPOffice/PhpSpreadsheet/issues/4282) [PR #4283](https://github.com/PHPOffice/PhpSpreadsheet/pull/4283) ## 2024-12-26 - 3.7.0 ### Deprecated - Drawing::setIsUrl is unneeded. The property is set when setPath determines whether path is a url. ### Fixed - Security patches for Samples. - Security patches for Html Writer. - Avoid unexpected charset in currency symbol. [PR #4279](https://github.com/PHPOffice/PhpSpreadsheet/pull/4279) - Add forceFullCalc option to Xlsx Writer. [Issue #4269](https://github.com/PHPOffice/PhpSpreadsheet/issues/4269) [PR #4271](https://github.com/PHPOffice/PhpSpreadsheet/pull/4271) - More context options may be needed for http(s) image. [Php issue 17121](https://github.com/php/php-src/issues/17121) [PR #4276](https://github.com/PHPOffice/PhpSpreadsheet/pull/4276) - Coverage-related tweaks to Xls Reader. [PR #4277](https://github.com/PHPOffice/PhpSpreadsheet/pull/4277) - Several fixed to ODS Writer. [Issue #4261](https://github.com/PHPOffice/PhpSpreadsheet/issues/4261) [PR #4263](https://github.com/PHPOffice/PhpSpreadsheet/pull/4263) [PR #4264](https://github.com/PHPOffice/PhpSpreadsheet/pull/4264) [PR #4266](https://github.com/PHPOffice/PhpSpreadsheet/pull/4266) ## 2024-12-08 - 3.6.0 ### Added - Nothing yet. ### Changed - Nothing yet. ### Moved - Nothing yet. ### Deprecated - Nothing yet. ### Fixed - Html Reader/Writer Better Handling of Booleans. [PR #4257](https://github.com/PHPOffice/PhpSpreadsheet/pull/4257) - Fill Patterns/Colors When Xml Attributes are Missing. [Issue #4248](https://github.com/PHPOffice/PhpSpreadsheet/issues/4248) [PR #4250](https://github.com/PHPOffice/PhpSpreadsheet/pull/4250) - Remove Unneccesary files from Composer Package. [PR #4262](https://github.com/PHPOffice/PhpSpreadsheet/pull/4262) - Swapped row and column indexes in ReferenceHelper. [Issue #4246](https://github.com/PHPOffice/PhpSpreadsheet/issues/4246) [PR #4247](https://github.com/PHPOffice/PhpSpreadsheet/pull/4247) - Fix minor break handling drawings. [Issue #4241](https://github.com/PHPOffice/PhpSpreadsheet/issues/4241) [PR #4244](https://github.com/PHPOffice/PhpSpreadsheet/pull/4244) - Ignore cell formatting when the format is a single @. [Issue #4242](https://github.com/PHPOffice/PhpSpreadsheet/issues/4242) [PR #4243](https://github.com/PHPOffice/PhpSpreadsheet/pull/4243) - Upgrade Dompdf to Php-8.4 compatible version [PR #4267](https://github.com/PHPOffice/PhpSpreadsheet/pull/4267) ## 2024-11-22 - 3.5.0 ### Added - Nothing yet. ### Changed - Settings::libXmlLoaderOptions is ignored. [PR #4233](https://github.com/PHPOffice/PhpSpreadsheet/pull/4233) ### Moved - Nothing yet. ### Deprecated - Settings::setLibXmlLoaderOptions() and Settings::getLibXmlLoaderOptions() are no longer needed - no replacement. - Worksheet::getHashCode is no longer needed. ### Fixed - Add support for `` tag when converting HTML to RichText. [Issue #4223](https://github.com/PHPOffice/PhpSpreadsheet/issues/4223) [PR #4224](https://github.com/PHPOffice/PhpSpreadsheet/pull/4224) - Change hash code for worksheet. [Issue #4192](https://github.com/PHPOffice/PhpSpreadsheet/issues/4192) [PR #4207](https://github.com/PHPOffice/PhpSpreadsheet/pull/4207) ## 2024-11-10 - 3.4.0 ### Security Fix - Several security patches. ### Added - Add Dynamic valueBinder Property to Spreadsheet and Readers. [Issue #1395](https://github.com/PHPOffice/PhpSpreadsheet/issues/1395) [PR #4185](https://github.com/PHPOffice/PhpSpreadsheet/pull/4185) - Allow Omitting Chart Border. [Issue #562](https://github.com/PHPOffice/PhpSpreadsheet/issues/562) [PR #4188](https://github.com/PHPOffice/PhpSpreadsheet/pull/4188) - Method to Test Whether Csv Will Be Affected by Php9. [PR #4189](https://github.com/PHPOffice/PhpSpreadsheet/pull/4189) ### Changed - Refactor Xls Reader. [PR #4118](https://github.com/PHPOffice/PhpSpreadsheet/pull/4118) ### Deprecated - IReader::SKIP_EMPTY_CELLS - use its alias IGNORE_EMPTY_CELLS instead. - Worksheet::getProtectedCells was deprecated in release 2, but was not properly documented, and not removed in release 3. Use getProtectedCellRanges instead. - Writer/Html::isMpdf property was deprecated in release 2, but was not properly documented, and not removed in release 3. Use instanceof Mpdf instead. ### Moved - Nothing yet. ### Fixed - Xls Writer Condtional Rules Applied to Whole Rows or Columns. [Issue #3185](https://github.com/PHPOffice/PhpSpreadsheet/issues/3185) [PR #4152](https://github.com/PHPOffice/PhpSpreadsheet/pull/4152) - Xlsx Writer Duplicate ContentTypes Entry for Background Image. [Issue #4179](https://github.com/PHPOffice/PhpSpreadsheet/issues/4179) [PR #4180](https://github.com/PHPOffice/PhpSpreadsheet/pull/4180) - Check strictNullComparison outside of loops. [PR #3347](https://github.com/PHPOffice/PhpSpreadsheet/pull/3347) - SUMIFS Does Not Require xlfn. [Issue #4182](https://github.com/PHPOffice/PhpSpreadsheet/issues/4182) [PR #4186](https://github.com/PHPOffice/PhpSpreadsheet/pull/4186) - Image Transparency/Opacity with Html Reader Changes. [Discussion #4117](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4117) [PR #4142](https://github.com/PHPOffice/PhpSpreadsheet/pull/4142) - Option to Write Hyperlink Rather Than Label to Csv. [Issue #1412](https://github.com/PHPOffice/PhpSpreadsheet/issues/1412) [PR #4151](https://github.com/PHPOffice/PhpSpreadsheet/pull/4151) - Invalid Html Due to Cached Filesize. [Issue #1107](https://github.com/PHPOffice/PhpSpreadsheet/issues/1107) [PR #4184](https://github.com/PHPOffice/PhpSpreadsheet/pull/4184) - Excel 2003 Allows Html Entities. [Issue #2157](https://github.com/PHPOffice/PhpSpreadsheet/issues/2157) [PR #4187](https://github.com/PHPOffice/PhpSpreadsheet/pull/4187) - Changes to ROUNDDOWN/ROUNDUP/TRUNC. [Issue #4213](https://github.com/PHPOffice/PhpSpreadsheet/issues/4213) [PR #4214](https://github.com/PHPOffice/PhpSpreadsheet/pull/4214) - Writer Xlsx ignoredErrors Before Drawings. [Issue #4200](https://github.com/PHPOffice/PhpSpreadsheet/issues/4200) [Issue #4145](https://github.com/PHPOffice/PhpSpreadsheet/issues/4145) [PR #4212](https://github.com/PHPOffice/PhpSpreadsheet/pull/4212) - Allow ANCHORARRAY as Data Validation list. [Issue #4197](https://github.com/PHPOffice/PhpSpreadsheet/issues/4197) [PR #4203](https://github.com/PHPOffice/PhpSpreadsheet/pull/4203) ## 2024-09-29 - 3.3.0 (no 3.0.\*, 3.1.\*, 3.2.\*) ### Dynamic Arrays - Support for Excel dynamic arrays is added. It is an opt-in feature, so our hope is that there will be no BC breaks, but it is a very large change. Full support is added for Xlsx. It is emulated as Ctrl-Shift-Enter arrays for Ods read and write and Excel2003 and Gnumeric read. Html/Pdf and Csv writers will populate cells on output if they are the result of array formulas. No support is added for Xls or Slk. ### Added - Excel Dynamic Arrays. [Issue #3901](https://github.com/PHPOffice/PhpSpreadsheet/issues/3901) [Issue #3659](https://github.com/PHPOffice/PhpSpreadsheet/issues/3659) [Issue #1834](https://github.com/PHPOffice/PhpSpreadsheet/issues/1834) [PR #3962](https://github.com/PHPOffice/PhpSpreadsheet/pull/3962) - String Value Binder Allow Setting "Ignore Number Stored as Text". [PR #4141](https://github.com/PHPOffice/PhpSpreadsheet/pull/4141) ### Changed - Xlsx Reader default datatype when none is specified in Xml is changed from string to numeric, which is how Excel treats it. There is expected to be little impact because DefaultValueBinder and AdvancedValueBinder correct mis-identification as string, and StringValueBinder usually expects string. [PR #4139](https://github.com/PHPOffice/PhpSpreadsheet/pull/4139) - Currency and Accounting Wizards are changed to act like Excel, and a new CurrencyBase Wizard is added for for non-Excel formats. [Issue #4125](https://github.com/PHPOffice/PhpSpreadsheet/issues/4125) [Issue #4124](https://github.com/PHPOffice/PhpSpreadsheet/issues/4124) [PR #4127](https://github.com/PHPOffice/PhpSpreadsheet/pull/4127) - Images will not be added to spreadsheet if they cannot be validated as images. ### Deprecated - Nothing yet. ### Removed - The following items were deprecated in release 2 and are now removed. - Writer\Xls\Style\ColorMap (no longer needed). - Reader\Xml::trySimpleXMLLoadString (should not have been public, no public replacement). - Calculation\Calculation::_translateFormulaToLocale (use method name translateFormulaToLocale without leading underscore). - Calculation\Calculation::_translateFormulaToEnglish (use method name translateFormulaToEnglish without leading underscore). ### Moved - Nothing yet. ### Fixed - Several security patches. - Xls Reader Some Ranges Not Handled Properly. [Issue #1570](https://github.com/PHPOffice/PhpSpreadsheet/issues/1570) [PR #4140](https://github.com/PHPOffice/PhpSpreadsheet/pull/4140) - Better Handling of legacyDrawing Xml. [Issue #4105](https://github.com/PHPOffice/PhpSpreadsheet/issues/4105) [PR #4122](https://github.com/PHPOffice/PhpSpreadsheet/pull/4122) - Improve Xlsx Reader Speed. [Issue #3917](https://github.com/PHPOffice/PhpSpreadsheet/issues/3917) [PR #4153](https://github.com/PHPOffice/PhpSpreadsheet/pull/4153) ## 2024-08-07 - 2.2.2 ### Added - Nothing yet. ### Changed - Nothing yet. ### Deprecated - Nothing yet. ### Moved - Nothing yet. ### Fixed - Html Reader Preserve Unicode Whitespace. [Issue #1284](https://github.com/PHPOffice/PhpSpreadsheet/issues/1284) [PR #4106](https://github.com/PHPOffice/PhpSpreadsheet/pull/4106) - RATE Function Floating Point Number of Periods. [PR #4107](https://github.com/PHPOffice/PhpSpreadsheet/pull/4107) - Parameter Name Change Xlsx Writer Workbook. [Issue #4108](https://github.com/PHPOffice/PhpSpreadsheet/issues/4108) [PR #4111](https://github.com/PHPOffice/PhpSpreadsheet/pull/4111) - New Algorithm for TRUNC, ROUNDUP, ROUNDDOWN. [Issue #4113](https://github.com/PHPOffice/PhpSpreadsheet/issues/4113) [PR #4115](https://github.com/PHPOffice/PhpSpreadsheet/pull/4115) - Worksheet applyStylesFromArray Retain Active Cell (Excel 16 was having a problem with some files). [Issue #4128](https://github.com/PHPOffice/PhpSpreadsheet/issues/4128) [PR #4132](https://github.com/PHPOffice/PhpSpreadsheet/pull/4132) ## 2024-07-29 - 2.2.1 ### Security Fix - Prevent XXE when loading files [PR #4119](https://github.com/PHPOffice/PhpSpreadsheet/pull/4119) ### Fixed - Add Sheet may leave Active Sheet uninitialized. [Issue #4112](https://github.com/PHPOffice/PhpSpreadsheet/issues/4112) [PR #4114](https://github.com/PHPOffice/PhpSpreadsheet/pull/4114) - Reference to Defined Name Specifying Worksheet. [Issue #206](https://github.com/PHPOffice/PhpSpreadsheet/issues/296) [PR #4096](https://github.com/PHPOffice/PhpSpreadsheet/pull/4096) - Xls Reader Print/Show Gridlines. [Issue #912](https://github.com/PHPOffice/PhpSpreadsheet/issues/912) [PR #4098](https://github.com/PHPOffice/PhpSpreadsheet/pull/4098) - ODS Reader Allow Omission of Page Settings Tags. [Issue #4099](https://github.com/PHPOffice/PhpSpreadsheet/issues/4099) [PR #4101](https://github.com/PHPOffice/PhpSpreadsheet/pull/4101) ## 2024-07-24 - 2.2.0 ### Added - Xlsx Reader Optionally Ignore Rows With No Cells. [Issue #3982](https://github.com/PHPOffice/PhpSpreadsheet/issues/3982) [PR #4035](https://github.com/PHPOffice/PhpSpreadsheet/pull/4035) - Means to change style without affecting current cell/sheet. [PR #4073](https://github.com/PHPOffice/PhpSpreadsheet/pull/4073) - Option for CSV output file to have varying numbers of columns for each row. [Issue #1415](https://github.com/PHPOffice/PhpSpreadsheet/issues/1415) [PR #4076](https://github.com/PHPOffice/PhpSpreadsheet/pull/4076) ### Changed - On read, Xlsx Reader had been breaking up union ranges into separate individual ranges. It will now try to preserve range as it was read in. [PR #4042](https://github.com/PHPOffice/PhpSpreadsheet/pull/4042) - Xlsx/Xls spreadsheet calculation and formatting of dates will use base date of spreadsheet even when spreadsheets with different base dates are simultaneously open. [Issue #1036](https://github.com/PHPOffice/PhpSpreadsheet/issues/1036) [Issue #1635](https://github.com/PHPOffice/PhpSpreadsheet/issues/1635) [PR #4071](https://github.com/PHPOffice/PhpSpreadsheet/pull/4071) ### Deprecated - Writer\Xls\Style\ColorMap is no longer needed. ### Moved - Nothing ### Fixed - Incorrect Reader CSV with BOM. [Issue #4028](https://github.com/PHPOffice/PhpSpreadsheet/issues/4028) [PR #4029](https://github.com/PHPOffice/PhpSpreadsheet/pull/4029) - POWER Null/Bool Args. [PR #4031](https://github.com/PHPOffice/PhpSpreadsheet/pull/4031) - Do Not Output Alignment and Protection for Conditional Format. [Issue #4025](https://github.com/PHPOffice/PhpSpreadsheet/issues/4025) [PR #4027](https://github.com/PHPOffice/PhpSpreadsheet/pull/4027) - Conditional Color Scale Improvements. [Issue #4049](https://github.com/PHPOffice/PhpSpreadsheet/issues/4049) [PR #4050](https://github.com/PHPOffice/PhpSpreadsheet/pull/4050) - Mpdf and Tcpdf Borders on Merged Cells. [Issue #3557](https://github.com/PHPOffice/PhpSpreadsheet/issues/3557) [PR #4047](https://github.com/PHPOffice/PhpSpreadsheet/pull/4047) - Xls Conditional Format Improvements. [PR #4030](https://github.com/PHPOffice/PhpSpreadsheet/pull/4030) [PR #4033](https://github.com/PHPOffice/PhpSpreadsheet/pull/4033) - Conditional Range Unions and Intersections [Issue #4039](https://github.com/PHPOffice/PhpSpreadsheet/issues/4039) [PR #4042](https://github.com/PHPOffice/PhpSpreadsheet/pull/4042) - Ods comments with newlines. [Issue #4081](https://github.com/PHPOffice/PhpSpreadsheet/issues/4081) [PR #4086](https://github.com/PHPOffice/PhpSpreadsheet/pull/4086) - Propagate errors in Text functions. [Issue #2581](https://github.com/PHPOffice/PhpSpreadsheet/issues/2581) [PR #4080](https://github.com/PHPOffice/PhpSpreadsheet/pull/4080) - Csv Reader allow use of html mimetype. [Issue #4036](https://github.com/PHPOffice/PhpSpreadsheet/issues/4036) [PR #4040](https://github.com/PHPOffice/PhpSpreadsheet/pull/4040) - Problem rendering line chart with missing plot label. [PR #4074](https://github.com/PHPOffice/PhpSpreadsheet/pull/4074) - More RTL in Xlsx/Html Comments [Issue #4004](https://github.com/PHPOffice/PhpSpreadsheet/issues/4004) [PR #4065](https://github.com/PHPOffice/PhpSpreadsheet/pull/4065) - Empty String in sharedStrings. [Issue #4063](https://github.com/PHPOffice/PhpSpreadsheet/issues/4063) [PR #4064](https://github.com/PHPOffice/PhpSpreadsheet/pull/4064) - Xlsx Writer RichText and TYPE_STRING. [Issue #476](https://github.com/PHPOffice/PhpSpreadsheet/issues/476) [PR #4094](https://github.com/PHPOffice/PhpSpreadsheet/pull/4094) - Ods boolean data. [Issue #460](https://github.com/PHPOffice/PhpSpreadsheet/issues/460) [PR #4093](https://github.com/PHPOffice/PhpSpreadsheet/pull/4093) - Html Writer Minor Fixes. [PR #4089](https://github.com/PHPOffice/PhpSpreadsheet/pull/4089) - Changes to INDEX function. [Issue #64](https://github.com/PHPOffice/PhpSpreadsheet/issues/64) [PR #4088](https://github.com/PHPOffice/PhpSpreadsheet/pull/4088) - Ods Reader and Whitespace Text Nodes. [Issue #804](https://github.com/PHPOffice/PhpSpreadsheet/issues/804) [PR #4087](https://github.com/PHPOffice/PhpSpreadsheet/pull/4087) - Ods Xml Reader and Whitespace Text Nodes. [Issue #804](https://github.com/PHPOffice/PhpSpreadsheet/issues/804) [PR #4087](https://github.com/PHPOffice/PhpSpreadsheet/pull/4087) - Treat invalid formulas as strings. [Issue #1310](https://github.com/PHPOffice/PhpSpreadsheet/issues/1310) [PR #4073](https://github.com/PHPOffice/PhpSpreadsheet/pull/4073) ## 2024-05-11 - 2.1.0 ### MINOR BREAKING CHANGE - Writing of cell comments to Html will now sanitize all Html tags within the comment, so the tags will be rendered as plaintext and have no other effects when rendered. Styling can be achieved by using the Font property of of the TextRuns which make up the comment, as is already the cases for Xlsx. [PR #3957](https://github.com/PHPOffice/PhpSpreadsheet/pull/3957) ### Added - Default Style Alignment Property (workaround for bug in non-Excel spreadsheet apps) [Issue #3918](https://github.com/PHPOffice/PhpSpreadsheet/issues/3918) [PR #3924](https://github.com/PHPOffice/PhpSpreadsheet/pull/3924) - Additional Support for Date/Time Styles [PR #3939](https://github.com/PHPOffice/PhpSpreadsheet/pull/3939) ### Changed - Nothing ### Deprecated - Reader/Xml trySimpleXMLLoadString should not have had public visibility, and will be removed. ### Removed - Nothing ### Fixed - IF Empty Arguments. [Issue #3875](https://github.com/PHPOffice/PhpSpreadsheet/issues/3875) [Issue #2146](https://github.com/PHPOffice/PhpSpreadsheet/issues/2146) [PR #3879](https://github.com/PHPOffice/PhpSpreadsheet/pull/3879) - Changes to floating point in Php8.4. [Issue #3896](https://github.com/PHPOffice/PhpSpreadsheet/issues/3896) [PR #3897](https://github.com/PHPOffice/PhpSpreadsheet/pull/3897) - Handling User-supplied Decimal and Thousands Separators. [Issue #3900](https://github.com/PHPOffice/PhpSpreadsheet/issues/3900) [PR #3903](https://github.com/PHPOffice/PhpSpreadsheet/pull/3903) - Improve Performance of CSV Writer. [Issue #3904](https://github.com/PHPOffice/PhpSpreadsheet/issues/3904) [PR #3906](https://github.com/PHPOffice/PhpSpreadsheet/pull/3906) - Fix issue with prepending zero in percentage [Issue #3920](https://github.com/PHPOffice/PhpSpreadsheet/issues/3920) [PR #3921](https://github.com/PHPOffice/PhpSpreadsheet/pull/3921) - Incorrect SUMPRODUCT Calculation [Issue #3909](https://github.com/PHPOffice/PhpSpreadsheet/issues/3909) [PR #3916](https://github.com/PHPOffice/PhpSpreadsheet/pull/3916) - Formula Misidentifying Text as Cell After Insertion/Deletion [Issue #3907](https://github.com/PHPOffice/PhpSpreadsheet/issues/3907) [PR #3915](https://github.com/PHPOffice/PhpSpreadsheet/pull/3915) - Unexpected Absolute Address in Xlsx Rels [Issue #3730](https://github.com/PHPOffice/PhpSpreadsheet/issues/3730) [PR #3923](https://github.com/PHPOffice/PhpSpreadsheet/pull/3923) - Unallocated Cells Affected by Column/Row Insert/Delete [Issue #3933](https://github.com/PHPOffice/PhpSpreadsheet/issues/3933) [PR #3940](https://github.com/PHPOffice/PhpSpreadsheet/pull/3940) - Invalid Builtin Defined Name in Xls Reader [Issue #3935](https://github.com/PHPOffice/PhpSpreadsheet/issues/3935) [PR #3942](https://github.com/PHPOffice/PhpSpreadsheet/pull/3942) - Hidden Rows and Columns Tcpdf/Mpdf [PR #3945](https://github.com/PHPOffice/PhpSpreadsheet/pull/3945) - RTL Text Alignment in Xlsx Comments [Issue #4004](https://github.com/PHPOffice/PhpSpreadsheet/issues/4004) [PR #4006](https://github.com/PHPOffice/PhpSpreadsheet/pull/4006) - Protect Sheet But Allow Sort [Issue #3951](https://github.com/PHPOffice/PhpSpreadsheet/issues/3951) [PR #3956](https://github.com/PHPOffice/PhpSpreadsheet/pull/3956) - Default Value for Conditional::$text [PR #3946](https://github.com/PHPOffice/PhpSpreadsheet/pull/3946) - Table Filter Buttons [Issue #3988](https://github.com/PHPOffice/PhpSpreadsheet/issues/3988) [PR #3992](https://github.com/PHPOffice/PhpSpreadsheet/pull/3992) - Improvements to Xml Reader [Issue #3999](https://github.com/PHPOffice/PhpSpreadsheet/issues/3999) [Issue #4000](https://github.com/PHPOffice/PhpSpreadsheet/issues/4000) [Issue #4001](https://github.com/PHPOffice/PhpSpreadsheet/issues/4001) [Issue #4002](https://github.com/PHPOffice/PhpSpreadsheet/issues/4002) [PR #4003](https://github.com/PHPOffice/PhpSpreadsheet/pull/4003) [PR #4007](https://github.com/PHPOffice/PhpSpreadsheet/pull/4007) - Html Reader non-UTF8 [Issue #3995](https://github.com/PHPOffice/PhpSpreadsheet/issues/3995) [Issue #866](https://github.com/PHPOffice/PhpSpreadsheet/issues/866) [Issue #1681](https://github.com/PHPOffice/PhpSpreadsheet/issues/1681) [PR #4019](https://github.com/PHPOffice/PhpSpreadsheet/pull/4019) ## 2.0.0 - 2024-01-04 ### BREAKING CHANGE - Typing was strengthened by leveraging native typing. This should not change any behavior. However, if you implement any interfaces or inherit from any classes, you will need to adapt your typing accordingly. If you use static analysis tools such as PHPStan or Psalm, new errors might be found. If you find actual bugs because of the new typing, please open a PR that fixes it with a **detailed** explanation of the reason. We'll try to merge and release typing-related fixes quickly in the coming days. [PR #3718](https://github.com/PHPOffice/PhpSpreadsheet/pull/3718) - All deprecated things have been removed, for details, see [816b91d0b4](https://github.com/PHPOffice/PhpSpreadsheet/commit/816b91d0b4a0c7285a9e3fc88c58f7730d922044) ### Added - Split screens (Xlsx and Xml only, not 100% complete). [Issue #3601](https://github.com/PHPOffice/PhpSpreadsheet/issues/3601) [PR #3622](https://github.com/PHPOffice/PhpSpreadsheet/pull/3622) - Permit Meta Viewport in Html. [Issue #3565](https://github.com/PHPOffice/PhpSpreadsheet/issues/3565) [PR #3623](https://github.com/PHPOffice/PhpSpreadsheet/pull/3623) - Hyperlink support for Ods. [Issue #3660](https://github.com/PHPOffice/PhpSpreadsheet/issues/3660) [PR #3669](https://github.com/PHPOffice/PhpSpreadsheet/pull/3669) - ListWorksheetInfo/Names for Html/Csv/Slk. [Issue #3706](https://github.com/PHPOffice/PhpSpreadsheet/issues/3706) [PR #3709](https://github.com/PHPOffice/PhpSpreadsheet/pull/3709) - Methods to determine if cell is actually locked, or hidden on formula bar. [PR #3722](https://github.com/PHPOffice/PhpSpreadsheet/pull/3722) - Add iterateOnlyExistingCells to Constructors. [Issue #3721](https://github.com/PHPOffice/PhpSpreadsheet/issues/3721) [PR #3727](https://github.com/PHPOffice/PhpSpreadsheet/pull/3727) - Support for Conditional Formatting Color Scale. [PR #3738](https://github.com/PHPOffice/PhpSpreadsheet/pull/3738) - Support Additional Tags in Helper/Html. [Issue #3751](https://github.com/PHPOffice/PhpSpreadsheet/issues/3751) [PR #3752](https://github.com/PHPOffice/PhpSpreadsheet/pull/3752) - Writer ODS : Write Border Style for cells [Issue #3690](https://github.com/PHPOffice/PhpSpreadsheet/issues/3690) [PR #3693](https://github.com/PHPOffice/PhpSpreadsheet/pull/3693) - Sheet Background Images [Issue #1649](https://github.com/PHPOffice/PhpSpreadsheet/issues/1649) [PR #3795](https://github.com/PHPOffice/PhpSpreadsheet/pull/3795) - Check if Coordinate is Inside Range [PR #3779](https://github.com/PHPOffice/PhpSpreadsheet/pull/3779) - Flipping Images [Issue #731](https://github.com/PHPOffice/PhpSpreadsheet/issues/731) [PR #3801](https://github.com/PHPOffice/PhpSpreadsheet/pull/3801) - Chart Dynamic Title and Font Properties [Issue #3797](https://github.com/PHPOffice/PhpSpreadsheet/issues/3797) [PR #3800](https://github.com/PHPOffice/PhpSpreadsheet/pull/3800) - Chart Axis Display Units and Logarithmic Scale. [Issue #3833](https://github.com/PHPOffice/PhpSpreadsheet/issues/3833) [PR #3836](https://github.com/PHPOffice/PhpSpreadsheet/pull/3836) - Partial Support of Fill Handles. [Discussion #3847](https://github.com/PHPOffice/PhpSpreadsheet/discussions/3847) [PR #3855](https://github.com/PHPOffice/PhpSpreadsheet/pull/3855) ### Changed - **Drop support for PHP 7.4**, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support [PR #3713](https://github.com/PHPOffice/PhpSpreadsheet/pull/3713) - RLM Added to NumberFormatter Currency. This happens depending on release of ICU which Php is using (it does not yet happen with any official release). PhpSpreadsheet will continue to use the value returned by Php, but a method is added to keep the result unchanged from release to release. [Issue #3571](https://github.com/PHPOffice/PhpSpreadsheet/issues/3571) [PR #3640](https://github.com/PHPOffice/PhpSpreadsheet/pull/3640) - `toFormattedString` will now always return a string. This was introduced with 1.28.0, but was not properly documented at the time. This can affect the results of `toArray`, `namedRangeToArray`, and `rangeToArray`. [PR #3304](https://github.com/PHPOffice/PhpSpreadsheet/pull/3304) - Value of constants FORMAT_CURRENCY_EUR and FORMAT_CURRENCY_USD was changed in 1.28.0, but was not properly documented at the time. [Issue #3577](https://github.com/PHPOffice/PhpSpreadsheet/issues/3577) - Html Writer will attempt to use Chart coordinates to determine image size. [Issue #3783](https://github.com/PHPOffice/PhpSpreadsheet/issues/3783) [PR #3787](https://github.com/PHPOffice/PhpSpreadsheet/pull/3787) ### Deprecated - Functions `_translateFormulaToLocale` and `_translateFormulaEnglish` are replaced by versions without leading underscore. [PR #3828](https://github.com/PHPOffice/PhpSpreadsheet/pull/3828) ### Removed - Nothing ### Fixed - Take advantage of mitoteam/jpgraph Extended mode to enable rendering of more graphs. [PR #3603](https://github.com/PHPOffice/PhpSpreadsheet/pull/3603) - Column widths, especially for ODS. [Issue #3609](https://github.com/PHPOffice/PhpSpreadsheet/issues/3609) [PR #3610](https://github.com/PHPOffice/PhpSpreadsheet/pull/3610) - Avoid NULL in String Function call (partial solution). [Issue #3613](https://github.com/PHPOffice/PhpSpreadsheet/issues/3613) [PR #3617](https://github.com/PHPOffice/PhpSpreadsheet/pull/3617) - Preserve transparency in Memory Drawing. [Issue #3624](https://github.com/PHPOffice/PhpSpreadsheet/issues/3624) [PR #3627](https://github.com/PHPOffice/PhpSpreadsheet/pull/3627) - Customizable padding for Exact Column Width. [Issue #3626](https://github.com/PHPOffice/PhpSpreadsheet/issues/3626) [PR #3628](https://github.com/PHPOffice/PhpSpreadsheet/pull/3628) - Ensure ROW function returns int (problem exposed in unreleased Php). [PR #3641](https://github.com/PHPOffice/PhpSpreadsheet/pull/3641) - Minor changes to Mpdf and Html Writers. [PR #3645](https://github.com/PHPOffice/PhpSpreadsheet/pull/3645) - Xlsx Reader Namespacing for Tables, Autofilters. [Issue #3665](https://github.com/PHPOffice/PhpSpreadsheet/issues/3665) [PR #3668](https://github.com/PHPOffice/PhpSpreadsheet/pull/3668) - Read Code Page for Xls ListWorksheetInfo/Names BIFF5. [Issue #3671](https://github.com/PHPOffice/PhpSpreadsheet/issues/3671) [PR #3672](https://github.com/PHPOffice/PhpSpreadsheet/pull/3672) - Read Data from Table on Different Sheet. [Issue #3635](https://github.com/PHPOffice/PhpSpreadsheet/issues/3635) [PR #3659](https://github.com/PHPOffice/PhpSpreadsheet/pull/3659) - Html Writer Styles Using Inline Css. [Issue #3678](https://github.com/PHPOffice/PhpSpreadsheet/issues/3678) [PR #3680](https://github.com/PHPOffice/PhpSpreadsheet/pull/3680) - Xlsx Read Ignoring Some Comments. [Issue #3654](https://github.com/PHPOffice/PhpSpreadsheet/issues/3654) [PR #3655](https://github.com/PHPOffice/PhpSpreadsheet/pull/3655) - Fractional Seconds in Date/Time Values. [PR #3677](https://github.com/PHPOffice/PhpSpreadsheet/pull/3677) - SetCalculatedValue Avoid Casting String to Numeric. [Issue #3658](https://github.com/PHPOffice/PhpSpreadsheet/issues/3658) [PR #3685](https://github.com/PHPOffice/PhpSpreadsheet/pull/3685) - Several Problems in a Very Complicated Spreadsheet. [Issue #3679](https://github.com/PHPOffice/PhpSpreadsheet/issues/3679) [PR #3681](https://github.com/PHPOffice/PhpSpreadsheet/pull/3681) - Inconsistent String Handling for Sum Functions. [Issue #3652](https://github.com/PHPOffice/PhpSpreadsheet/issues/3652) [PR #3653](https://github.com/PHPOffice/PhpSpreadsheet/pull/3653) - Recomputation of Relative Addresses in Defined Names. [Issue #3661](https://github.com/PHPOffice/PhpSpreadsheet/issues/3661) [PR #3673](https://github.com/PHPOffice/PhpSpreadsheet/pull/3673) - Writer Xls Characters Outside BMP (emojis). [Issue #642](https://github.com/PHPOffice/PhpSpreadsheet/issues/642) [PR #3696](https://github.com/PHPOffice/PhpSpreadsheet/pull/3696) - Xlsx Reader Improve Handling of Row and Column Styles. [Issue #3533](https://github.com/PHPOffice/PhpSpreadsheet/issues/3533) [Issue #3534](https://github.com/PHPOffice/PhpSpreadsheet/issues/3534) [PR #3688](https://github.com/PHPOffice/PhpSpreadsheet/pull/3688) - Avoid Allocating RowDimension Unneccesarily. [PR #3686](https://github.com/PHPOffice/PhpSpreadsheet/pull/3686) - Use Column Style when Row Dimension Exists Without Style. [Issue #3534](https://github.com/PHPOffice/PhpSpreadsheet/issues/3534) [PR #3688](https://github.com/PHPOffice/PhpSpreadsheet/pull/3688) - Inconsistency Between Cell Data and Explicitly Declared Type. [Issue #3711](https://github.com/PHPOffice/PhpSpreadsheet/issues/3711) [PR #3715](https://github.com/PHPOffice/PhpSpreadsheet/pull/3715) - Unexpected Namespacing in rels File. [Issue #3720](https://github.com/PHPOffice/PhpSpreadsheet/issues/3720) [PR #3722](https://github.com/PHPOffice/PhpSpreadsheet/pull/3722) - Break Some Circular References. [PR #3716](https://github.com/PHPOffice/PhpSpreadsheet/pull/3716) [PR #3707](https://github.com/PHPOffice/PhpSpreadsheet/pull/3707) - Missing Font Index in Some Xls. [PR #3734](https://github.com/PHPOffice/PhpSpreadsheet/pull/3734) - Load Tables even with READ_DATA_ONLY. [PR #3726](https://github.com/PHPOffice/PhpSpreadsheet/pull/3726) - Theme File Missing but Referenced in Spreadsheet. [Issue #3770](https://github.com/PHPOffice/PhpSpreadsheet/issues/3770) [PR #3772](https://github.com/PHPOffice/PhpSpreadsheet/pull/3772) - Slk Shared Formulas. [Issue #2267](https://github.com/PHPOffice/PhpSpreadsheet/issues/2267) [PR #3776](https://github.com/PHPOffice/PhpSpreadsheet/pull/3776) - Html omitting some charts. [Issue #3767](https://github.com/PHPOffice/PhpSpreadsheet/issues/3767) [PR #3771](https://github.com/PHPOffice/PhpSpreadsheet/pull/3771) - Case Insensitive Comparison for Sheet Names [PR #3791](https://github.com/PHPOffice/PhpSpreadsheet/pull/3791) - Performance improvement for Xlsx Reader. [Issue #3683](https://github.com/PHPOffice/PhpSpreadsheet/issues/3683) [PR #3810](https://github.com/PHPOffice/PhpSpreadsheet/pull/3810) - Prevent loop in Shared/File. [Issue #3807](https://github.com/PHPOffice/PhpSpreadsheet/issues/3807) [PR #3809](https://github.com/PHPOffice/PhpSpreadsheet/pull/3809) - Consistent handling of decimal/thousands separators between StringHelper and Php setlocale. [Issue #3811](https://github.com/PHPOffice/PhpSpreadsheet/issues/3811) [PR #3815](https://github.com/PHPOffice/PhpSpreadsheet/pull/3815) - Clone worksheet with tables or charts. [Issue #3820](https://github.com/PHPOffice/PhpSpreadsheet/issues/3820) [PR #3821](https://github.com/PHPOffice/PhpSpreadsheet/pull/3821) - COUNTIFS Does Not Require xlfn. [Issue #3819](https://github.com/PHPOffice/PhpSpreadsheet/issues/3819) [PR #3827](https://github.com/PHPOffice/PhpSpreadsheet/pull/3827) - Strip `xlfn.` and `xlws.` from Formula Translations. [Issue #3819](https://github.com/PHPOffice/PhpSpreadsheet/issues/3819) [PR #3828](https://github.com/PHPOffice/PhpSpreadsheet/pull/3828) - Recurse directories searching for font file. [Issue #2809](https://github.com/PHPOffice/PhpSpreadsheet/issues/2809) [PR #3830](https://github.com/PHPOffice/PhpSpreadsheet/pull/3830) - Reduce memory consumption of Worksheet::rangeToArray() when many empty rows are read. [Issue #3814](https://github.com/PHPOffice/PhpSpreadsheet/issues/3814) [PR #3834](https://github.com/PHPOffice/PhpSpreadsheet/pull/3834) - Reduce time used by Worksheet::rangeToArray() when many empty rows are read. [PR #3839](https://github.com/PHPOffice/PhpSpreadsheet/pull/3839) - Html Reader Tolerate Invalid Sheet Title. [PR #3845](https://github.com/PHPOffice/PhpSpreadsheet/pull/3845) - Do not include unparsed drawings when new drawing added. [Issue #3843](https://github.com/PHPOffice/PhpSpreadsheet/issues/3843) [PR #3846](https://github.com/PHPOffice/PhpSpreadsheet/pull/3846) - Do not include unparsed drawings when new drawing added. [Issue #3861](https://github.com/PHPOffice/PhpSpreadsheet/issues/3861) [PR #3862](https://github.com/PHPOffice/PhpSpreadsheet/pull/3862) - Excel omits `between` operator for data validation. [Issue #3863](https://github.com/PHPOffice/PhpSpreadsheet/issues/3863) [PR #3865](https://github.com/PHPOffice/PhpSpreadsheet/pull/3865) - Use less space when inserting rows and columns. [Issue #3687](https://github.com/PHPOffice/PhpSpreadsheet/issues/3687) [PR #3856](https://github.com/PHPOffice/PhpSpreadsheet/pull/3856) - Excel inconsistent handling of MIN/MAX/MINA/MAXA. [Issue #3866](https://github.com/PHPOffice/PhpSpreadsheet/issues/3866) [PR #3868](https://github.com/PHPOffice/PhpSpreadsheet/pull/3868) ## 1.29.0 - 2023-06-15 ### Added - Wizards for defining Number Format masks for Dates and Times, including Durations/Intervals. [PR #3458](https://github.com/PHPOffice/PhpSpreadsheet/pull/3458) - Specify data type in html tags. [Issue #3444](https://github.com/PHPOffice/PhpSpreadsheet/issues/3444) [PR #3445](https://github.com/PHPOffice/PhpSpreadsheet/pull/3445) - Provide option to ignore hidden rows/columns in `toArray()` methods. [PR #3494](https://github.com/PHPOffice/PhpSpreadsheet/pull/3494) - Font/Effects/Theme support for Chart Data Labels and Axis. [PR #3476](https://github.com/PHPOffice/PhpSpreadsheet/pull/3476) - Font Themes support. [PR #3486](https://github.com/PHPOffice/PhpSpreadsheet/pull/3486) - Ability to Ignore Cell Errors in Excel. [Issue #1141](https://github.com/PHPOffice/PhpSpreadsheet/issues/1141) [PR #3508](https://github.com/PHPOffice/PhpSpreadsheet/pull/3508) - Unzipped Gnumeric file [PR #3591](https://github.com/PHPOffice/PhpSpreadsheet/pull/3591) ### Changed - Xlsx Color schemes read in will be written out (previously Excel 2007-2010 Color scheme was always written); manipulation of those schemes before write, including restoring prior behavior, is provided [PR #3476](https://github.com/PHPOffice/PhpSpreadsheet/pull/3476) - Memory and speed optimisations for Read Filters with Xlsx Files and Shared Formulae. [PR #3474](https://github.com/PHPOffice/PhpSpreadsheet/pull/3474) - Allow `CellRange` and `CellAddress` objects for the `range` argument in the `rangeToArray()` method. [PR #3494](https://github.com/PHPOffice/PhpSpreadsheet/pull/3494) - Stock charts will now read and reproduce `upDownBars` and subsidiary tags; these were previously ignored on read and hard-coded on write. [PR #3515](https://github.com/PHPOffice/PhpSpreadsheet/pull/3515) ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Updates Cell formula absolute ranges/references, and Defined Name absolute ranges/references when inserting/deleting rows/columns. [Issue #3368](https://github.com/PHPOffice/PhpSpreadsheet/issues/3368) [PR #3402](https://github.com/PHPOffice/PhpSpreadsheet/pull/3402) - EOMONTH() and EDATE() Functions should round date value before evaluation. [Issue #3436](https://github.com/PHPOffice/PhpSpreadsheet/issues/3436) [PR #3437](https://github.com/PHPOffice/PhpSpreadsheet/pull/3437) - NETWORKDAYS function erroneously being converted to NETWORK_xlfn.DAYS in Xlsx Writer. [Issue #3461](https://github.com/PHPOffice/PhpSpreadsheet/issues/3461) [PR #3463](https://github.com/PHPOffice/PhpSpreadsheet/pull/3463) - Getting a style for a CellAddress instance fails if the worksheet is set in the CellAddress instance. [Issue #3439](https://github.com/PHPOffice/PhpSpreadsheet/issues/3439) [PR #3469](https://github.com/PHPOffice/PhpSpreadsheet/pull/3469) - Shared Formulae outside the filter range when reading with a filter are not always being identified. [Issue #3473](https://github.com/PHPOffice/PhpSpreadsheet/issues/3473) [PR #3474](https://github.com/PHPOffice/PhpSpreadsheet/pull/3474) - Xls Reader Conditional Styles. [PR #3400](https://github.com/PHPOffice/PhpSpreadsheet/pull/3400) - Allow use of # and 0 digit placeholders in fraction masks. [PR #3401](https://github.com/PHPOffice/PhpSpreadsheet/pull/3401) - Modify Date/Time check in the NumberFormatter for decimal/fractional times. [PR #3413](https://github.com/PHPOffice/PhpSpreadsheet/pull/3413) - Misplaced Xml Writing Chart Label FillColor. [Issue #3397](https://github.com/PHPOffice/PhpSpreadsheet/issues/3397) [PR #3404](https://github.com/PHPOffice/PhpSpreadsheet/pull/3404) - TEXT function ignores Time in DateTimeStamp. [Issue #3409](https://github.com/PHPOffice/PhpSpreadsheet/issues/3409) [PR #3411](https://github.com/PHPOffice/PhpSpreadsheet/pull/3411) - Xlsx Column Autosize Approximate for CJK. [Issue #3405](https://github.com/PHPOffice/PhpSpreadsheet/issues/3405) [PR #3416](https://github.com/PHPOffice/PhpSpreadsheet/pull/3416) - Correct Xlsx Parsing of quotePrefix="0". [Issue #3435](https://github.com/PHPOffice/PhpSpreadsheet/issues/3435) [PR #3438](https://github.com/PHPOffice/PhpSpreadsheet/pull/3438) - More Display Options for Chart Axis and Legend. [Issue #3414](https://github.com/PHPOffice/PhpSpreadsheet/issues/3414) [PR #3434](https://github.com/PHPOffice/PhpSpreadsheet/pull/3434) - Apply strict type checking to Complex suffix. [PR #3452](https://github.com/PHPOffice/PhpSpreadsheet/pull/3452) - Incorrect Font Color Read Xlsx Rich Text Indexed Color Custom Palette. [Issue #3464](https://github.com/PHPOffice/PhpSpreadsheet/issues/3464) [PR #3465](https://github.com/PHPOffice/PhpSpreadsheet/pull/3465) - Xlsx Writer Honor Alignment in Default Font. [Issue #3443](https://github.com/PHPOffice/PhpSpreadsheet/issues/3443) [PR #3459](https://github.com/PHPOffice/PhpSpreadsheet/pull/3459) - Support Border for Charts. [PR #3462](https://github.com/PHPOffice/PhpSpreadsheet/pull/3462) - Error in "this row" structured reference calculation (cached result from first row when using a range) [Issue #3504](https://github.com/PHPOffice/PhpSpreadsheet/issues/3504) [PR #3505](https://github.com/PHPOffice/PhpSpreadsheet/pull/3505) - Allow colour palette index references in Number Format masks [Issue #3511](https://github.com/PHPOffice/PhpSpreadsheet/issues/3511) [PR #3512](https://github.com/PHPOffice/PhpSpreadsheet/pull/3512) - Xlsx Reader formula with quotePrefix [Issue #3495](https://github.com/PHPOffice/PhpSpreadsheet/issues/3495) [PR #3497](https://github.com/PHPOffice/PhpSpreadsheet/pull/3497) - Handle REF error as part of range [Issue #3453](https://github.com/PHPOffice/PhpSpreadsheet/issues/3453) [PR #3467](https://github.com/PHPOffice/PhpSpreadsheet/pull/3467) - Handle Absolute Pathnames in Rels File [Issue #3553](https://github.com/PHPOffice/PhpSpreadsheet/issues/3553) [PR #3554](https://github.com/PHPOffice/PhpSpreadsheet/pull/3554) - Return Page Breaks in Order [Issue #3552](https://github.com/PHPOffice/PhpSpreadsheet/issues/3552) [PR #3555](https://github.com/PHPOffice/PhpSpreadsheet/pull/3555) - Add position attribute for MemoryDrawing in Html [Issue #3529](https://github.com/PHPOffice/PhpSpreadsheet/issues/3529 [PR #3535](https://github.com/PHPOffice/PhpSpreadsheet/pull/3535) - Allow Index_number as Array for VLOOKUP/HLOOKUP [Issue #3561](https://github.com/PHPOffice/PhpSpreadsheet/issues/3561 [PR #3570](https://github.com/PHPOffice/PhpSpreadsheet/pull/3570) - Add Unsupported Options in Xml Spreadsheet [Issue #3566](https://github.com/PHPOffice/PhpSpreadsheet/issues/3566 [Issue #3568](https://github.com/PHPOffice/PhpSpreadsheet/issues/3568 [Issue #3569](https://github.com/PHPOffice/PhpSpreadsheet/issues/3569 [PR #3567](https://github.com/PHPOffice/PhpSpreadsheet/pull/3567) - Changes to NUMBERVALUE, VALUE, DATEVALUE, TIMEVALUE [Issue #3574](https://github.com/PHPOffice/PhpSpreadsheet/issues/3574 [PR #3575](https://github.com/PHPOffice/PhpSpreadsheet/pull/3575) - Redo calculation of color tinting [Issue #3550](https://github.com/PHPOffice/PhpSpreadsheet/issues/3550) [PR #3580](https://github.com/PHPOffice/PhpSpreadsheet/pull/3580) - Accommodate Slash with preg_quote [PR #3582](https://github.com/PHPOffice/PhpSpreadsheet/pull/3582) [PR #3583](https://github.com/PHPOffice/PhpSpreadsheet/pull/3583) [PR #3584](https://github.com/PHPOffice/PhpSpreadsheet/pull/3584) - HyperlinkBase Property and Html Handling of Properties [Issue #3573](https://github.com/PHPOffice/PhpSpreadsheet/issues/3573) [PR #3589](https://github.com/PHPOffice/PhpSpreadsheet/pull/3589) - Improvements for Data Validation [Issue #3592](https://github.com/PHPOffice/PhpSpreadsheet/issues/3592) [Issue #3594](https://github.com/PHPOffice/PhpSpreadsheet/issues/3594) [PR #3605](https://github.com/PHPOffice/PhpSpreadsheet/pull/3605) ## 1.28.0 - 2023-02-25 ### Added - Support for configuring a Chart Title's overlay [PR #3325](https://github.com/PHPOffice/PhpSpreadsheet/pull/3325) - Wizards for defining Number Format masks for Numbers, Percentages, Scientific, Currency and Accounting [PR #3334](https://github.com/PHPOffice/PhpSpreadsheet/pull/3334) - Support for fixed value divisor in fractional Number Format Masks [PR #3339](https://github.com/PHPOffice/PhpSpreadsheet/pull/3339) - Allow More Fonts/Fontnames for Exact Width Calculation [PR #3326](https://github.com/PHPOffice/PhpSpreadsheet/pull/3326) [Issue #3190](https://github.com/PHPOffice/PhpSpreadsheet/issues/3190) - Allow override of the Value Binder when setting a Cell value [PR #3361](https://github.com/PHPOffice/PhpSpreadsheet/pull/3361) ### Changed - Improved handling for @ placeholder in Number Format Masks [PR #3344](https://github.com/PHPOffice/PhpSpreadsheet/pull/3344) - Improved handling for ? placeholder in Number Format Masks [PR #3394](https://github.com/PHPOffice/PhpSpreadsheet/pull/3394) - Improved support for locale settings and currency codes when matching formatted strings to numerics in the Calculation Engine [PR #3373](https://github.com/PHPOffice/PhpSpreadsheet/pull/3373) and [PR #3374](https://github.com/PHPOffice/PhpSpreadsheet/pull/3374) - Improved support for locale settings and matching in the Advanced Value Binder [PR #3376](https://github.com/PHPOffice/PhpSpreadsheet/pull/3376) - `toFormattedString` will now always return a string. This can affect the results of `toArray`, `namedRangeToArray`, and `rangeToArray`. [PR #3304](https://github.com/PHPOffice/PhpSpreadsheet/pull/3304) - Value of constants FORMAT_CURRENCY_EUR and FORMAT_CURRENCY_USD is changed. [Issue #3577](https://github.com/PHPOffice/PhpSpreadsheet/issues/3577) [PR #3377](https://github.com/PHPOffice/PhpSpreadsheet/pull/3377) ### Deprecated - Rationalisation of Pre-defined Currency Format Masks [PR #3377](https://github.com/PHPOffice/PhpSpreadsheet/pull/3377) ### Removed - Nothing ### Fixed - Calculation Engine doesn't evaluate Defined Name when default cell A1 is quote-prefixed [Issue #3335](https://github.com/PHPOffice/PhpSpreadsheet/issues/3335) [PR #3336](https://github.com/PHPOffice/PhpSpreadsheet/pull/3336) - XLSX Writer - Array Formulas do not include function prefix [Issue #3337](https://github.com/PHPOffice/PhpSpreadsheet/issues/3337) [PR #3338](https://github.com/PHPOffice/PhpSpreadsheet/pull/3338) - Permit Max Column for Row Breaks [Issue #3143](https://github.com/PHPOffice/PhpSpreadsheet/issues/3143) [PR #3345](https://github.com/PHPOffice/PhpSpreadsheet/pull/3345) - AutoSize Columns should allow for dropdown icon when AutoFilter is for a Table [Issue #3356](https://github.com/PHPOffice/PhpSpreadsheet/issues/3356) [PR #3358](https://github.com/PHPOffice/PhpSpreadsheet/pull/3358) and for Center Alignment of Headers [Issue #3395](https://github.com/PHPOffice/PhpSpreadsheet/issues/3395) [PR #3399](https://github.com/PHPOffice/PhpSpreadsheet/pull/3399) - Decimal Precision for Scientific Number Format Mask [Issue #3381](https://github.com/PHPOffice/PhpSpreadsheet/issues/3381) [PR #3382](https://github.com/PHPOffice/PhpSpreadsheet/pull/3382) - Xls Writer Parser Handle Boolean Literals as Function Arguments [Issue #3369](https://github.com/PHPOffice/PhpSpreadsheet/issues/3369) [PR #3391](https://github.com/PHPOffice/PhpSpreadsheet/pull/3391) - Conditional Formatting Improvements for Xlsx [Issue #3370](https://github.com/PHPOffice/PhpSpreadsheet/issues/3370) [Issue #3202](https://github.com/PHPOffice/PhpSpreadsheet/issues/3302) [PR #3372](https://github.com/PHPOffice/PhpSpreadsheet/pull/3372) - Coerce Bool to Int for Mathematical Operations on Arrays [Issue #3389](https://github.com/PHPOffice/PhpSpreadsheet/issues/3389) [Issue #3396](https://github.com/PHPOffice/PhpSpreadsheet/issues/3396) [PR #3392](https://github.com/PHPOffice/PhpSpreadsheet/pull/3392) ## 1.27.1 - 2023-02-08 ### Added - Nothing ### Changed - Nothing ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fix Composer --dev dependency issue with dealerdirect/phpcodesniffer-composer-installer renaming their `master` branch to `main` ## 1.27.0 - 2023-01-24 ### Added - Option to specify a range of columns/rows for the Row/Column `isEmpty()` methods [PR #3315](https://github.com/PHPOffice/PhpSpreadsheet/pull/3315) - Option for Cell Iterator to return a null value or create and return a new cell when accessing a cell that doesn't exist [PR #3314](https://github.com/PHPOffice/PhpSpreadsheet/pull/3314) - Support for Structured References in the Calculation Engine [PR #3261](https://github.com/PHPOffice/PhpSpreadsheet/pull/3261) - Limited Support for Form Controls [PR #3130](https://github.com/PHPOffice/PhpSpreadsheet/pull/3130) [Issue #2396](https://github.com/PHPOffice/PhpSpreadsheet/issues/2396) [Issue #1770](https://github.com/PHPOffice/PhpSpreadsheet/issues/1770) [Issue #2388](https://github.com/PHPOffice/PhpSpreadsheet/issues/2388) [Issue #2904](https://github.com/PHPOffice/PhpSpreadsheet/issues/2904) [Issue #2661](https://github.com/PHPOffice/PhpSpreadsheet/issues/2661) ### Changed - Nothing ### Deprecated - Nothing ### Removed - Shared/JAMA is removed. [PR #3260](https://github.com/PHPOffice/PhpSpreadsheet/pull/3260) ### Fixed - Namespace-Aware Code for SheetViewOptions, SheetProtection [PR #3230](https://github.com/PHPOffice/PhpSpreadsheet/pull/3230) - Additional Method for XIRR if Newton-Raphson Doesn't Converge [Issue #689](https://github.com/PHPOffice/PhpSpreadsheet/issues/689) [PR #3262](https://github.com/PHPOffice/PhpSpreadsheet/pull/3262) - Better Handling of Composite Charts [Issue #2333](https://github.com/PHPOffice/PhpSpreadsheet/issues/2333) [PR #3265](https://github.com/PHPOffice/PhpSpreadsheet/pull/3265) - Update Column Reference for Columns Beginning with Y and Z [Issue #3263](https://github.com/PHPOffice/PhpSpreadsheet/issues/3263) [PR #3264](https://github.com/PHPOffice/PhpSpreadsheet/pull/3264) - Honor Fit to 1-Page Height Html/Pdf [Issue #3266](https://github.com/PHPOffice/PhpSpreadsheet/issues/3266) [PR #3279](https://github.com/PHPOffice/PhpSpreadsheet/pull/3279) - AND/OR/XOR Handling of Literal Strings [PR #3287](https://github.com/PHPOffice/PhpSpreadsheet/pull/3287) - Xls Reader Vertical Break and Writer Page Order [Issue #3305](https://github.com/PHPOffice/PhpSpreadsheet/issues/3305) [PR #3306](https://github.com/PHPOffice/PhpSpreadsheet/pull/3306) ## 1.26.0 - 2022-12-21 ### Added - Extended flag options for the Reader `load()` and Writer `save()` methods - Apply Row/Column limits (1048576 and XFD) in ReferenceHelper [PR #3213](https://github.com/PHPOffice/PhpSpreadsheet/pull/3213) - Allow the creation of In-Memory Drawings from a string of binary image data, or from a stream. [PR #3157](https://github.com/PHPOffice/PhpSpreadsheet/pull/3157) - Xlsx Reader support for Pivot Tables [PR #2829](https://github.com/PHPOffice/PhpSpreadsheet/pull/2829) - Permit Date/Time Entered on Spreadsheet to be calculated as Float [Issue #1416](https://github.com/PHPOffice/PhpSpreadsheet/issues/1416) [PR #3121](https://github.com/PHPOffice/PhpSpreadsheet/pull/3121) ### Changed - Nothing ### Deprecated - Direct update of Calculation::suppressFormulaErrors is replaced with setter. - Font public static variable defaultColumnWidths replaced with constant DEFAULT_COLUMN_WIDTHS. - ExcelError public static variable errorCodes replaced with constant ERROR_CODES. - NumberFormat constant FORMAT_DATE_YYYYMMDD2 replaced with existing identical FORMAT_DATE_YYYYMMDD. ### Removed - Nothing ### Fixed - Fixed handling for `_xlws` prefixed functions from Office365 [Issue #3245](https://github.com/PHPOffice/PhpSpreadsheet/issues/3245) [PR #3247](https://github.com/PHPOffice/PhpSpreadsheet/pull/3247) - Conditionals formatting rules applied to rows/columns are removed [Issue #3184](https://github.com/PHPOffice/PhpSpreadsheet/issues/3184) [PR #3213](https://github.com/PHPOffice/PhpSpreadsheet/pull/3213) - Treat strings containing currency or accounting values as floats in Calculation Engine operations [Issue #3165](https://github.com/PHPOffice/PhpSpreadsheet/issues/3165) [PR #3189](https://github.com/PHPOffice/PhpSpreadsheet/pull/3189) - Treat strings containing percentage values as floats in Calculation Engine operations [Issue #3155](https://github.com/PHPOffice/PhpSpreadsheet/issues/3155) [PR #3156](https://github.com/PHPOffice/PhpSpreadsheet/pull/3156) and [PR #3164](https://github.com/PHPOffice/PhpSpreadsheet/pull/3164) - Xlsx Reader Accept Palette of Fewer than 64 Colors [Issue #3093](https://github.com/PHPOffice/PhpSpreadsheet/issues/3093) [PR #3096](https://github.com/PHPOffice/PhpSpreadsheet/pull/3096) - Use Locale-Independent Float Conversion for Xlsx Writer Custom Property [Issue #3095](https://github.com/PHPOffice/PhpSpreadsheet/issues/3095) [PR #3099](https://github.com/PHPOffice/PhpSpreadsheet/pull/3099) - Allow setting AutoFilter range on a single cell or row [Issue #3102](https://github.com/PHPOffice/PhpSpreadsheet/issues/3102) [PR #3111](https://github.com/PHPOffice/PhpSpreadsheet/pull/3111) - Xlsx Reader External Data Validations Flag Missing [Issue #2677](https://github.com/PHPOffice/PhpSpreadsheet/issues/2677) [PR #3078](https://github.com/PHPOffice/PhpSpreadsheet/pull/3078) - Reduces extra memory usage on `__destruct()` calls [PR #3092](https://github.com/PHPOffice/PhpSpreadsheet/pull/3092) - Additional properties for Trendlines [Issue #3011](https://github.com/PHPOffice/PhpSpreadsheet/issues/3011) [PR #3028](https://github.com/PHPOffice/PhpSpreadsheet/pull/3028) - Calculation suppressFormulaErrors fix [Issue #1531](https://github.com/PHPOffice/PhpSpreadsheet/issues/1531) [PR #3092](https://github.com/PHPOffice/PhpSpreadsheet/pull/3092) - Permit Date/Time Entered on Spreadsheet to be Calculated as Float [Issue #1416](https://github.com/PHPOffice/PhpSpreadsheet/issues/1416) [PR #3121](https://github.com/PHPOffice/PhpSpreadsheet/pull/3121) - Incorrect Handling of Data Validation Formula Containing Ampersand [Issue #3145](https://github.com/PHPOffice/PhpSpreadsheet/issues/3145) [PR #3146](https://github.com/PHPOffice/PhpSpreadsheet/pull/3146) - Xlsx Namespace Handling of Drawings, RowAndColumnAttributes, MergeCells [Issue #3138](https://github.com/PHPOffice/PhpSpreadsheet/issues/3138) [PR #3136](https://github.com/PHPOffice/PhpSpreadsheet/pull/3137) - Generation3 Copy With Image in Footer [Issue #3126](https://github.com/PHPOffice/PhpSpreadsheet/issues/3126) [PR #3140](https://github.com/PHPOffice/PhpSpreadsheet/pull/3140) - MATCH Function Problems with Int/Float Compare and Wildcards [Issue #3141](https://github.com/PHPOffice/PhpSpreadsheet/issues/3141) [PR #3142](https://github.com/PHPOffice/PhpSpreadsheet/pull/3142) - Fix ODS Read Filter on number-columns-repeated cell [Issue #3148](https://github.com/PHPOffice/PhpSpreadsheet/issues/3148) [PR #3149](https://github.com/PHPOffice/PhpSpreadsheet/pull/3149) - Problems Formatting Very Small and Very Large Numbers [Issue #3128](https://github.com/PHPOffice/PhpSpreadsheet/issues/3128) [PR #3152](https://github.com/PHPOffice/PhpSpreadsheet/pull/3152) - XlsxWrite preserve line styles for y-axis, not just x-axis [PR #3163](https://github.com/PHPOffice/PhpSpreadsheet/pull/3163) - Xlsx Namespace Handling of Drawings, RowAndColumnAttributes, MergeCells [Issue #3138](https://github.com/PHPOffice/PhpSpreadsheet/issues/3138) [PR #3137](https://github.com/PHPOffice/PhpSpreadsheet/pull/3137) - More Detail for Cyclic Error Messages [Issue #3169](https://github.com/PHPOffice/PhpSpreadsheet/issues/3169) [PR #3170](https://github.com/PHPOffice/PhpSpreadsheet/pull/3170) - Improved Documentation for Deprecations - many PRs [Issue #3162](https://github.com/PHPOffice/PhpSpreadsheet/issues/3162) ## 1.25.2 - 2022-09-25 ### Added - Nothing ### Changed - Nothing ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Composer dependency clash with ezyang/htmlpurifier ## 1.25.0 - 2022-09-25 ### Added - Implementation of the new `TEXTBEFORE()`, `TEXTAFTER()` and `TEXTSPLIT()` Excel Functions - Implementation of the `ARRAYTOTEXT()` and `VALUETOTEXT()` Excel Functions - Support for [mitoteam/jpgraph](https://packagist.org/packages/mitoteam/jpgraph) implementation of JpGraph library to render charts added. - Charts: Add Gradients, Transparency, Hidden Axes, Rounded Corners, Trendlines, Date Axes. ### Changed - Allow variant behaviour when merging cells [Issue #3065](https://github.com/PHPOffice/PhpSpreadsheet/issues/3065) - Merge methods now allow an additional `$behaviour` argument. Permitted values are: - Worksheet::MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells (the default behaviour) - Worksheet::MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells - Worksheet::MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell ### Deprecated - Axis getLineProperty deprecated in favor of getLineColorProperty. - Moved majorGridlines and minorGridlines from Chart to Axis. Setting either in Chart constructor or through Chart methods, or getting either using Chart methods is deprecated. - Chart::EXCEL_COLOR_TYPE_* copied from Properties to ChartColor; use in Properties is deprecated. - ChartColor::EXCEL_COLOR_TYPE_ARGB deprecated in favor of EXCEL_COLOR_TYPE_RGB ("A" component was never allowed). - Misspelled Properties::LINE_STYLE_DASH_SQUERE_DOT deprecated in favor of LINE_STYLE_DASH_SQUARE_DOT. - Clone not permitted for Spreadsheet. Spreadsheet->copy() can be used instead. ### Removed - Nothing ### Fixed - Fix update to defined names when inserting/deleting rows/columns [Issue #3076](https://github.com/PHPOffice/PhpSpreadsheet/issues/3076) [PR #3077](https://github.com/PHPOffice/PhpSpreadsheet/pull/3077) - Fix DataValidation sqRef when inserting/deleting rows/columns [Issue #3056](https://github.com/PHPOffice/PhpSpreadsheet/issues/3056) [PR #3074](https://github.com/PHPOffice/PhpSpreadsheet/pull/3074) - Named ranges not usable as anchors in OFFSET function [Issue #3013](https://github.com/PHPOffice/PhpSpreadsheet/issues/3013) - Fully flatten an array [Issue #2955](https://github.com/PHPOffice/PhpSpreadsheet/issues/2955) [PR #2956](https://github.com/PHPOffice/PhpSpreadsheet/pull/2956) - cellExists() and getCell() methods should support UTF-8 named cells [Issue #2987](https://github.com/PHPOffice/PhpSpreadsheet/issues/2987) [PR #2988](https://github.com/PHPOffice/PhpSpreadsheet/pull/2988) - Spreadsheet copy fixed, clone disabled. [PR #2951](https://github.com/PHPOffice/PhpSpreadsheet/pull/2951) - Fix PDF problems with text rotation and paper size. [Issue #1747](https://github.com/PHPOffice/PhpSpreadsheet/issues/1747) [Issue #1713](https://github.com/PHPOffice/PhpSpreadsheet/issues/1713) [PR #2960](https://github.com/PHPOffice/PhpSpreadsheet/pull/2960) - Limited support for chart titles as formulas [Issue #2965](https://github.com/PHPOffice/PhpSpreadsheet/issues/2965) [Issue #749](https://github.com/PHPOffice/PhpSpreadsheet/issues/749) [PR #2971](https://github.com/PHPOffice/PhpSpreadsheet/pull/2971) - Add Gradients, Transparency, and Hidden Axes to Chart [Issue #2257](https://github.com/PHPOffice/PhpSpreadsheet/issues/2257) [Issue #2229](https://github.com/PHPOffice/PhpSpreadsheet/issues/2929) [Issue #2935](https://github.com/PHPOffice/PhpSpreadsheet/issues/2935) [PR #2950](https://github.com/PHPOffice/PhpSpreadsheet/pull/2950) - Chart Support for Rounded Corners and Trendlines [Issue #2968](https://github.com/PHPOffice/PhpSpreadsheet/issues/2968) [Issue #2815](https://github.com/PHPOffice/PhpSpreadsheet/issues/2815) [PR #2976](https://github.com/PHPOffice/PhpSpreadsheet/pull/2976) - Add setName Method for Chart [Issue #2991](https://github.com/PHPOffice/PhpSpreadsheet/issues/2991) [PR #3001](https://github.com/PHPOffice/PhpSpreadsheet/pull/3001) - Eliminate partial dependency on php-intl in StringHelper [Issue #2982](https://github.com/PHPOffice/PhpSpreadsheet/issues/2982) [PR #2994](https://github.com/PHPOffice/PhpSpreadsheet/pull/2994) - Minor changes for Pdf [Issue #2999](https://github.com/PHPOffice/PhpSpreadsheet/issues/2999) [PR #3002](https://github.com/PHPOffice/PhpSpreadsheet/pull/3002) [PR #3006](https://github.com/PHPOffice/PhpSpreadsheet/pull/3006) - Html/Pdf Do net set background color for cells using (default) nofill [PR #3016](https://github.com/PHPOffice/PhpSpreadsheet/pull/3016) - Add support for Date Axis to Chart [Issue #2967](https://github.com/PHPOffice/PhpSpreadsheet/issues/2967) [PR #3018](https://github.com/PHPOffice/PhpSpreadsheet/pull/3018) - Reconcile Differences Between Css and Excel for Cell Alignment [PR #3048](https://github.com/PHPOffice/PhpSpreadsheet/pull/3048) - R1C1 Format Internationalization and Better Support for Relative Offsets [Issue #1704](https://github.com/PHPOffice/PhpSpreadsheet/issues/1704) [PR #3052](https://github.com/PHPOffice/PhpSpreadsheet/pull/3052) - Minor Fix for Percentage Formatting [Issue #1929](https://github.com/PHPOffice/PhpSpreadsheet/issues/1929) [PR #3053](https://github.com/PHPOffice/PhpSpreadsheet/pull/3053) ## 1.24.1 - 2022-07-18 ### Added - Support for SimpleCache Interface versions 1.0, 2.0 and 3.0 - Add Chart Axis Option textRotation [Issue #2705](https://github.com/PHPOffice/PhpSpreadsheet/issues/2705) [PR #2940](https://github.com/PHPOffice/PhpSpreadsheet/pull/2940) ### Changed - Nothing ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fix Encoding issue with Html reader (PHP 8.2 deprecation for mb_convert_encoding) [Issue #2942](https://github.com/PHPOffice/PhpSpreadsheet/issues/2942) [PR #2943](https://github.com/PHPOffice/PhpSpreadsheet/pull/2943) - Additional Chart fixes - Pie chart with part separated unwantedly [Issue #2506](https://github.com/PHPOffice/PhpSpreadsheet/issues/2506) [PR #2928](https://github.com/PHPOffice/PhpSpreadsheet/pull/2928) - Chart styling is lost on simple load / save process [Issue #1797](https://github.com/PHPOffice/PhpSpreadsheet/issues/1797) [Issue #2077](https://github.com/PHPOffice/PhpSpreadsheet/issues/2077) [PR #2930](https://github.com/PHPOffice/PhpSpreadsheet/pull/2930) - Can't create contour chart (surface 2d) [Issue #2931](https://github.com/PHPOffice/PhpSpreadsheet/issues/2931) [PR #2933](https://github.com/PHPOffice/PhpSpreadsheet/pull/2933) - VLOOKUP Breaks When Array Contains Null Cells [Issue #2934](https://github.com/PHPOffice/PhpSpreadsheet/issues/2934) [PR #2939](https://github.com/PHPOffice/PhpSpreadsheet/pull/2939) ## 1.24.0 - 2022-07-09 Note that this will be the last 1.x branch release before the 2.x release. We will maintain both branches in parallel for a time; but users are requested to update to version 2.0 once that is fully available. ### Added - Added `removeComment()` method for Worksheet [PR #2875](https://github.com/PHPOffice/PhpSpreadsheet/pull/2875/files) - Add point size option for scatter charts [Issue #2298](https://github.com/PHPOffice/PhpSpreadsheet/issues/2298) [PR #2801](https://github.com/PHPOffice/PhpSpreadsheet/pull/2801) - Basic support for Xlsx reading/writing Chart Sheets [PR #2830](https://github.com/PHPOffice/PhpSpreadsheet/pull/2830) Note that a ChartSheet is still only written as a normal Worksheet containing a single chart, not as an actual ChartSheet. - Added Worksheet visibility in Ods Reader [PR #2851](https://github.com/PHPOffice/PhpSpreadsheet/pull/2851) and Gnumeric Reader [PR #2853](https://github.com/PHPOffice/PhpSpreadsheet/pull/2853) - Added Worksheet visibility in Ods Writer [PR #2850](https://github.com/PHPOffice/PhpSpreadsheet/pull/2850) - Allow Csv Reader to treat string as contents of file [Issue #1285](https://github.com/PHPOffice/PhpSpreadsheet/issues/1285) [PR #2792](https://github.com/PHPOffice/PhpSpreadsheet/pull/2792) - Allow Csv Reader to store null string rather than leave cell empty [Issue #2840](https://github.com/PHPOffice/PhpSpreadsheet/issues/2840) [PR #2842](https://github.com/PHPOffice/PhpSpreadsheet/pull/2842) - Provide new Worksheet methods to identify if a row or column is "empty", making allowance for different definitions of "empty": - Treat rows/columns containing no cell records as empty (default) - Treat cells containing a null value as empty - Treat cells containing an empty string as empty ### Changed - Modify `rangeBoundaries()`, `rangeDimension()` and `getRangeBoundaries()` Coordinate methods to work with row/column ranges as well as with cell ranges and cells [PR #2926](https://github.com/PHPOffice/PhpSpreadsheet/pull/2926) - Better enforcement of value modification to match specified datatype when using `setValueExplicit()` - Relax validation of merge cells to allow merge for a single cell reference [Issue #2776](https://github.com/PHPOffice/PhpSpreadsheet/issues/2776) - Memory and speed improvements, particularly for the Cell Collection, and the Writers. See [the Discussion section on github](https://github.com/PHPOffice/PhpSpreadsheet/discussions/2821) for details of performance across versions - Improved performance for removing rows/columns from a worksheet ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Xls Reader resolving absolute named ranges to relative ranges [Issue #2826](https://github.com/PHPOffice/PhpSpreadsheet/issues/2826) [PR #2827](https://github.com/PHPOffice/PhpSpreadsheet/pull/2827) - Null value handling in the Excel Math/Trig PRODUCT() function [Issue #2833](https://github.com/PHPOffice/PhpSpreadsheet/issues/2833) [PR #2834](https://github.com/PHPOffice/PhpSpreadsheet/pull/2834) - Invalid Print Area defined in Xlsx corrupts internal storage of print area [Issue #2848](https://github.com/PHPOffice/PhpSpreadsheet/issues/2848) [PR #2849](https://github.com/PHPOffice/PhpSpreadsheet/pull/2849) - Time interval formatting [Issue #2768](https://github.com/PHPOffice/PhpSpreadsheet/issues/2768) [PR #2772](https://github.com/PHPOffice/PhpSpreadsheet/pull/2772) - Copy from Xls(x) to Html/Pdf loses drawings [PR #2788](https://github.com/PHPOffice/PhpSpreadsheet/pull/2788) - Html Reader converting cell containing 0 to null string [Issue #2810](https://github.com/PHPOffice/PhpSpreadsheet/issues/2810) [PR #2813](https://github.com/PHPOffice/PhpSpreadsheet/pull/2813) - Many fixes for Charts, especially, but not limited to, Scatter, Bubble, and Surface charts. [Issue #2762](https://github.com/PHPOffice/PhpSpreadsheet/issues/2762) [Issue #2299](https://github.com/PHPOffice/PhpSpreadsheet/issues/2299) [Issue #2700](https://github.com/PHPOffice/PhpSpreadsheet/issues/2700) [Issue #2817](https://github.com/PHPOffice/PhpSpreadsheet/issues/2817) [Issue #2763](https://github.com/PHPOffice/PhpSpreadsheet/issues/2763) [Issue #2219](https://github.com/PHPOffice/PhpSpreadsheet/issues/2219) [Issue #2863](https://github.com/PHPOffice/PhpSpreadsheet/issues/2863) [PR #2828](https://github.com/PHPOffice/PhpSpreadsheet/pull/2828) [PR #2841](https://github.com/PHPOffice/PhpSpreadsheet/pull/2841) [PR #2846](https://github.com/PHPOffice/PhpSpreadsheet/pull/2846) [PR #2852](https://github.com/PHPOffice/PhpSpreadsheet/pull/2852) [PR #2856](https://github.com/PHPOffice/PhpSpreadsheet/pull/2856) [PR #2865](https://github.com/PHPOffice/PhpSpreadsheet/pull/2865) [PR #2872](https://github.com/PHPOffice/PhpSpreadsheet/pull/2872) [PR #2879](https://github.com/PHPOffice/PhpSpreadsheet/pull/2879) [PR #2898](https://github.com/PHPOffice/PhpSpreadsheet/pull/2898) [PR #2906](https://github.com/PHPOffice/PhpSpreadsheet/pull/2906) [PR #2922](https://github.com/PHPOffice/PhpSpreadsheet/pull/2922) [PR #2923](https://github.com/PHPOffice/PhpSpreadsheet/pull/2923) - Adjust both coordinates for two-cell anchors when rows/columns are added/deleted. [Issue #2908](https://github.com/PHPOffice/PhpSpreadsheet/issues/2908) [PR #2909](https://github.com/PHPOffice/PhpSpreadsheet/pull/2909) - Keep calculated string results below 32K. [PR #2921](https://github.com/PHPOffice/PhpSpreadsheet/pull/2921) - Filter out illegal Unicode char values FFFE/FFFF. [Issue #2897](https://github.com/PHPOffice/PhpSpreadsheet/issues/2897) [PR #2910](https://github.com/PHPOffice/PhpSpreadsheet/pull/2910) - Better handling of REF errors and propagation of all errors in Calculation engine. [PR #2902](https://github.com/PHPOffice/PhpSpreadsheet/pull/2902) - Calculating Engine regexp for Column/Row references when there are multiple quoted worksheet references in the formula [Issue #2874](https://github.com/PHPOffice/PhpSpreadsheet/issues/2874) [PR #2899](https://github.com/PHPOffice/PhpSpreadsheet/pull/2899) ## 1.23.0 - 2022-04-24 ### Added - Ods Writer support for Freeze Pane [Issue #2013](https://github.com/PHPOffice/PhpSpreadsheet/issues/2013) [PR #2755](https://github.com/PHPOffice/PhpSpreadsheet/pull/2755) - Ods Writer support for setting column width/row height (including the use of AutoSize) [Issue #2346](https://github.com/PHPOffice/PhpSpreadsheet/issues/2346) [PR #2753](https://github.com/PHPOffice/PhpSpreadsheet/pull/2753) - Introduced CellAddress, CellRange, RowRange and ColumnRange value objects that can be used as an alternative to a string value (e.g. `'C5'`, `'B2:D4'`, `'2:2'` or `'B:C'`) in appropriate contexts. - Implementation of the FILTER(), SORT(), SORTBY() and UNIQUE() Lookup/Reference (array) functions. - Implementation of the ISREF() Information function. - Added support for reading "formatted" numeric values from Csv files; although default behaviour of reading these values as strings is preserved. (i.e a value of "12,345.67" can be read as numeric `12345.67`, not simply as a string `"12,345.67"`, if the `castFormattedNumberToNumeric()` setting is enabled. This functionality is locale-aware, using the server's locale settings to identify the thousands and decimal separators. - Support for two cell anchor drawing of images. [#2532](https://github.com/PHPOffice/PhpSpreadsheet/pull/2532) [#2674](https://github.com/PHPOffice/PhpSpreadsheet/pull/2674) - Limited support for Xls Reader to handle Conditional Formatting: Ranges and Rules are read, but style is currently limited to font size, weight and color; and to fill style and color. - Add ability to suppress Mac line ending check for CSV [#2623](https://github.com/PHPOffice/PhpSpreadsheet/pull/2623) - Initial support for creating and writing Tables (Xlsx Writer only) [PR #2671](https://github.com/PHPOffice/PhpSpreadsheet/pull/2671) See `/samples/Table` for examples of use. Note that PreCalculateFormulas needs to be disabled when saving spreadsheets containing tables with formulae (totals or column formulae). ### Changed - Gnumeric Reader now loads number formatting for cells. - Gnumeric Reader now correctly identifies selected worksheet and selected cells in a worksheet. - Some Refactoring of the Ods Reader, moving all formula and address translation from Ods to Excel into a separate class to eliminate code duplication and ensure consistency. - Make Boolean Conversion in Csv Reader locale-aware when using the String Value Binder. This is determined by the Calculation Engine locale setting. (i.e. `"Vrai"` wil be converted to a boolean `true` if the Locale is set to `fr`.) - Allow `psr/simple-cache` 2.x ### Deprecated - All Excel Function implementations in `Calculation\Functions` (including the Error functions) have been moved to dedicated classes for groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. - Worksheet methods that reference cells "byColumnandRow". All such methods have an equivalent that references the cell by its address (e.g. '`E3'` rather than `5, 3`). These functions now accept either a cell address string (`'E3')` or an array with columnId and rowId (`[5, 3]`) or a new `CellAddress` object as their `cellAddress`/`coordinate` argument. This includes the methods: - `setCellValueByColumnAndRow()` use the equivalent `setCellValue()` - `setCellValueExplicitByColumnAndRow()` use the equivalent `setCellValueExplicit()` - `getCellByColumnAndRow()` use the equivalent `getCell()` - `cellExistsByColumnAndRow()` use the equivalent `cellExists()` - `getStyleByColumnAndRow()` use the equivalent `getStyle()` - `setBreakByColumnAndRow()` use the equivalent `setBreak()` - `mergeCellsByColumnAndRow()` use the equivalent `mergeCells()` - `unmergeCellsByColumnAndRow()` use the equivalent `unmergeCells()` - `protectCellsByColumnAndRow()` use the equivalent `protectCells()` - `unprotectCellsByColumnAndRow()` use the equivalent `unprotectCells()` - `setAutoFilterByColumnAndRow()` use the equivalent `setAutoFilter()` - `freezePaneByColumnAndRow()` use the equivalent `freezePane()` - `getCommentByColumnAndRow()` use the equivalent `getComment()` - `setSelectedCellByColumnAndRow()` use the equivalent `setSelectedCells()` This change provides more consistency in the methods (not every "by cell address" method has an equivalent "byColumnAndRow" method); and the "by cell address" methods often provide more flexibility, such as allowing a range of cells, or referencing them by passing the defined name of a named range as the argument. ### Removed - Nothing ### Fixed - Make allowance for the AutoFilter dropdown icon in the first row of an Autofilter range when using Autosize columns. [Issue #2413](https://github.com/PHPOffice/PhpSpreadsheet/issues/2413) [PR #2754](https://github.com/PHPOffice/PhpSpreadsheet/pull/2754) - Support for "chained" ranges (e.g. `A5:C10:C20:F1`) in the Calculation Engine; and also support for using named ranges with the Range operator (e.g. `NamedRange1:NamedRange2`) [Issue #2730](https://github.com/PHPOffice/PhpSpreadsheet/issues/2730) [PR #2746](https://github.com/PHPOffice/PhpSpreadsheet/pull/2746) - Update Conditional Formatting ranges and rule conditions when inserting/deleting rows/columns [Issue #2678](https://github.com/PHPOffice/PhpSpreadsheet/issues/2678) [PR #2689](https://github.com/PHPOffice/PhpSpreadsheet/pull/2689) - Allow `INDIRECT()` to accept row/column ranges as well as cell ranges [PR #2687](https://github.com/PHPOffice/PhpSpreadsheet/pull/2687) - Fix bug when deleting cells with hyperlinks, where the hyperlink was then being "inherited" by whatever cell moved to that cell address. - Fix bug in Conditional Formatting in the Xls Writer that resulted in a broken file when there were multiple conditional ranges in a worksheet. - Fix Conditional Formatting in the Xls Writer to work with rules that contain string literals, cell references and formulae. - Fix for setting Active Sheet to the first loaded worksheet when bookViews element isn't defined [Issue #2666](https://github.com/PHPOffice/PhpSpreadsheet/issues/2666) [PR #2669](https://github.com/PHPOffice/PhpSpreadsheet/pull/2669) - Fixed behaviour of XLSX font style vertical align settings [PR #2619](https://github.com/PHPOffice/PhpSpreadsheet/pull/2619) - Resolved formula translations to handle separators (row and column) for array functions as well as for function argument separators; and cleanly handle nesting levels. Note that this method is used when translating Excel functions between `en_us` and other locale languages, as well as when converting formulae between different spreadsheet formats (e.g. Ods to Excel). Nor is this a perfect solution, as there may still be issues when function calls have array arguments that themselves contain function calls; but it's still better than the current logic. - Fix for escaping double quotes within a formula [Issue #1971](https://github.com/PHPOffice/PhpSpreadsheet/issues/1971) [PR #2651](https://github.com/PHPOffice/PhpSpreadsheet/pull/2651) - Change open mode for output from `wb+` to `wb` [Issue #2372](https://github.com/PHPOffice/PhpSpreadsheet/issues/2372) [PR #2657](https://github.com/PHPOffice/PhpSpreadsheet/pull/2657) - Use color palette if supplied [Issue #2499](https://github.com/PHPOffice/PhpSpreadsheet/issues/2499) [PR #2595](https://github.com/PHPOffice/PhpSpreadsheet/pull/2595) - Xls reader treat drawing offsets as int rather than float [PR #2648](https://github.com/PHPOffice/PhpSpreadsheet/pull/2648) - Handle booleans in conditional styles properly [PR #2654](https://github.com/PHPOffice/PhpSpreadsheet/pull/2654) - Fix for reading files in the root directory of a ZipFile, which should not be prefixed by relative paths ("./") as dirname($filename) does by default. - Fix invalid style of cells in empty columns with columnDimensions and rows with rowDimensions in added external sheet. [PR #2739](https://github.com/PHPOffice/PhpSpreadsheet/pull/2739) - Time Interval Formatting [Issue #2768](https://github.com/PHPOffice/PhpSpreadsheet/issues/2768) [PR #2772](https://github.com/PHPOffice/PhpSpreadsheet/pull/2772) ## 1.22.0 - 2022-02-18 ### Added - Namespacing phase 2 - styles. [PR #2471](https://github.com/PHPOffice/PhpSpreadsheet/pull/2471) - Improved support for passing of array arguments to Excel function implementations to return array results (where appropriate). [Issue #2551](https://github.com/PHPOffice/PhpSpreadsheet/issues/2551) This is the first stage in an ongoing process of adding array support to all appropriate function implementations, - Support for the Excel365 Math/Trig SEQUENCE() function [PR #2536](https://github.com/PHPOffice/PhpSpreadsheet/pull/2536) - Support for the Excel365 Math/Trig RANDARRAY() function [PR #2540](https://github.com/PHPOffice/PhpSpreadsheet/pull/2540) Note that the Spill Operator is not yet supported in the Calculation Engine; but this can still be useful for defining array constants. - Improved support for Conditional Formatting Rules [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491) - Provide support for a wider range of Conditional Formatting Rules for Xlsx Reader/Writer: - Cells Containing (cellIs) - Specific Text (containing, notContaining, beginsWith, endsWith) - Dates Occurring (all supported timePeriods) - Blanks/NoBlanks - Errors/NoErrors - Duplicates/Unique - Expression - Provision of CF Wizards (for all the above listed rule types) to help create/modify CF Rules without having to manage all the combinations of types/operators, and the complexities of formula expressions, or the text/timePeriod attributes. See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/conditional-formatting/) for details - Full support of the above CF Rules for the Xlsx Reader and Writer; even when the file being loaded has CF rules listed in the `` element for the worksheet rather than the `` element. - Provision of a CellMatcher to identify if rules are matched for a cell, and which matching style will be applied. - Improved documentation and examples, covering all supported CF rule types. - Add support for one digit decimals (FORMAT_NUMBER_0, FORMAT_PERCENTAGE_0). [PR #2525](https://github.com/PHPOffice/PhpSpreadsheet/pull/2525) - Initial work enabling Excel function implementations for handling arrays as arguments when used in "array formulae" [#2562](https://github.com/PHPOffice/PhpSpreadsheet/issues/2562) - Enable most of the Date/Time functions to accept array arguments [#2573](https://github.com/PHPOffice/PhpSpreadsheet/issues/2573) - Array ready functions - Text, Math/Trig, Statistical, Engineering and Logical [#2580](https://github.com/PHPOffice/PhpSpreadsheet/issues/2580) ### Changed - Additional Russian translations for Excel Functions (courtesy of aleks-samurai). - Improved code coverage for NumberFormat. [PR #2556](https://github.com/PHPOffice/PhpSpreadsheet/pull/2556) - Extract some methods from the Calculation Engine into dedicated classes [#2537](https://github.com/PHPOffice/PhpSpreadsheet/issues/2537) - Eliminate calls to `flattenSingleValue()` that are no longer required when we're checking for array values as arguments [#2590](https://github.com/PHPOffice/PhpSpreadsheet/issues/2590) ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fixed `ReferenceHelper@insertNewBefore` behavior when removing column before last column with null value [PR #2541](https://github.com/PHPOffice/PhpSpreadsheet/pull/2541) - Fix bug with `DOLLARDE()` and `DOLLARFR()` functions when the dollar value is negative [Issue #2578](https://github.com/PHPOffice/PhpSpreadsheet/issues/2578) [PR #2579](https://github.com/PHPOffice/PhpSpreadsheet/pull/2579) - Fix partial function name matching when translating formulae from Russian to English [Issue #2533](https://github.com/PHPOffice/PhpSpreadsheet/issues/2533) [PR #2534](https://github.com/PHPOffice/PhpSpreadsheet/pull/2534) - Various bugs related to Conditional Formatting Rules, and errors in the Xlsx Writer for Conditional Formatting [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491) - Xlsx Reader merge range fixes. [Issue #2501](https://github.com/PHPOffice/PhpSpreadsheet/issues/2501) [PR #2504](https://github.com/PHPOffice/PhpSpreadsheet/pull/2504) - Handle explicit "date" type for Cell in Xlsx Reader. [Issue #2373](https://github.com/PHPOffice/PhpSpreadsheet/issues/2373) [PR #2485](https://github.com/PHPOffice/PhpSpreadsheet/pull/2485) - Recalibrate Row/Column Dimensions after removeRow/Column. [Issue #2442](https://github.com/PHPOffice/PhpSpreadsheet/issues/2442) [PR #2486](https://github.com/PHPOffice/PhpSpreadsheet/pull/2486) - Refinement for XIRR. [Issue #2469](https://github.com/PHPOffice/PhpSpreadsheet/issues/2469) [PR #2487](https://github.com/PHPOffice/PhpSpreadsheet/pull/2487) - Xlsx Reader handle cell with non-null explicit type but null value. [Issue #2488](https://github.com/PHPOffice/PhpSpreadsheet/issues/2488) [PR #2489](https://github.com/PHPOffice/PhpSpreadsheet/pull/2489) - Xlsx Reader fix height and width for oneCellAnchorDrawings. [PR #2492](https://github.com/PHPOffice/PhpSpreadsheet/pull/2492) - Fix rounding error in NumberFormat::NUMBER_PERCENTAGE, NumberFormat::NUMBER_PERCENTAGE_00. [PR #2555](https://github.com/PHPOffice/PhpSpreadsheet/pull/2555) - Don't treat thumbnail file as xml. [Issue #2516](https://github.com/PHPOffice/PhpSpreadsheet/issues/2516) [PR #2517](https://github.com/PHPOffice/PhpSpreadsheet/pull/2517) - Eliminating Xlsx Reader warning when no sz tag for RichText. [Issue #2542](https://github.com/PHPOffice/PhpSpreadsheet/issues/2542) [PR #2550](https://github.com/PHPOffice/PhpSpreadsheet/pull/2550) - Fix Xlsx/Xls Writer handling of inline strings. [Issue #353](https://github.com/PHPOffice/PhpSpreadsheet/issues/353) [PR #2569](https://github.com/PHPOffice/PhpSpreadsheet/pull/2569) - Richtext colors were not being read correctly after namespace change [#2458](https://github.com/PHPOffice/PhpSpreadsheet/issues/2458) - Fix discrepancy between the way markdown tables are rendered in ReadTheDocs and in PHPStorm [#2520](https://github.com/PHPOffice/PhpSpreadsheet/issues/2520) - Update Russian Functions Text File [#2557](https://github.com/PHPOffice/PhpSpreadsheet/issues/2557) - Fix documentation, instantiation example [#2564](https://github.com/PHPOffice/PhpSpreadsheet/issues/2564) ## 1.21.0 - 2022-01-06 ### Added - Ability to add a picture to the background of the comment. Supports four image formats: png, jpeg, gif, bmp. New `Comment::setSizeAsBackgroundImage()` to change the size of a comment to the size of a background image. [Issue #1547](https://github.com/PHPOffice/PhpSpreadsheet/issues/1547) [PR #2422](https://github.com/PHPOffice/PhpSpreadsheet/pull/2422) - Ability to set default paper size and orientation [PR #2410](https://github.com/PHPOffice/PhpSpreadsheet/pull/2410) - Ability to extend AutoFilter to Maximum Row [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414) ### Changed - Xlsx Writer will evaluate AutoFilter only if it is as yet unevaluated, or has changed since it was last evaluated [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414) ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Rounding in `NumberFormatter` [Issue #2385](https://github.com/PHPOffice/PhpSpreadsheet/issues/2385) [PR #2399](https://github.com/PHPOffice/PhpSpreadsheet/pull/2399) - Support for themes [Issue #2075](https://github.com/PHPOffice/PhpSpreadsheet/issues/2075) [Issue #2387](https://github.com/PHPOffice/PhpSpreadsheet/issues/2387) [PR #2403](https://github.com/PHPOffice/PhpSpreadsheet/pull/2403) - Read spreadsheet with `#` in name [Issue #2405](https://github.com/PHPOffice/PhpSpreadsheet/issues/2405) [PR #2409](https://github.com/PHPOffice/PhpSpreadsheet/pull/2409) - Improve PDF support for page size and orientation [Issue #1691](https://github.com/PHPOffice/PhpSpreadsheet/issues/1691) [PR #2410](https://github.com/PHPOffice/PhpSpreadsheet/pull/2410) - Wildcard handling issues in text match [Issue #2430](https://github.com/PHPOffice/PhpSpreadsheet/issues/2430) [PR #2431](https://github.com/PHPOffice/PhpSpreadsheet/pull/2431) - Respect DataType in `insertNewBefore` [PR #2433](https://github.com/PHPOffice/PhpSpreadsheet/pull/2433) - Handle rows explicitly hidden after AutoFilter [Issue #1641](https://github.com/PHPOffice/PhpSpreadsheet/issues/1641) [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414) - Special characters in image file name [Issue #1470](https://github.com/PHPOffice/PhpSpreadsheet/issues/1470) [Issue #2415](https://github.com/PHPOffice/PhpSpreadsheet/issues/2415) [PR #2416](https://github.com/PHPOffice/PhpSpreadsheet/pull/2416) - Mpdf with very many styles [Issue #2432](https://github.com/PHPOffice/PhpSpreadsheet/issues/2432) [PR #2434](https://github.com/PHPOffice/PhpSpreadsheet/pull/2434) - Name clashes between parsed and unparsed drawings [Issue #1767](https://github.com/PHPOffice/PhpSpreadsheet/issues/1767) [Issue #2396](https://github.com/PHPOffice/PhpSpreadsheet/issues/2396) [PR #2423](https://github.com/PHPOffice/PhpSpreadsheet/pull/2423) - Fill pattern start and end colors [Issue #2441](https://github.com/PHPOffice/PhpSpreadsheet/issues/2441) [PR #2444](https://github.com/PHPOffice/PhpSpreadsheet/pull/2444) - General style specified in wrong case [Issue #2450](https://github.com/PHPOffice/PhpSpreadsheet/issues/2450) [PR #2451](https://github.com/PHPOffice/PhpSpreadsheet/pull/2451) - Null passed to `AutoFilter::setRange()` [Issue #2281](https://github.com/PHPOffice/PhpSpreadsheet/issues/2281) [PR #2454](https://github.com/PHPOffice/PhpSpreadsheet/pull/2454) - Another undefined index in Xls reader (#2470) [Issue #2463](https://github.com/PHPOffice/PhpSpreadsheet/issues/2463) [PR #2470](https://github.com/PHPOffice/PhpSpreadsheet/pull/2470) - Allow single-cell checks on conditional styles, even when the style is configured for a range of cells (#) [PR #2483](https://github.com/PHPOffice/PhpSpreadsheet/pull/2483) ## 1.20.0 - 2021-11-23 ### Added - Xlsx Writer Support for WMF Files [#2339](https://github.com/PHPOffice/PhpSpreadsheet/issues/2339) - Use standard temporary file for internal use of HTMLPurifier [#2383](https://github.com/PHPOffice/PhpSpreadsheet/issues/2383) ### Changed - Drop support for PHP 7.2, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support - Use native typing for objects that were already documented as such ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fixed null conversation for strToUpper [#2292](https://github.com/PHPOffice/PhpSpreadsheet/issues/2292) - Fixed Trying to access array offset on value of type null (Xls Reader) [#2315](https://github.com/PHPOffice/PhpSpreadsheet/issues/2315) - Don't corrupt XLSX files containing data validation [#2377](https://github.com/PHPOffice/PhpSpreadsheet/issues/2377) - Non-fixed cells were not updated if shared formula has a fixed cell [#2354](https://github.com/PHPOffice/PhpSpreadsheet/issues/2354) - Declare key of generic ArrayObject - CSV reader better support for boolean values [#2374](https://github.com/PHPOffice/PhpSpreadsheet/pull/2374) - Some ZIP file could not be read [#2376](https://github.com/PHPOffice/PhpSpreadsheet/pull/2376) - Fix regression were hyperlinks could not be read [#2391](https://github.com/PHPOffice/PhpSpreadsheet/pull/2391) - AutoFilter Improvements [#2393](https://github.com/PHPOffice/PhpSpreadsheet/pull/2393) - Don't corrupt file when using chart with fill color [#589](https://github.com/PHPOffice/PhpSpreadsheet/pull/589) - Restore imperfect array formula values in xlsx writer [#2343](https://github.com/PHPOffice/PhpSpreadsheet/pull/2343) - Restore explicit list of changes to PHPExcel migration document [#1546](https://github.com/PHPOffice/PhpSpreadsheet/issues/1546) ## 1.19.0 - 2021-10-31 ### Added - Ability to set style on named range, and validate input to setSelectedCells [Issue #2279](https://github.com/PHPOffice/PhpSpreadsheet/issues/2279) [PR #2280](https://github.com/PHPOffice/PhpSpreadsheet/pull/2280) - Process comments in Sylk file [Issue #2276](https://github.com/PHPOffice/PhpSpreadsheet/issues/2276) [PR #2277](https://github.com/PHPOffice/PhpSpreadsheet/pull/2277) - Addition of Custom Properties to Ods Writer, and 32-bit-safe timestamps for Document Properties [PR #2113](https://github.com/PHPOffice/PhpSpreadsheet/pull/2113) - Added callback to CSV reader to set user-specified defaults for various properties (especially for escape which has a poor PHP-inherited default of backslash which does not correspond with Excel) [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) - Phase 1 of better namespace handling for Xlsx, resolving many open issues [PR #2173](https://github.com/PHPOffice/PhpSpreadsheet/pull/2173) [PR #2204](https://github.com/PHPOffice/PhpSpreadsheet/pull/2204) [PR #2303](https://github.com/PHPOffice/PhpSpreadsheet/pull/2303) - Add ability to extract images if source is a URL [Issue #1997](https://github.com/PHPOffice/PhpSpreadsheet/issues/1997) [PR #2072](https://github.com/PHPOffice/PhpSpreadsheet/pull/2072) - Support for passing flags in the Reader `load()` and Writer `save()`methods, and through the IOFactory, to set behaviours [PR #2136](https://github.com/PHPOffice/PhpSpreadsheet/pull/2136) - See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-and-writing-to-file/#readerwriter-flags) for details - More flexibility in the StringValueBinder to determine what datatypes should be treated as strings [PR #2138](https://github.com/PHPOffice/PhpSpreadsheet/pull/2138) - Helper class for conversion between css size Units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`) [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) - Allow Row height and Column Width to be set using different units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`), rather than only in points or MS Excel column width units [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) - Ability to stream to an Amazon S3 bucket [Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249) - Provided a Size Helper class to validate size values (pt, px, em) [PR #1694](https://github.com/PHPOffice/PhpSpreadsheet/pull/1694) ### Changed - Nothing. ### Deprecated - PHP 8.1 will deprecate auto_detect_line_endings. As a result of this change, Csv Reader using some release after PHP8.1 will no longer be able to handle a Csv with Mac line endings. ### Removed - Nothing. ### Fixed - Unexpected format in Xlsx Timestamp [Issue #2331](https://github.com/PHPOffice/PhpSpreadsheet/issues/2331) [PR #2332](https://github.com/PHPOffice/PhpSpreadsheet/pull/2332) - Corrections for HLOOKUP [Issue #2123](https://github.com/PHPOffice/PhpSpreadsheet/issues/2123) [PR #2330](https://github.com/PHPOffice/PhpSpreadsheet/pull/2330) - Corrections for Xlsx Read Comments [Issue #2316](https://github.com/PHPOffice/PhpSpreadsheet/issues/2316) [PR #2329](https://github.com/PHPOffice/PhpSpreadsheet/pull/2329) - Lowercase Calibri font names [Issue #2273](https://github.com/PHPOffice/PhpSpreadsheet/issues/2273) [PR #2325](https://github.com/PHPOffice/PhpSpreadsheet/pull/2325) - isFormula Referencing Sheet with Space in Title [Issue #2304](https://github.com/PHPOffice/PhpSpreadsheet/issues/2304) [PR #2306](https://github.com/PHPOffice/PhpSpreadsheet/pull/2306) - Xls Reader Fatal Error due to Undefined Offset [Issue #1114](https://github.com/PHPOffice/PhpSpreadsheet/issues/1114) [PR #2308](https://github.com/PHPOffice/PhpSpreadsheet/pull/2308) - Permit Csv Reader delimiter to be set to null [Issue #2287](https://github.com/PHPOffice/PhpSpreadsheet/issues/2287) [PR #2288](https://github.com/PHPOffice/PhpSpreadsheet/pull/2288) - Csv Reader did not handle booleans correctly [PR #2232](https://github.com/PHPOffice/PhpSpreadsheet/pull/2232) - Problems when deleting sheet with local defined name [Issue #2266](https://github.com/PHPOffice/PhpSpreadsheet/issues/2266) [PR #2284](https://github.com/PHPOffice/PhpSpreadsheet/pull/2284) - Worksheet passwords were not always handled correctly [Issue #1897](https://github.com/PHPOffice/PhpSpreadsheet/issues/1897) [PR #2197](https://github.com/PHPOffice/PhpSpreadsheet/pull/2197) - Gnumeric Reader will now distinguish between Created and Modified timestamp [PR #2133](https://github.com/PHPOffice/PhpSpreadsheet/pull/2133) - Xls Reader will now handle MACCENTRALEUROPE with or without hyphen [Issue #549](https://github.com/PHPOffice/PhpSpreadsheet/issues/549) [PR #2213](https://github.com/PHPOffice/PhpSpreadsheet/pull/2213) - Tweaks to input file validation [Issue #1718](https://github.com/PHPOffice/PhpSpreadsheet/issues/1718) [PR #2217](https://github.com/PHPOffice/PhpSpreadsheet/pull/2217) - Html Reader did not handle comments correctly [Issue #2234](https://github.com/PHPOffice/PhpSpreadsheet/issues/2234) [PR #2235](https://github.com/PHPOffice/PhpSpreadsheet/pull/2235) - Apache OpenOffice Uses Unexpected Case for General format [Issue #2239](https://github.com/PHPOffice/PhpSpreadsheet/issues/2239) [PR #2242](https://github.com/PHPOffice/PhpSpreadsheet/pull/2242) - Problems with fraction formatting [Issue #2253](https://github.com/PHPOffice/PhpSpreadsheet/issues/2253) [PR #2254](https://github.com/PHPOffice/PhpSpreadsheet/pull/2254) - Xlsx Reader had problems reading file with no styles.xml or empty styles.xml [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) [PR #2247](https://github.com/PHPOffice/PhpSpreadsheet/pull/2247) - Xlsx Reader did not read Data Validation flags correctly [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225) - Better handling of empty arguments in Calculation engine [PR #2143](https://github.com/PHPOffice/PhpSpreadsheet/pull/2143) - Many fixes for Autofilter [Issue #2216](https://github.com/PHPOffice/PhpSpreadsheet/issues/2216) [PR #2141](https://github.com/PHPOffice/PhpSpreadsheet/pull/2141) [PR #2162](https://github.com/PHPOffice/PhpSpreadsheet/pull/2162) [PR #2218](https://github.com/PHPOffice/PhpSpreadsheet/pull/2218) - Locale generator will now use Unix line endings even on Windows [Issue #2172](https://github.com/PHPOffice/PhpSpreadsheet/issues/2172) [PR #2174](https://github.com/PHPOffice/PhpSpreadsheet/pull/2174) - Support differences in implementation of Text functions between Excel/Ods/Gnumeric [PR #2151](https://github.com/PHPOffice/PhpSpreadsheet/pull/2151) - Fixes to places where PHP8.1 enforces new or previously unenforced restrictions [PR #2137](https://github.com/PHPOffice/PhpSpreadsheet/pull/2137) [PR #2191](https://github.com/PHPOffice/PhpSpreadsheet/pull/2191) [PR #2231](https://github.com/PHPOffice/PhpSpreadsheet/pull/2231) - Clone for HashTable was incorrect [PR #2130](https://github.com/PHPOffice/PhpSpreadsheet/pull/2130) - Xlsx Reader was not evaluating Document Security Lock correctly [PR #2128](https://github.com/PHPOffice/PhpSpreadsheet/pull/2128) - Error in COUPNCD handling end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119) - Xls Writer Parser did not handle concatenation operator correctly [PR #2080](https://github.com/PHPOffice/PhpSpreadsheet/pull/2080) - Xlsx Writer did not handle boolean false correctly [Issue #2082](https://github.com/PHPOffice/PhpSpreadsheet/issues/2082) [PR #2087](https://github.com/PHPOffice/PhpSpreadsheet/pull/2087) - SUM needs to treat invalid strings differently depending on whether they come from a cell or are used as literals [Issue #2042](https://github.com/PHPOffice/PhpSpreadsheet/issues/2042) [PR #2045](https://github.com/PHPOffice/PhpSpreadsheet/pull/2045) - Html reader could have set illegal coordinates when dealing with embedded tables [Issue #2029](https://github.com/PHPOffice/PhpSpreadsheet/issues/2029) [PR #2032](https://github.com/PHPOffice/PhpSpreadsheet/pull/2032) - Documentation for printing gridlines was wrong [PR #2188](https://github.com/PHPOffice/PhpSpreadsheet/pull/2188) - Return Value Error - DatabaseAbstruct::buildQuery() return null but must be string [Issue #2158](https://github.com/PHPOffice/PhpSpreadsheet/issues/2158) [PR #2160](https://github.com/PHPOffice/PhpSpreadsheet/pull/2160) - Xlsx reader not recognize data validations that references another sheet [Issue #1432](https://github.com/PHPOffice/PhpSpreadsheet/issues/1432) [Issue #2149](https://github.com/PHPOffice/PhpSpreadsheet/issues/2149) [PR #2150](https://github.com/PHPOffice/PhpSpreadsheet/pull/2150) [PR #2265](https://github.com/PHPOffice/PhpSpreadsheet/pull/2265) - Don't calculate cell width for autosize columns if a cell contains a null or empty string value [Issue #2165](https://github.com/PHPOffice/PhpSpreadsheet/issues/2165) [PR #2167](https://github.com/PHPOffice/PhpSpreadsheet/pull/2167) - Allow negative interest rate values in a number of the Financial functions (`PPMT()`, `PMT()`, `FV()`, `PV()`, `NPER()`, etc) [Issue #2163](https://github.com/PHPOffice/PhpSpreadsheet/issues/2163) [PR #2164](https://github.com/PHPOffice/PhpSpreadsheet/pull/2164) - Xls Reader changing grey background to black in Excel template [Issue #2147](https://github.com/PHPOffice/PhpSpreadsheet/issues/2147) [PR #2156](https://github.com/PHPOffice/PhpSpreadsheet/pull/2156) - Column width and Row height styles in the Html Reader when the value includes a unit of measure [Issue #2145](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145). - Data Validation flags not set correctly when reading XLSX files [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225) - Reading XLSX files without styles.xml throws an exception [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) - Improved performance of `Style::applyFromArray()` when applied to several cells [PR #1785](https://github.com/PHPOffice/PhpSpreadsheet/issues/1785). - Improve XLSX parsing speed if no readFilter is applied (again) - [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772) ## 1.18.0 - 2021-05-31 ### Added - Enhancements to CSV Reader, allowing options to be set when using `IOFactory::load()` with a callback to set delimiter, enclosure, charset etc [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) - See [documentation](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md#csv-comma-separated-values) for details. - Implemented basic AutoFiltering for Ods Reader and Writer [PR #2053](https://github.com/PHPOffice/PhpSpreadsheet/pull/2053) - Implemented basic AutoFiltering for Gnumeric Reader [PR #2055](https://github.com/PHPOffice/PhpSpreadsheet/pull/2055) - Improved support for Row and Column ranges in formulae [Issue #1755](https://github.com/PHPOffice/PhpSpreadsheet/issues/1755) [PR #2028](https://github.com/PHPOffice/PhpSpreadsheet/pull/2028) - Implemented URLENCODE() Web Function - Implemented the CHITEST(), CHISQ.DIST() and CHISQ.INV() and equivalent Statistical functions, for both left- and right-tailed distributions. - Support for ActiveSheet and SelectedCells in the ODS Reader and Writer [PR #1908](https://github.com/PHPOffice/PhpSpreadsheet/pull/1908) - Support for notContainsText Conditional Style in xlsx [Issue #984](https://github.com/PHPOffice/PhpSpreadsheet/issues/984) ### Changed - Use of `nb` rather than `no` as the locale code for Norsk Bokmål. ### Deprecated - All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. ### Removed - Use of `nb` rather than `no` as the locale language code for Norsk Bokmål. ### Fixed - Fixed error in COUPNCD() calculation for end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) - [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119) - Resolve default values when a null argument is passed for HLOOKUP(), VLOOKUP() and ADDRESS() functions [Issue #2120](https://github.com/PHPOffice/PhpSpreadsheet/issues/2120) - [PR #2121](https://github.com/PHPOffice/PhpSpreadsheet/pull/2121) - Fixed incorrect R1C1 to A1 subtraction formula conversion (`R[-2]C-R[2]C`) [Issue #2076](https://github.com/PHPOffice/PhpSpreadsheet/pull/2076) [PR #2086](https://github.com/PHPOffice/PhpSpreadsheet/pull/2086) - Correctly handle absolute A1 references when converting to R1C1 format [PR #2060](https://github.com/PHPOffice/PhpSpreadsheet/pull/2060) - Correct default fill style for conditional without a pattern defined [Issue #2035](https://github.com/PHPOffice/PhpSpreadsheet/issues/2035) [PR #2050](https://github.com/PHPOffice/PhpSpreadsheet/pull/2050) - Fixed issue where array key check for existince before accessing arrays in Xlsx.php [PR #1970](https://github.com/PHPOffice/PhpSpreadsheet/pull/1970) - Fixed issue with quoted strings in number format mask rendered with toFormattedString() [Issue 1972#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1972) [PR #1978](https://github.com/PHPOffice/PhpSpreadsheet/pull/1978) - Fixed issue with percentage formats in number format mask rendered with toFormattedString() [Issue 1929#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1929) [PR #1928](https://github.com/PHPOffice/PhpSpreadsheet/pull/1928) - Fixed issue with _ spacing character in number format mask corrupting output from toFormattedString() [Issue 1924#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1924) [PR #1927](https://github.com/PHPOffice/PhpSpreadsheet/pull/1927) - Fix for [Issue #1887](https://github.com/PHPOffice/PhpSpreadsheet/issues/1887) - Lose Track of Selected Cells After Save - Fixed issue with Xlsx@listWorksheetInfo not returning any data - Fixed invalid arguments triggering mb_substr() error in LEFT(), MID() and RIGHT() text functions [Issue #640](https://github.com/PHPOffice/PhpSpreadsheet/issues/640) - Fix for [Issue #1916](https://github.com/PHPOffice/PhpSpreadsheet/issues/1916) - Invalid signature check for XML files - Fix change in `Font::setSize()` behavior for PHP8 [PR #2100](https://github.com/PHPOffice/PhpSpreadsheet/pull/2100) ## 1.17.1 - 2021-03-01 ### Added - Implementation of the Excel `AVERAGEIFS()` functions as part of a restructuring of Database functions and Conditional Statistical functions. - Support for date values and percentages in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1875](https://github.com/PHPOffice/PhpSpreadsheet/pull/1875) - Support for booleans, and for wildcard text search in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1876](https://github.com/PHPOffice/PhpSpreadsheet/pull/1876) - Implemented DataBar for conditional formatting in Xlsx, providing read/write and creation of (type, value, direction, fills, border, axis position, color settings) as DataBar options in Excel. [#1754](https://github.com/PHPOffice/PhpSpreadsheet/pull/1754) - Alignment for ODS Writer [#1796](https://github.com/PHPOffice/PhpSpreadsheet/issues/1796) - Basic implementation of the PERMUTATIONA() Statistical Function ### Changed - Formula functions that previously called PHP functions directly are now processed through the Excel Functions classes; resolving issues with PHP8 stricter typing. [#1789](https://github.com/PHPOffice/PhpSpreadsheet/issues/1789) The following MathTrig functions are affected: `ABS()`, `ACOS()`, `ACOSH()`, `ASIN()`, `ASINH()`, `ATAN()`, `ATANH()`, `COS()`, `COSH()`, `DEGREES()` (rad2deg), `EXP()`, `LN()` (log), `LOG10()`, `RADIANS()` (deg2rad), `SIN()`, `SINH()`, `SQRT()`, `TAN()`, `TANH()`. One TextData function is also affected: `REPT()` (str_repeat). - `formatAsDate` correctly matches language metadata, reverting c55272e - Formulae that previously crashed on sub function call returning excel error value now return said value. The following functions are affected `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, `AMORDEGRC()`. - Adapt some function error return value to match excel's error. The following functions are affected `PPMT()`, `IPMT()`. ### Deprecated - Calling many of the Excel formula functions directly rather than through the Calculation Engine. The logic for these Functions is now being moved out of the categorised `Database`, `DateTime`, `Engineering`, `Financial`, `Logical`, `LookupRef`, `MathTrig`, `Statistical`, `TextData` and `Web` classes into small, dedicated classes for individual functions or related groups of functions. This makes the logic in these classes easier to maintain; and will reduce the memory footprint required to execute formulae when calling these functions. ### Removed - Nothing. ### Fixed - Avoid Duplicate Titles When Reading Multiple HTML Files.[Issue #1823](https://github.com/PHPOffice/PhpSpreadsheet/issues/1823) [PR #1829](https://github.com/PHPOffice/PhpSpreadsheet/pull/1829) - Fixed issue with Worksheet's `getCell()` method when trying to get a cell by defined name. [#1858](https://github.com/PHPOffice/PhpSpreadsheet/issues/1858) - Fix possible endless loop in NumberFormat Masks [#1792](https://github.com/PHPOffice/PhpSpreadsheet/issues/1792) - Fix problem resulting from literal dot inside quotes in number format masks [PR #1830](https://github.com/PHPOffice/PhpSpreadsheet/pull/1830) - Resolve Google Sheets Xlsx charts issue. Google Sheets uses oneCellAnchor positioning and does not include *Cache values in the exported Xlsx [PR #1761](https://github.com/PHPOffice/PhpSpreadsheet/pull/1761) - Fix for Xlsx Chart axis titles mapping to correct X or Y axis label when only one is present [PR #1760](https://github.com/PHPOffice/PhpSpreadsheet/pull/1760) - Fix For Null Exception on ODS Read of Page Settings. [#1772](https://github.com/PHPOffice/PhpSpreadsheet/issues/1772) - Fix Xlsx reader overriding manually set number format with builtin number format [PR #1805](https://github.com/PHPOffice/PhpSpreadsheet/pull/1805) - Fix Xlsx reader cell alignment [PR #1710](https://github.com/PHPOffice/PhpSpreadsheet/pull/1710) - Fix for not yet implemented data-types in Open Document writer [Issue #1674](https://github.com/PHPOffice/PhpSpreadsheet/issues/1674) - Fix XLSX reader when having a corrupt numeric cell data type [PR #1664](https://github.com/phpoffice/phpspreadsheet/pull/1664) - Fix on `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, `AMORDEGRC()` usage. When those functions called one of `YEARFRAC()`, `PPMT()`, `IPMT()` and they would get back an error value (represented as a string), trying to use numeral operands (`+`, `/`, `-`, `*`) on said return value and a number (`float or `int`) would fail. ## 1.16.0 - 2020-12-31 ### Added - CSV Reader - Best Guess for Encoding, and Handle Null-string Escape [#1647](https://github.com/PHPOffice/PhpSpreadsheet/issues/1647) ### Changed - Updated the CONVERT() function to support all current MS Excel categories and Units of Measure. ### Deprecated - All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. ### Removed - Nothing. ### Fixed - Fixed issue with absolute path in worksheets' Target [PR #1769](https://github.com/PHPOffice/PhpSpreadsheet/pull/1769) - Fix for Xls Reader when SST has a bad length [#1592](https://github.com/PHPOffice/PhpSpreadsheet/issues/1592) - Resolve Xlsx loader issue whe hyperlinks don't have a destination - Resolve issues when printer settings resources IDs clash with drawing IDs - Resolve issue with SLK long filenames [#1612](https://github.com/PHPOffice/PhpSpreadsheet/issues/1612) - ROUNDUP and ROUNDDOWN return incorrect results for values of 0 [#1627](https://github.com/phpoffice/phpspreadsheet/pull/1627) - Apply Column and Row Styles to Existing Cells [#1712](https://github.com/PHPOffice/PhpSpreadsheet/issues/1712) [PR #1721](https://github.com/PHPOffice/PhpSpreadsheet/pull/1721) - Resolve issues with defined names where worksheet doesn't exist (#1686)[https://github.com/PHPOffice/PhpSpreadsheet/issues/1686] and [#1723](https://github.com/PHPOffice/PhpSpreadsheet/issues/1723) - [PR #1742](https://github.com/PHPOffice/PhpSpreadsheet/pull/1742) - Fix for issue [#1735](https://github.com/PHPOffice/PhpSpreadsheet/issues/1735) Incorrect activeSheetIndex after RemoveSheetByIndex - [PR #1743](https://github.com/PHPOffice/PhpSpreadsheet/pull/1743) - Ensure that the list of shared formulae is maintained when an xlsx file is chunked with readFilter[Issue #169](https://github.com/PHPOffice/PhpSpreadsheet/issues/1669). - Fix for notice during accessing "cached magnification factor" offset [#1354](https://github.com/PHPOffice/PhpSpreadsheet/pull/1354) - Fix compatibility with ext-gd on php 8 ### Security Fix (CVE-2020-7776) - Prevent XSS through cell comments in the HTML Writer. ## 1.15.0 - 2020-10-11 ### Added - Implemented Page Order for Xlsx and Xls Readers, and provided Page Settings (Orientation, Scale, Horizontal/Vertical Centering, Page Order, Margins) support for Ods, Gnumeric and Xls Readers [#1559](https://github.com/PHPOffice/PhpSpreadsheet/pull/1559) - Implementation of the Excel `LOGNORM.DIST()`, `NORM.S.DIST()`, `GAMMA()` and `GAUSS()` functions. [#1588](https://github.com/PHPOffice/PhpSpreadsheet/pull/1588) - Named formula implementation, and improved handling of Defined Names generally [#1535](https://github.com/PHPOffice/PhpSpreadsheet/pull/1535) - Defined Names are now case-insensitive - Distinction between named ranges and named formulae - Correct handling of union and intersection operators in named ranges - Correct evaluation of named range operators in calculations - fix resolution of relative named range values in the calculation engine; previously all named range values had been treated as absolute. - Calculation support for named formulae - Support for nested ranges and formulae (named ranges and formulae that reference other named ranges/formulae) in calculations - Introduction of a helper to convert address formats between R1C1 and A1 (and the reverse) - Proper support for both named ranges and named formulae in all appropriate Readers - **Xlsx** (Previously only simple named ranges were supported) - **Xls** (Previously only simple named ranges were supported) - **Gnumeric** (Previously neither named ranges nor formulae were supported) - **Ods** (Previously neither named ranges nor formulae were supported) - **Xml** (Previously neither named ranges nor formulae were supported) - Proper support for named ranges and named formulae in all appropriate Writers - **Xlsx** (Previously only simple named ranges were supported) - **Xls** (Previously neither named ranges nor formulae were supported) - Still not supported, but some parser issues resolved that previously failed to differentiate between a defined name and a function name - **Ods** (Previously neither named ranges nor formulae were supported) - Support for PHP 8.0 ### Changed - Improve Coverage for ODS Reader [#1545](https://github.com/phpoffice/phpspreadsheet/pull/1545) - Named formula implementation, and improved handling of Defined Names generally [#1535](https://github.com/PHPOffice/PhpSpreadsheet/pull/1535) - fix resolution of relative named range values in the calculation engine; previously all named range values had been treated as absolute. - Drop $this->spreadSheet null check from Xlsx Writer [#1646](https://github.com/phpoffice/phpspreadsheet/pull/1646) - Improving Coverage for Excel2003 XML Reader [#1557](https://github.com/phpoffice/phpspreadsheet/pull/1557) ### Deprecated - **IMPORTANT NOTE:** This Introduces a **BC break** in the handling of named ranges. Previously, a named range cell reference of `B2` would be treated identically to a named range cell reference of `$B2` or `B$2` or `$B$2` because the calculation engine treated then all as absolute references. These changes "fix" that, so the calculation engine now handles relative references in named ranges correctly. This change that resolves previously incorrect behaviour in the calculation may affect users who have dynamically defined named ranges using relative references when they should have used absolute references. ### Removed - Nothing. ### Fixed - PrintArea causes exception [#1544](https://github.com/phpoffice/phpspreadsheet/pull/1544) - Calculation/DateTime Failure With PHP8 [#1661](https://github.com/phpoffice/phpspreadsheet/pull/1661) - Reader/Gnumeric Failure with PHP8 [#1662](https://github.com/phpoffice/phpspreadsheet/pull/1662) - ReverseSort bug, exposed but not caused by PHP8 [#1660](https://github.com/phpoffice/phpspreadsheet/pull/1660) - Bug setting Superscript/Subscript to false [#1567](https://github.com/phpoffice/phpspreadsheet/pull/1567) ## 1.14.1 - 2020-07-19 ### Added - nothing ### Fixed - WEBSERVICE is HTTP client agnostic and must be configured via `Settings::setHttpClient()` [#1562](https://github.com/PHPOffice/PhpSpreadsheet/issues/1562) - Borders were not complete on rowspanned columns using HTML reader [#1473](https://github.com/PHPOffice/PhpSpreadsheet/pull/1473) ### Changed ## 1.14.0 - 2020-06-29 ### Added - Add support for IFS() logical function [#1442](https://github.com/PHPOffice/PhpSpreadsheet/pull/1442) - Add Cell Address Helper to provide conversions between the R1C1 and A1 address formats [#1558](https://github.com/PHPOffice/PhpSpreadsheet/pull/1558) - Add ability to edit Html/Pdf before saving [#1499](https://github.com/PHPOffice/PhpSpreadsheet/pull/1499) - Add ability to set codepage explicitly for BIFF5 [#1018](https://github.com/PHPOffice/PhpSpreadsheet/issues/1018) - Added support for the WEBSERVICE function [#1409](https://github.com/PHPOffice/PhpSpreadsheet/pull/1409) ### Fixed - Resolve evaluation of utf-8 named ranges in calculation engine [#1522](https://github.com/PHPOffice/PhpSpreadsheet/pull/1522) - Fix HLOOKUP on single row [#1512](https://github.com/PHPOffice/PhpSpreadsheet/pull/1512) - Fix MATCH when comparing different numeric types [#1521](https://github.com/PHPOffice/PhpSpreadsheet/pull/1521) - Fix exact MATCH on ranges with empty cells [#1520](https://github.com/PHPOffice/PhpSpreadsheet/pull/1520) - Fix for Issue [#1516](https://github.com/PHPOffice/PhpSpreadsheet/issues/1516) (Cloning worksheet makes corrupted Xlsx) [#1530](https://github.com/PHPOffice/PhpSpreadsheet/pull/1530) - Fix For Issue [#1509](https://github.com/PHPOffice/PhpSpreadsheet/issues/1509) (Can not set empty enclosure for CSV) [#1518](https://github.com/PHPOffice/PhpSpreadsheet/pull/1518) - Fix for Issue [#1505](https://github.com/PHPOffice/PhpSpreadsheet/issues/1505) (TypeError : Argument 4 passed to PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeAttributeIf() must be of the type string) [#1525](https://github.com/PHPOffice/PhpSpreadsheet/pull/1525) - Fix for Issue [#1495](https://github.com/PHPOffice/PhpSpreadsheet/issues/1495) (Sheet index being changed when multiple sheets are used in formula) [#1500]((https://github.com/PHPOffice/PhpSpreadsheet/pull/1500)) - Fix for Issue [#1533](https://github.com/PHPOffice/PhpSpreadsheet/issues/1533) (A reference to a cell containing a string starting with "#" leads to errors in the generated xlsx.) [#1534](https://github.com/PHPOffice/PhpSpreadsheet/pull/1534) - Xls Writer - Correct Timestamp Bug [#1493](https://github.com/PHPOffice/PhpSpreadsheet/pull/1493) - Don't ouput row and columns without any cells in HTML writer [#1235](https://github.com/PHPOffice/PhpSpreadsheet/issues/1235) ## 1.13.0 - 2020-05-31 ### Added - Support writing to streams in all writers [#1292](https://github.com/PHPOffice/PhpSpreadsheet/issues/1292) - Support CSV files with data wrapping a lot of lines [#1468](https://github.com/PHPOffice/PhpSpreadsheet/pull/1468) - Support protection of worksheet by a specific hash algorithm [#1485](https://github.com/PHPOffice/PhpSpreadsheet/pull/1485) ### Fixed - Fix Chart samples by updating chart parameter from 0 to DataSeries::EMPTY_AS_GAP [#1448](https://github.com/PHPOffice/PhpSpreadsheet/pull/1448) - Fix return type in docblock for the Cells::get() [#1398](https://github.com/PHPOffice/PhpSpreadsheet/pull/1398) - Fix RATE, PRICE, XIRR, and XNPV Functions [#1456](https://github.com/PHPOffice/PhpSpreadsheet/pull/1456) - Save Excel 2010+ functions properly in XLSX [#1461](https://github.com/PHPOffice/PhpSpreadsheet/pull/1461) - Several improvements in HTML writer [#1464](https://github.com/PHPOffice/PhpSpreadsheet/pull/1464) - Fix incorrect behaviour when saving XLSX file with drawings [#1462](https://github.com/PHPOffice/PhpSpreadsheet/pull/1462), - Fix Crash while trying setting a cell the value "123456\n" [#1476](https://github.com/PHPOffice/PhpSpreadsheet/pull/1481) - Improved DATEDIF() function and reduced errors for Y and YM units [#1466](https://github.com/PHPOffice/PhpSpreadsheet/pull/1466) - Stricter typing for mergeCells [#1494](https://github.com/PHPOffice/PhpSpreadsheet/pull/1494) ### Changed - Drop support for PHP 7.1, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support - Drop partial migration tool in favor of complete migration via RectorPHP [#1445](https://github.com/PHPOffice/PhpSpreadsheet/issues/1445) - Limit composer package to `src/` [#1424](https://github.com/PHPOffice/PhpSpreadsheet/pull/1424) ## 1.12.0 - 2020-04-27 ### Added - Improved the ARABIC function to also handle short-hand roman numerals - Added support for the FLOOR.MATH and FLOOR.PRECISE functions [#1351](https://github.com/PHPOffice/PhpSpreadsheet/pull/1351) ### Fixed - Fix ROUNDUP and ROUNDDOWN for floating-point rounding error [#1404](https://github.com/PHPOffice/PhpSpreadsheet/pull/1404) - Fix ROUNDUP and ROUNDDOWN for negative number [#1417](https://github.com/PHPOffice/PhpSpreadsheet/pull/1417) - Fix loading styles from vmlDrawings when containing whitespace [#1347](https://github.com/PHPOffice/PhpSpreadsheet/issues/1347) - Fix incorrect behavior when removing last row [#1365](https://github.com/PHPOffice/PhpSpreadsheet/pull/1365) - MATCH with a static array should return the position of the found value based on the values submitted [#1332](https://github.com/PHPOffice/PhpSpreadsheet/pull/1332) - Fix Xlsx Reader's handling of undefined fill color [#1353](https://github.com/PHPOffice/PhpSpreadsheet/pull/1353) ## 1.11.0 - 2020-03-02 ### Added - Added support for the BASE function - Added support for the ARABIC function - Conditionals - Extend Support for (NOT)CONTAINSBLANKS [#1278](https://github.com/PHPOffice/PhpSpreadsheet/pull/1278) ### Fixed - Handle Error in Formula Processing Better for Xls [#1267](https://github.com/PHPOffice/PhpSpreadsheet/pull/1267) - Handle ConditionalStyle NumberFormat When Reading Xlsx File [#1296](https://github.com/PHPOffice/PhpSpreadsheet/pull/1296) - Fix Xlsx Writer's handling of decimal commas [#1282](https://github.com/PHPOffice/PhpSpreadsheet/pull/1282) - Fix for issue by removing test code mistakenly left in [#1328](https://github.com/PHPOffice/PhpSpreadsheet/pull/1328) - Fix for Xls writer wrong selected cells and active sheet [#1256](https://github.com/PHPOffice/PhpSpreadsheet/pull/1256) - Fix active cell when freeze pane is used [#1323](https://github.com/PHPOffice/PhpSpreadsheet/pull/1323) - Fix XLSX file loading with autofilter containing '$' [#1326](https://github.com/PHPOffice/PhpSpreadsheet/pull/1326) - PHPDoc - Use `@return $this` for fluent methods [#1362](https://github.com/PHPOffice/PhpSpreadsheet/pull/1362) ## 1.10.1 - 2019-12-02 ### Changed - PHP 7.4 compatibility ### Fixed - FLOOR() function accept negative number and negative significance [#1245](https://github.com/PHPOffice/PhpSpreadsheet/pull/1245) - Correct column style even when using rowspan [#1249](https://github.com/PHPOffice/PhpSpreadsheet/pull/1249) - Do not confuse defined names and cell refs [#1263](https://github.com/PHPOffice/PhpSpreadsheet/pull/1263) - XLSX reader/writer keep decimal for floats with a zero decimal part [#1262](https://github.com/PHPOffice/PhpSpreadsheet/pull/1262) - ODS writer prevent invalid numeric value if locale decimal separator is comma [#1268](https://github.com/PHPOffice/PhpSpreadsheet/pull/1268) - Xlsx writer actually writes plotVisOnly and dispBlanksAs from chart properties [#1266](https://github.com/PHPOffice/PhpSpreadsheet/pull/1266) ## 1.10.0 - 2019-11-18 ### Changed - Change license from LGPL 2.1 to MIT [#140](https://github.com/PHPOffice/PhpSpreadsheet/issues/140) ### Added - Implementation of IFNA() logical function - Support "showZeros" worksheet option to change how Excel shows and handles "null" values returned from a calculation - Allow HTML Reader to accept HTML as a string into an existing spreadsheet [#1212](https://github.com/PHPOffice/PhpSpreadsheet/pull/1212) ### Fixed - IF implementation properly handles the value `#N/A` [#1165](https://github.com/PHPOffice/PhpSpreadsheet/pull/1165) - Formula Parser: Wrong line count for stuff like "MyOtherSheet!A:D" [#1215](https://github.com/PHPOffice/PhpSpreadsheet/issues/1215) - Call garbage collector after removing a column to prevent stale cached values - Trying to remove a column that doesn't exist deletes the latest column - Keep big integer as integer instead of lossely casting to float [#874](https://github.com/PHPOffice/PhpSpreadsheet/pull/874) - Fix branch pruning handling of non boolean conditions [#1167](https://github.com/PHPOffice/PhpSpreadsheet/pull/1167) - Fix ODS Reader when no DC namespace are defined [#1182](https://github.com/PHPOffice/PhpSpreadsheet/pull/1182) - Fixed Functions->ifCondition for allowing <> and empty condition [#1206](https://github.com/PHPOffice/PhpSpreadsheet/pull/1206) - Validate XIRR inputs and return correct error values [#1120](https://github.com/PHPOffice/PhpSpreadsheet/issues/1120) - Allow to read xlsx files with exotic workbook names like "workbook2.xml" [#1183](https://github.com/PHPOffice/PhpSpreadsheet/pull/1183) ## 1.9.0 - 2019-08-17 ### Changed - Drop support for PHP 5.6 and 7.0, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support ### Added - When <br> appears in a table cell, set the cell to wrap [#1071](https://github.com/PHPOffice/PhpSpreadsheet/issues/1071) and [#1070](https://github.com/PHPOffice/PhpSpreadsheet/pull/1070) - Add MAXIFS, MINIFS, COUNTIFS and Remove MINIF, MAXIF [#1056](https://github.com/PHPOffice/PhpSpreadsheet/issues/1056) - HLookup needs an ordered list even if range_lookup is set to false [#1055](https://github.com/PHPOffice/PhpSpreadsheet/issues/1055) and [#1076](https://github.com/PHPOffice/PhpSpreadsheet/pull/1076) - Improve performance of IF function calls via ranch pruning to avoid resolution of every branches [#844](https://github.com/PHPOffice/PhpSpreadsheet/pull/844) - MATCH function supports `*?~` Excel functionality, when match_type=0 [#1116](https://github.com/PHPOffice/PhpSpreadsheet/issues/1116) - Allow HTML Reader to accept HTML as a string [#1136](https://github.com/PHPOffice/PhpSpreadsheet/pull/1136) ### Fixed - Fix to AVERAGEIF() function when called with a third argument - Eliminate duplicate fill none style entries [#1066](https://github.com/PHPOffice/PhpSpreadsheet/issues/1066) - Fix number format masks containing literal (non-decimal point) dots [#1079](https://github.com/PHPOffice/PhpSpreadsheet/issues/1079) - Fix number format masks containing named colours that were being misinterpreted as date formats; and add support for masks that fully replace the value with a full text string [#1009](https://github.com/PHPOffice/PhpSpreadsheet/issues/1009) - Stricter-typed comparison testing in COUNTIF() and COUNTIFS() evaluation [#1046](https://github.com/PHPOffice/PhpSpreadsheet/issues/1046) - COUPNUM should not return zero when settlement is in the last period [#1020](https://github.com/PHPOffice/PhpSpreadsheet/issues/1020) and [#1021](https://github.com/PHPOffice/PhpSpreadsheet/pull/1021) - Fix handling of named ranges referencing sheets with spaces or "!" in their title - Cover `getSheetByName()` with tests for name with quote and spaces [#739](https://github.com/PHPOffice/PhpSpreadsheet/issues/739) - Best effort to support invalid colspan values in HTML reader - [#878](https://github.com/PHPOffice/PhpSpreadsheet/pull/878) - Fixes incorrect rows deletion [#868](https://github.com/PHPOffice/PhpSpreadsheet/issues/868) - MATCH function fix (value search by type, stop search when match_type=-1 and unordered element encountered) [#1116](https://github.com/PHPOffice/PhpSpreadsheet/issues/1116) - Fix `getCalculatedValue()` error with more than two INDIRECT [#1115](https://github.com/PHPOffice/PhpSpreadsheet/pull/1115) - Writer\Html did not hide columns [#985](https://github.com/PHPOffice/PhpSpreadsheet/pull/985) ## 1.8.2 - 2019-07-08 ### Fixed - Uncaught error when opening ods file and properties aren't defined [#1047](https://github.com/PHPOffice/PhpSpreadsheet/issues/1047) - Xlsx Reader Cell datavalidations bug [#1052](https://github.com/PHPOffice/PhpSpreadsheet/pull/1052) ## 1.8.1 - 2019-07-02 ### Fixed - Allow nullable theme for Xlsx Style Reader class [#1043](https://github.com/PHPOffice/PhpSpreadsheet/issues/1043) ## 1.8.0 - 2019-07-01 ### Security Fix (CVE-2019-12331) - Detect double-encoded xml in the Security scanner, and reject as suspicious. - This change also broadens the scope of the `libxml_disable_entity_loader` setting when reading XML-based formats, so that it is enabled while the xml is being parsed and not simply while it is loaded. On some versions of PHP, this can cause problems because it is not thread-safe, and can affect other PHP scripts running on the same server. This flag is set to true when instantiating a loader, and back to its original setting when the Reader is no longer in scope, or manually unset. - Provide a check to identify whether libxml_disable_entity_loader is thread-safe or not. `XmlScanner::threadSafeLibxmlDisableEntityLoaderAvailability()` - Provide an option to disable the libxml_disable_entity_loader call through settings. This is not recommended as it reduces the security of the XML-based readers, and should only be used if you understand the consequences and have no other choice. ### Added - Added support for the SWITCH function [#963](https://github.com/PHPOffice/PhpSpreadsheet/issues/963) and [#983](https://github.com/PHPOffice/PhpSpreadsheet/pull/983) - Add accounting number format style [#974](https://github.com/PHPOffice/PhpSpreadsheet/pull/974) ### Fixed - Whitelist `tsv` extension when opening CSV files [#429](https://github.com/PHPOffice/PhpSpreadsheet/issues/429) - Fix a SUMIF warning with some versions of PHP when having different length of arrays provided as input [#873](https://github.com/PHPOffice/PhpSpreadsheet/pull/873) - Fix incorrectly handled backslash-escaped space characters in number format ## 1.7.0 - 2019-05-26 - Added support for inline styles in Html reader (borders, alignment, width, height) - QuotedText cells no longer treated as formulae if the content begins with a `=` - Clean handling for DDE in formulae ### Fixed - Fix handling for escaped enclosures and new lines in CSV Separator Inference - Fix MATCH an error was appearing when comparing strings against 0 (always true) - Fix wrong calculation of highest column with specified row [#700](https://github.com/PHPOffice/PhpSpreadsheet/issues/700) - Fix VLOOKUP - Fix return type hint ## 1.6.0 - 2019-01-02 ### Added - Refactored Matrix Functions to use external Matrix library - Possibility to specify custom colors of values for pie and donut charts [#768](https://github.com/PHPOffice/PhpSpreadsheet/pull/768) ### Fixed - Improve XLSX parsing speed if no readFilter is applied [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772) - Fix column names if read filter calls in XLSX reader skip columns [#777](https://github.com/PHPOffice/PhpSpreadsheet/pull/777) - XLSX reader can now ignore blank cells, using the setReadEmptyCells(false) method. [#810](https://github.com/PHPOffice/PhpSpreadsheet/issues/810) - Fix LOOKUP function which was breaking on edge cases [#796](https://github.com/PHPOffice/PhpSpreadsheet/issues/796) - Fix VLOOKUP with exact matches [#809](https://github.com/PHPOffice/PhpSpreadsheet/pull/809) - Support COUNTIFS multiple arguments [#830](https://github.com/PHPOffice/PhpSpreadsheet/pull/830) - Change `libxml_disable_entity_loader()` as shortly as possible [#819](https://github.com/PHPOffice/PhpSpreadsheet/pull/819) - Improved memory usage and performance when loading large spreadsheets [#822](https://github.com/PHPOffice/PhpSpreadsheet/pull/822) - Improved performance when loading large spreadsheets [#825](https://github.com/PHPOffice/PhpSpreadsheet/pull/825) - Improved performance when loading large spreadsheets [#824](https://github.com/PHPOffice/PhpSpreadsheet/pull/824) - Fix color from CSS when reading from HTML [#831](https://github.com/PHPOffice/PhpSpreadsheet/pull/831) - Fix infinite loop when reading invalid ODS files [#832](https://github.com/PHPOffice/PhpSpreadsheet/pull/832) - Fix time format for duration is incorrect [#666](https://github.com/PHPOffice/PhpSpreadsheet/pull/666) - Fix iconv unsupported `//IGNORE//TRANSLIT` on IBM i [#791](https://github.com/PHPOffice/PhpSpreadsheet/issues/791) ### Changed - `master` is the new default branch, `develop` does not exist anymore ## 1.5.2 - 2018-11-25 ### Security - Improvements to the design of the XML Security Scanner [#771](https://github.com/PHPOffice/PhpSpreadsheet/issues/771) ## 1.5.1 - 2018-11-20 ### Security - Fix and improve XXE security scanning for XML-based and HTML Readers [#771](https://github.com/PHPOffice/PhpSpreadsheet/issues/771) ### Added - Support page margin in mPDF [#750](https://github.com/PHPOffice/PhpSpreadsheet/issues/750) ### Fixed - Support numeric condition in SUMIF, SUMIFS, AVERAGEIF, COUNTIF, MAXIF and MINIF [#683](https://github.com/PHPOffice/PhpSpreadsheet/issues/683) - SUMIFS containing multiple conditions [#704](https://github.com/PHPOffice/PhpSpreadsheet/issues/704) - Csv reader avoid notice when the file is empty [#743](https://github.com/PHPOffice/PhpSpreadsheet/pull/743) - Fix print area parser for XLSX reader [#734](https://github.com/PHPOffice/PhpSpreadsheet/pull/734) - Support overriding `DefaultValueBinder::dataTypeForValue()` without overriding `DefaultValueBinder::bindValue()` [#735](https://github.com/PHPOffice/PhpSpreadsheet/pull/735) - Mpdf export can exceed pcre.backtrack_limit [#637](https://github.com/PHPOffice/PhpSpreadsheet/issues/637) - Fix index overflow on data values array [#748](https://github.com/PHPOffice/PhpSpreadsheet/pull/748) ## 1.5.0 - 2018-10-21 ### Added - PHP 7.3 support - Add the DAYS() function [#594](https://github.com/PHPOffice/PhpSpreadsheet/pull/594) ### Fixed - Sheet title can contain exclamation mark [#325](https://github.com/PHPOffice/PhpSpreadsheet/issues/325) - Xls file cause the exception during open by Xls reader [#402](https://github.com/PHPOffice/PhpSpreadsheet/issues/402) - Skip non numeric value in SUMIF [#618](https://github.com/PHPOffice/PhpSpreadsheet/pull/618) - OFFSET should allow omitted height and width [#561](https://github.com/PHPOffice/PhpSpreadsheet/issues/561) - Correctly determine delimiter when CSV contains line breaks inside enclosures [#716](https://github.com/PHPOffice/PhpSpreadsheet/issues/716) ## 1.4.1 - 2018-09-30 ### Fixed - Remove locale from formatting string [#644](https://github.com/PHPOffice/PhpSpreadsheet/pull/644) - Allow iterators to go out of bounds with prev [#587](https://github.com/PHPOffice/PhpSpreadsheet/issues/587) - Fix warning when reading xlsx without styles [#631](https://github.com/PHPOffice/PhpSpreadsheet/pull/631) - Fix broken sample links on windows due to $baseDir having backslash [#653](https://github.com/PHPOffice/PhpSpreadsheet/pull/653) ## 1.4.0 - 2018-08-06 ### Added - Add excel function EXACT(value1, value2) support [#595](https://github.com/PHPOffice/PhpSpreadsheet/pull/595) - Support workbook view attributes for Xlsx format [#523](https://github.com/PHPOffice/PhpSpreadsheet/issues/523) - Read and write hyperlink for drawing image [#490](https://github.com/PHPOffice/PhpSpreadsheet/pull/490) - Added calculation engine support for the new bitwise functions that were added in MS Excel 2013 - BITAND() Returns a Bitwise 'And' of two numbers - BITOR() Returns a Bitwise 'Or' of two number - BITXOR() Returns a Bitwise 'Exclusive Or' of two numbers - BITLSHIFT() Returns a number shifted left by a specified number of bits - BITRSHIFT() Returns a number shifted right by a specified number of bits - Added calculation engine support for other new functions that were added in MS Excel 2013 and MS Excel 2016 - Text Functions - CONCAT() Synonym for CONCATENATE() - NUMBERVALUE() Converts text to a number, in a locale-independent way - UNICHAR() Synonym for CHAR() in PHPSpreadsheet, which has always used UTF-8 internally - UNIORD() Synonym for ORD() in PHPSpreadsheet, which has always used UTF-8 internally - TEXTJOIN() Joins together two or more text strings, separated by a delimiter - Logical Functions - XOR() Returns a logical Exclusive Or of all arguments - Date/Time Functions - ISOWEEKNUM() Returns the ISO 8601 week number of the year for a given date - Lookup and Reference Functions - FORMULATEXT() Returns a formula as a string - Financial Functions - PDURATION() Calculates the number of periods required for an investment to reach a specified value - RRI() Calculates the interest rate required for an investment to grow to a specified future value - Engineering Functions - ERF.PRECISE() Returns the error function integrated between 0 and a supplied limit - ERFC.PRECISE() Synonym for ERFC - Math and Trig Functions - SEC() Returns the secant of an angle - SECH() Returns the hyperbolic secant of an angle - CSC() Returns the cosecant of an angle - CSCH() Returns the hyperbolic cosecant of an angle - COT() Returns the cotangent of an angle - COTH() Returns the hyperbolic cotangent of an angle - ACOT() Returns the cotangent of an angle - ACOTH() Returns the hyperbolic cotangent of an angle - Refactored Complex Engineering Functions to use external complex number library - Added calculation engine support for the new complex number functions that were added in MS Excel 2013 - IMCOSH() Returns the hyperbolic cosine of a complex number - IMCOT() Returns the cotangent of a complex number - IMCSC() Returns the cosecant of a complex number - IMCSCH() Returns the hyperbolic cosecant of a complex number - IMSEC() Returns the secant of a complex number - IMSECH() Returns the hyperbolic secant of a complex number - IMSINH() Returns the hyperbolic sine of a complex number - IMTAN() Returns the tangent of a complex number ### Fixed - Fix ISFORMULA() function to work with a cell reference to another worksheet - Xlsx reader crashed when reading a file with workbook protection [#553](https://github.com/PHPOffice/PhpSpreadsheet/pull/553) - Cell formats with escaped spaces were causing incorrect date formatting [#557](https://github.com/PHPOffice/PhpSpreadsheet/issues/557) - Could not open CSV file containing HTML fragment [#564](https://github.com/PHPOffice/PhpSpreadsheet/issues/564) - Exclude the vendor folder in migration [#481](https://github.com/PHPOffice/PhpSpreadsheet/issues/481) - Chained operations on cell ranges involving borders operated on last cell only [#428](https://github.com/PHPOffice/PhpSpreadsheet/issues/428) - Avoid memory exhaustion when cloning worksheet with a drawing [#437](https://github.com/PHPOffice/PhpSpreadsheet/issues/437) - Migration tool keep variables containing $PHPExcel untouched [#598](https://github.com/PHPOffice/PhpSpreadsheet/issues/598) - Rowspans/colspans were incorrect when adding worksheet using loadIntoExisting [#619](https://github.com/PHPOffice/PhpSpreadsheet/issues/619) ## 1.3.1 - 2018-06-12 ### Fixed - Ranges across Z and AA columns incorrectly threw an exception [#545](https://github.com/PHPOffice/PhpSpreadsheet/issues/545) ## 1.3.0 - 2018-06-10 ### Added - Support to read Xlsm templates with form elements, macros, printer settings, protected elements and back compatibility drawing, and save result without losing important elements of document [#435](https://github.com/PHPOffice/PhpSpreadsheet/issues/435) - Expose sheet title maximum length as `Worksheet::SHEET_TITLE_MAXIMUM_LENGTH` [#482](https://github.com/PHPOffice/PhpSpreadsheet/issues/482) - Allow escape character to be set in CSV reader [#492](https://github.com/PHPOffice/PhpSpreadsheet/issues/492) ### Fixed - Subtotal 9 in a group that has other subtotals 9 exclude the totals of the other subtotals in the range [#332](https://github.com/PHPOffice/PhpSpreadsheet/issues/332) - `Helper\Html` support UTF-8 HTML input [#444](https://github.com/PHPOffice/PhpSpreadsheet/issues/444) - Xlsx loaded an extra empty comment for each real comment [#375](https://github.com/PHPOffice/PhpSpreadsheet/issues/375) - Xlsx reader do not read rows and columns filtered out in readFilter at all [#370](https://github.com/PHPOffice/PhpSpreadsheet/issues/370) - Make newer Excel versions properly recalculate formulas on document open [#456](https://github.com/PHPOffice/PhpSpreadsheet/issues/456) - `Coordinate::extractAllCellReferencesInRange()` throws an exception for an invalid range [#519](https://github.com/PHPOffice/PhpSpreadsheet/issues/519) - Fixed parsing of conditionals in COUNTIF functions [#526](https://github.com/PHPOffice/PhpSpreadsheet/issues/526) - Corruption errors for saved Xlsx docs with frozen panes [#532](https://github.com/PHPOffice/PhpSpreadsheet/issues/532) ## 1.2.1 - 2018-04-10 ### Fixed - Plain text and richtext mixed in same cell can be read [#442](https://github.com/PHPOffice/PhpSpreadsheet/issues/442) ## 1.2.0 - 2018-03-04 ### Added - HTML writer creates a generator meta tag [#312](https://github.com/PHPOffice/PhpSpreadsheet/issues/312) - Support invalid zoom value in XLSX format [#350](https://github.com/PHPOffice/PhpSpreadsheet/pull/350) - Support for `_xlfn.` prefixed functions and `ISFORMULA`, `MODE.SNGL`, `STDEV.S`, `STDEV.P` [#390](https://github.com/PHPOffice/PhpSpreadsheet/pull/390) ### Fixed - Avoid potentially unsupported PSR-16 cache keys [#354](https://github.com/PHPOffice/PhpSpreadsheet/issues/354) - Check for MIME type to know if CSV reader can read a file [#167](https://github.com/PHPOffice/PhpSpreadsheet/issues/167) - Use proper € symbol for currency format [#379](https://github.com/PHPOffice/PhpSpreadsheet/pull/379) - Read printing area correctly when skipping some sheets [#371](https://github.com/PHPOffice/PhpSpreadsheet/issues/371) - Avoid incorrectly overwriting calculated value type [#394](https://github.com/PHPOffice/PhpSpreadsheet/issues/394) - Select correct cell when calling freezePane [#389](https://github.com/PHPOffice/PhpSpreadsheet/issues/389) - `setStrikethrough()` did not set the font [#403](https://github.com/PHPOffice/PhpSpreadsheet/issues/403) ## 1.1.0 - 2018-01-28 ### Added - Support for PHP 7.2 - Support cell comments in HTML writer and reader [#308](https://github.com/PHPOffice/PhpSpreadsheet/issues/308) - Option to stop at a conditional styling, if it matches (only XLSX format) [#292](https://github.com/PHPOffice/PhpSpreadsheet/pull/292) - Support for line width for data series when rendering Xlsx [#329](https://github.com/PHPOffice/PhpSpreadsheet/pull/329) ### Fixed - Better auto-detection of CSV separators [#305](https://github.com/PHPOffice/PhpSpreadsheet/issues/305) - Support for shape style ending with `;` [#304](https://github.com/PHPOffice/PhpSpreadsheet/issues/304) - Freeze Panes takes wrong coordinates for XLSX [#322](https://github.com/PHPOffice/PhpSpreadsheet/issues/322) - `COLUMNS` and `ROWS` functions crashed in some cases [#336](https://github.com/PHPOffice/PhpSpreadsheet/issues/336) - Support XML file without styles [#331](https://github.com/PHPOffice/PhpSpreadsheet/pull/331) - Cell coordinates which are already a range cause an exception [#319](https://github.com/PHPOffice/PhpSpreadsheet/issues/319) ## 1.0.0 - 2017-12-25 ### Added - Support to write merged cells in ODS format [#287](https://github.com/PHPOffice/PhpSpreadsheet/issues/287) - Able to set the `topLeftCell` in freeze panes [#261](https://github.com/PHPOffice/PhpSpreadsheet/pull/261) - Support `DateTimeImmutable` as cell value - Support migration of prefixed classes ### Fixed - Can read very small HTML files [#194](https://github.com/PHPOffice/PhpSpreadsheet/issues/194) - Written DataValidation was corrupted [#290](https://github.com/PHPOffice/PhpSpreadsheet/issues/290) - Date format compatible with both LibreOffice and Excel [#298](https://github.com/PHPOffice/PhpSpreadsheet/issues/298) ### BREAKING CHANGE - Constant `TYPE_DOUGHTNUTCHART` is now `TYPE_DOUGHNUTCHART`. ## 1.0.0-beta2 - 2017-11-26 ### Added - Support for chart fill color - @CrazyBite [#158](https://github.com/PHPOffice/PhpSpreadsheet/pull/158) - Support for read Hyperlink for xml - @GreatHumorist [#223](https://github.com/PHPOffice/PhpSpreadsheet/pull/223) - Support for cell value validation according to data validation rules - @SailorMax [#257](https://github.com/PHPOffice/PhpSpreadsheet/pull/257) - Support for custom implementation, or configuration, of PDF libraries - @SailorMax [#266](https://github.com/PHPOffice/PhpSpreadsheet/pull/266) ### Changed - Merge data-validations to reduce written worksheet size - @billblume [#131](https://github.com/PHPOffice/PhpSpreadSheet/issues/131) - Throws exception if a XML file is invalid - @GreatHumorist [#222](https://github.com/PHPOffice/PhpSpreadsheet/pull/222) - Upgrade to mPDF 7.0+ [#144](https://github.com/PHPOffice/PhpSpreadsheet/issues/144) ### Fixed - Control characters in cell values are automatically escaped [#212](https://github.com/PHPOffice/PhpSpreadsheet/issues/212) - Prevent color changing when copy/pasting xls files written by PhpSpreadsheet to another file - @al-lala [#218](https://github.com/PHPOffice/PhpSpreadsheet/issues/218) - Add cell reference automatic when there is no cell reference('r' attribute) in Xlsx file. - @GreatHumorist [#225](https://github.com/PHPOffice/PhpSpreadsheet/pull/225) Refer to [#201](https://github.com/PHPOffice/PhpSpreadsheet/issues/201) - `Reader\Xlsx::getFromZipArchive()` function return false if the zip entry could not be located. - @anton-harvey [#268](https://github.com/PHPOffice/PhpSpreadsheet/pull/268) ### BREAKING CHANGE - Extracted coordinate method to dedicate class [migration guide](./docs/topics/migration-from-PHPExcel.md). - Column indexes are based on 1, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Standardization of array keys used for style, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Easier usage of PDF writers, and other custom readers and writers, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Easier usage of chart renderers, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Rename a few more classes to keep them in their related namespaces: - `CalcEngine` => `Calculation\Engine` - `PhpSpreadsheet\Calculation` => `PhpSpreadsheet\Calculation\Calculation` - `PhpSpreadsheet\Cell` => `PhpSpreadsheet\Cell\Cell` - `PhpSpreadsheet\Chart` => `PhpSpreadsheet\Chart\Chart` - `PhpSpreadsheet\RichText` => `PhpSpreadsheet\RichText\RichText` - `PhpSpreadsheet\Style` => `PhpSpreadsheet\Style\Style` - `PhpSpreadsheet\Worksheet` => `PhpSpreadsheet\Worksheet\Worksheet` ## 1.0.0-beta - 2017-08-17 ### Added - Initial implementation of SUMIFS() function - Additional codepages - MemoryDrawing not working in HTML writer [#808](https://github.com/PHPOffice/PHPExcel/issues/808) - CSV Reader can auto-detect the separator used in file [#141](https://github.com/PHPOffice/PhpSpreadsheet/pull/141) - HTML Reader supports some basic inline styles [#180](https://github.com/PHPOffice/PhpSpreadsheet/pull/180) ### Changed - Start following [SemVer](https://semver.org) properly. ### Fixed - Fix to getCell() method when cell reference includes a worksheet reference - @MarkBaker - Ignore inlineStr type if formula element exists - @ncrypthic [#570](https://github.com/PHPOffice/PHPExcel/issues/570) - Excel 2007 Reader freezes because of conditional formatting - @rentalhost [#575](https://github.com/PHPOffice/PHPExcel/issues/575) - Readers will now parse files containing worksheet titles over 31 characters [#176](https://github.com/PHPOffice/PhpSpreadsheet/pull/176) - Fixed PHP8 deprecation warning for libxml_disable_entity_loader() [#1625](https://github.com/phpoffice/phpspreadsheet/pull/1625) ### General - Whitespace after toRichTextObject() - @MarkBaker [#554](https://github.com/PHPOffice/PHPExcel/issues/554) - Optimize vlookup() sort - @umpirsky [#548](https://github.com/PHPOffice/PHPExcel/issues/548) - c:max and c:min elements shall NOT be inside c:orientation elements - @vitalyrepin [#869](https://github.com/PHPOffice/PHPExcel/pull/869) - Implement actual timezone adjustment into PHPExcel_Shared_Date::PHPToExcel - @sim642 [#489](https://github.com/PHPOffice/PHPExcel/pull/489) ### BREAKING CHANGE - Introduction of namespaces for all classes, eg: `PHPExcel_Calculation_Functions` becomes `PhpOffice\PhpSpreadsheet\Calculation\Functions` - Some classes were renamed for clarity and/or consistency: For a comprehensive list of all class changes, and a semi-automated migration path, read the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Dropped `PHPExcel_Calculation_Functions::VERSION()`. Composer or git should be used to know the version. - Dropped `PHPExcel_Settings::setPdfRenderer()` and `PHPExcel_Settings::setPdfRenderer()`. Composer should be used to autoload PDF libs. - Dropped support for HHVM ## Previous versions of PHPExcel The changelog for the project when it was called PHPExcel is [still available](./CHANGELOG.PHPExcel.md). ### Changed - Replace ezyang/htmlpurifier (LGPL2.1) with voku/anti-xss (MIT) ================================================ FILE: CONTRIBUTING.md ================================================ # Want to contribute? If you would like to contribute, here are some notes and guidelines: - All new development should be on feature/fix branches, which are then merged to the `master` branch once stable and approved; so the `master` branch is always the most up-to-date, working code - If you are going to submit a pull request, please fork from `master`, and submit your pull request back as a fix/feature branch referencing the GitHub issue number - Install (development) dependencies by running `composer install` inside your PhpSpreadsheet clone. - The code must work with all PHP versions that we support. - You can call `composer versions` to test version compatibility. - Code style should be maintained. - `composer style` will identify any issues with Coding Style. - `composer fix` will fix most issues with Coding Style. - All code changes must be validated by `composer check`. - Please include Unit Tests to verify that a bug exists, and that this PR fixes it. - Please include Unit Tests to show that a new Feature works as expected. - Please don't "bundle" several changes into a single PR; submit a PR for each discrete change/fix. - Remember to update documentation if necessary. - [Helpful article about forking](https://help.github.com/articles/fork-a-repo/ "Forking a GitHub repository") - [Helpful article about pull requests](https://help.github.com/articles/using-pull-requests/ "Pull Requests") ## Unit Tests When writing Unit Tests, please - Always try to write Unit Tests for both the happy and unhappy paths. - Put all assertions in the Test itself, not in an abstract class that the Test extends (even if this means code duplication between tests). - Include any necessary `setup()` and `tearDown()` in the Test itself. - If you change any global settings (such as system locale, or Compatibility Mode for Excel Function tests), make sure that you reset to the default in the `tearDown()`. - Use the `ExcelError` functions in assertions for Excel Error values in Excel Function implementations.
Not only does it reduce the risk of typos; but at some point in the future, ExcelError values will be an object rather than a string, and we won't then need to update all the tests. - Don't over-complicate test code by testing happy and unhappy paths in the same test. This makes it easier to see exactly what is being tested when reviewing the PR. I want to be able to see it in the PR, not have to hunt in other unchanged classes to see what the test is doing. ## How to release 1. Complete CHANGELOG.md and commit 2. Create an annotated tag 1. `git tag -a 1.2.3` 2. Tag subject must be the version number, eg: `1.2.3` 3. Tag body must be a copy-paste of the changelog entries. 3. Push the tag with `git push --tags`, GitHub Actions will create a GitHub release automatically, and the release details will automatically be sent to packagist. 4. By default, Github removes markdown headings in the Release Notes. You can either edit to restore these, or, probably preferably, change the default comment character on your system - `git config core.commentChar ";"`. > **Note:** Tagged releases are made from the `master` branch. Only in an emergency should a tagged release be made from the `release` branch. (i.e. cherry-picked hot-fixes.) However, there are 4 branches which have been updated to apply security patches, and those may be tagged if future security updates are needed. - 1.30.x (no further updates aside from security patches, including code changes needed for Php 8.5 compatibility) - 2.1.x (no further updates aside from security patches, including code changes needed for Php 8.5 compatibility) - 2.4.x - 3.10.x ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019-2026 PhpSpreadsheet Authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # PhpSpreadsheet [![Build Status](https://github.com/PHPOffice/PhpSpreadsheet/workflows/main/badge.svg)](https://github.com/PHPOffice/PhpSpreadsheet/actions) [![Code Coverage](https://coveralls.io/repos/github/PHPOffice/PhpSpreadsheet/badge.svg?branch=master)](https://coveralls.io/github/PHPOffice/PhpSpreadsheet?branch=master) [![Total Downloads](https://img.shields.io/packagist/dt/PHPOffice/PhpSpreadsheet)](https://packagist.org/packages/phpoffice/phpspreadsheet) [![Latest Stable Version](https://img.shields.io/github/v/release/PHPOffice/PhpSpreadsheet)](https://packagist.org/packages/phpoffice/phpspreadsheet) [![License](https://poser.pugx.org/phpoffice/phpspreadsheet/license)](https://packagist.org/packages/phpoffice/phpspreadsheet) [![Join the chat at https://gitter.im/PHPOffice/PhpSpreadsheet](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/PHPOffice/PhpSpreadsheet) PhpSpreadsheet is a library written in pure PHP and offers a set of classes that allow you to read and write various spreadsheet file formats such as Excel and LibreOffice Calc. This is the master branch, and is maintained for security and bug fixes. ## PHP Version Support LTS: For maintained branches, support for PHP versions will only be maintained for a period of six months beyond the [end of life](https://www.php.net/supported-versions) of that PHP version. Currently the required PHP minimum version is PHP __8.1__, and we [will support that version](https://www.php.net/supported-versions.php) until 30th June 2026. See the `composer.json` for other requirements. ## Installation See the [install instructions](https://phpspreadsheet.readthedocs.io/en/latest/#installation). ## Documentation Read more about it, including install instructions, in the [official documentation](https://phpspreadsheet.readthedocs.io). Or check out the [API documentation](https://phpoffice.github.io/PhpSpreadsheet). Please ask your support questions on [StackOverflow](https://stackoverflow.com/questions/tagged/phpspreadsheet), or have a quick chat on [Gitter](https://gitter.im/PHPOffice/PhpSpreadsheet). ## Patreon I am now running a [Patreon](https://www.patreon.com/MarkBaker) to support the work that I do on PhpSpreadsheet. Supporters will receive access to articles about working with PhpSpreadsheet, and how to use some of its more advanced features. Posts already available to Patreon supporters: - The Dating Game - A look at how MS Excel (and PhpSpreadsheet) handle date and time values. - Looping the Loop - Advice on Iterating through the rows and cells in a worksheet. And for Patrons at levels actively using PhpSpreadsheet: - Behind the Mask - A look at Number Format Masks. The Next Article (currently Work in Progress): - Formula for Success - How to debug formulae that don't produce the expected result. My aim is to post at least one article each month, taking a detailed look at some feature of MS Excel and how to use that feature in PhpSpreadsheet, or on how to perform different activities in PhpSpreadsheet. Planned posts for the future include topics like: - Tables - Structured References - AutoFiltering - Array Formulae - Conditional Formatting - Data Validation - Value Binders - Images - Charts After a period of six months exclusive to Patreon supporters, articles will be incorporated into the public documentation for the library. ## PHPExcel vs PhpSpreadsheet ? PhpSpreadsheet is the next version of PHPExcel. It breaks compatibility to dramatically improve the code base quality (namespaces, PSR compliance, use of latest PHP language features, etc.). Because all efforts have shifted to PhpSpreadsheet, PHPExcel will no longer be maintained. All contributions for PHPExcel, patches and new features, should target PhpSpreadsheet `master` branch. Do you need to migrate? There is [an automated tool](/docs/topics/migration-from-PHPExcel.md) for that. ## License PhpSpreadsheet is licensed under [MIT](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/LICENSE). ================================================ FILE: bin/check-phpdoc-types.php ================================================ #!/usr/bin/env php generateLocales(); ================================================ FILE: bin/pre-commit ================================================ #!/bin/bash pass=true files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(php|phtml)$') if [ "$files" != "" ]; then # Run php syntax check before commit while read -r file; do php -l "$file" if [ $? -ne 0 ]; then pass=false fi done <<< "$files" # Run php-cs-fixer validation before commit echo "$files" | xargs ./vendor/bin/php-cs-fixer fix --diff --config .php-cs-fixer.dist.php if [ $? -ne 0 ]; then pass=false fi # Automatically add files that may have been fixed by php-cs-fixer echo "$files" | xargs git add fi # Check PHPDoc types ./bin/check-phpdoc-types.php if [ $? -ne 0 ]; then pass=false fi if $pass; then exit 0 else echo "" echo "PRE-COMMIT HOOK FAILED:" echo "Code style validation failed. Please fix errors and try committing again." exit 1 fi ================================================ FILE: composer.json ================================================ { "name": "phpoffice/phpspreadsheet", "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", "keywords": [ "PHP", "OpenXML", "Excel", "xlsx", "xls", "ods", "gnumeric", "spreadsheet" ], "config": { "platform": { "php" : "8.1.99" }, "process-timeout": 600, "sort-packages": true, "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } }, "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", "type": "library", "license": "MIT", "authors": [ { "name": "Maarten Balliauw", "homepage": "https://blog.maartenballiauw.be" }, { "name": "Mark Baker", "homepage": "https://markbakeruk.net" }, { "name": "Franck Lefevre", "homepage": "https://rootslabs.net" }, { "name": "Erik Tilt" }, { "name": "Adrien Crivelli" }, { "name": "Owen Leibman" } ], "scripts": { "check": [ "php bin/check-phpdoc-types.php", "phpcs samples/ src/ tests/ --report=checkstyle", "phpcs samples/ src/ tests/ --standard=PHPCompatibility --runtime-set testVersion 8.0- --exclude=PHPCompatibility.Variables.ForbiddenThisUseContexts -n", "php-cs-fixer fix --ansi --dry-run --diff", "phpstan analyse --ansi --memory-limit=2048M", "phpunit --color=always" ], "style": [ "phpcs samples/ src/ tests/ --report=checkstyle", "php-cs-fixer fix --ansi --dry-run --diff" ], "fix": [ "phpcbf samples/ src/ tests/ --report=checkstyle", "php-cs-fixer fix" ], "versions": [ "phpcs samples/ src/ tests/ --standard=PHPCompatibility --runtime-set testVersion 8.0- --exclude=PHPCompatibility.Variables.ForbiddenThisUseContexts -n" ] }, "require": { "php": "^8.1", "ext-ctype": "*", "ext-dom": "*", "ext-fileinfo": "*", "ext-filter": "*", "ext-gd": "*", "ext-iconv": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-simplexml": "*", "ext-xml": "*", "ext-xmlreader": "*", "ext-xmlwriter": "*", "ext-zip": "*", "ext-zlib": "*", "composer/pcre": "^1||^2||^3", "maennchen/zipstream-php": "^2.1 || ^3.0", "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { "ext-intl": "*", "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0 || ^3.0", "friendsofphp/php-cs-fixer": "^3.2", "mitoteam/jpgraph": "^10.5", "mpdf/mpdf": "^8.1.1", "phpcompatibility/php-compatibility": "^9.3", "phpstan/phpstan": "^1.1 || ^2.0", "phpstan/phpstan-deprecation-rules": "^1.0 || ^2.0", "phpstan/phpstan-phpunit": "^1.0 || ^2.0", "phpunit/phpunit": "^10.5", "squizlabs/php_codesniffer": "^3.7", "tecnickcom/tcpdf": "^6.5" }, "suggest": { "ext-intl": "PHP Internationalization Functions, required for NumberFormat Wizard and StringHelper::setLocale()", "mpdf/mpdf": "Option for rendering PDF with PDF Writer", "dompdf/dompdf": "Option for rendering PDF with PDF Writer", "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer", "mitoteam/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers" }, "autoload": { "psr-4": { "PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet" } }, "autoload-dev": { "psr-4": { "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests", "PhpOffice\\PhpSpreadsheetInfra\\": "infra" } } } ================================================ FILE: docs/extra/extra.css ================================================ /* Make the huge table always visible */ table.features-cross-reference { overflow: visible !important; } .rst-content table.features-cross-reference.docutils th, .rst-content table.features-cross-reference.docutils td { background-color: white; } /* https://github.com/mkdocs/mkdocs/discussions/3035#discussioncomment-7237037 */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } .wy-table-responsive { overflow : visible !important; } /* https://github.com/readthedocs/sphinx_rtd_theme/issues/295#issuecomment-455226058 */ .wy-nav-content {max-width: none;} ================================================ FILE: docs/extra/extrajs.js ================================================ document.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("table").forEach(function(table) { table.classList.add("docutils"); }); }); ================================================ FILE: docs/faq.md ================================================ # Frequently asked questions ## There seems to be a problem with character encoding... It is necessary to use UTF-8 encoding for all texts in PhpSpreadsheet. If the script uses different encoding then you can convert those texts with PHP's `iconv()` or `mb_convert_encoding()` functions. ## Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate yyy bytes) in zzz on line aaa PhpSpreadsheet holds an "in memory" representation of a spreadsheet, so it is susceptible to PHP's memory limitations. The memory made available to PHP can be increased by editing the value of the `memory_limit` directive in your `php.ini` file, or by using `ini_set('memory_limit', '128M')` within your code. Some Readers and Writers are faster than others, and they also use differing amounts of memory. ## Protection on my worksheet is not working? When you make use of any of the worksheet protection features (e.g. cell range protection, prohibiting deleting rows, ...), make sure you enable worksheet security. This can for example be done like this: ```php $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); ``` ## Feature X is not working with Reader\_Y / Writer\_Z Not all features of PhpSpreadsheet are implemented in all of the Reader / Writer classes. This is mostly due to underlying libraries not supporting a specific feature or not having implemented a specific feature. For example autofilter is not implemented in PEAR Spreadsheet\_Excel\_writer, which is the base of our Xls writer. We are slowly building up a list of features, together with the different readers and writers that support them, in the [features cross reference](./references/features-cross-reference.md). ## Formulas don't seem to be calculated in Excel2003 using compatibility pack? This is normal behaviour of the compatibility pack, `Xlsx` displays this correctly. Use `\PhpOffice\PhpSpreadsheet\Writer\Xls` if you really need calculated values, or force recalculation in Excel2003. ## Setting column width is not 100% accurate Trying to set column width, I experience one problem. When I open the file in Excel, the actual width is 0.71 less than it should be. The short answer is that PhpSpreadsheet uses a measure where padding is included. See [how to set a column's width](./topics/recipes.md#setting-a-columns-width) for more details. ## I cannot serialize or json_encode my Spreadsheet No, you can't. Consider the Spreadsheet object as a PHP resource, which cannot be serialized. ================================================ FILE: docs/index.md ================================================ # Welcome to PhpSpreadsheet's documentation ![Logo](./assets/logo.svg) PhpSpreadsheet is a library written in pure PHP and offers a set of classes that allow you to read and write various spreadsheet file formats such as Excel and LibreOffice Calc. ## File formats supported |Format |Reading|Writing| |--------------------------------------------|:-----:|:-----:| |Open Document Format/OASIS (.ods) | ✓ | ✓ | |Office Open XML (.xlsx) Excel 2007 and above| ✓ | ✓ | |BIFF 8 (.xls) Excel 97 and above | ✓ | ✓ | |BIFF 5 (.xls) Excel 95 | ✓ | | |SpreadsheetML (.xml) Excel 2003 | ✓ | | |Gnumeric | ✓ | | |HTML | ✓ | ✓ | |SYLK | ✓ | | |CSV | ✓ | ✓ | |PDF (using either the TCPDF, Dompdf or mPDF libraries, which need to be installed separately)| | ✓ | Note - reading or writing certain aspects of a spreadsheet may not be supported in all formats. For more details, please consult [Features Cross-reference](./references/features-cross-reference.md). # Getting started ## Software requirements PHP version 8.1 or newer to develop using PhpSpreadsheet. Other requirements, such as PHP extensions, are enforced by composer. See the `require` section of [the composer.json file](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/composer.json) for details. ### PHP version support LTS: Support for PHP versions will only be maintained for a period of six months beyond the [end of life of that PHP version](https://www.php.net/eol.php). Currently, the required PHP minimum version is __PHP 8.1__, and we [will support that version](https://www.php.net/eol.php) until June 2026. Support for PHP versions will only be maintained for a period of six months beyond the [end of life](https://www.php.net/supported-versions) of that PHP version. See the `composer.json` for other requirements. ## Installation Use [composer](https://getcomposer.org) to install PhpSpreadsheet into your project: ```sh composer require phpoffice/phpspreadsheet ``` Or also download the documentation and samples if you plan to use them (note that `git` must be in your path for this to work): ```sh composer require phpoffice/phpspreadsheet --prefer-source ``` If you are building your installation on a development machine that is on a different PHP version to the server where it will be deployed, or if your PHP CLI version is different from your run-time such as `php-fpm` or Apache's `mod_php`, then you might want to configure composer for that. See [composer documentation](https://getcomposer.org/doc/06-config.md#platform) on how to edit your `composer.json` to ensure that the correct dependencies are retrieved to match your deployment environment. See [CLI vs Application run-time](https://php.watch/articles/composer-platform-check) for more details. ### Additional Installation Options If you want to write to PDF, or to include Charts when you write to HTML or PDF, then you will need to install additional libraries: #### PDF For PDF Generation, you can install any of the following, and then configure PhpSpreadsheet to indicate which library you are going to use: - mpdf/mpdf - dompdf/dompdf - tecnickcom/tcpdf and configure PhpSpreadsheet using: ```php // Dompdf, Mpdf or Tcpdf (as appropriate) $className = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf::class; IOFactory::registerWriter('Pdf', $className); ``` or the appropriate PDF Writer wrapper for the library that you have chosen to install. #### Chart Export For Chart export, we support following packages, which you will also need to install yourself using `composer require` - [jpgraph/jpgraph](https://packagist.org/packages/jpgraph/jpgraph) (this package was abandoned at version 4.0. You can manually download the latest version that supports PHP 8 and above from [jpgraph.net](https://jpgraph.net/)) - [mitoteam/jpgraph](https://packagist.org/packages/mitoteam/jpgraph) - up to date fork with modern PHP versions support and some bugs fixed. and then configure PhpSpreadsheet using: ```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); ``` One or the other of these libraries is necessary if you want to generate HTML or PDF files that include charts; or to render a Chart to an Image format from within your code. They are not necessary to define charts for writing to `Xlsx` files. Other file formats don't support writing Charts. ## Hello World This would be the simplest way to write a spreadsheet: ```php getActiveSheet(); $activeWorksheet->setCellValue('A1', 'Hello World !'); $writer = new Xlsx($spreadsheet); $writer->save('hello world.xlsx'); ``` ## Learn by example A good way to get started is to run some of the samples. Don't forget to download them via `--prefer-source` composer flag. And then serve them via PHP built-in webserver: ```sh php -S localhost:8000 -t vendor/phpoffice/phpspreadsheet/samples ``` Then point your browser to: > http://localhost:8000/ The samples may also be run directly from the command line, for example: ```sh php vendor/phpoffice/phpspreadsheet/samples/Basic/01_Simple.php ``` ## Learn by documentation For more documentation in depth, you may read about an [overview of the architecture](./topics/architecture.md), [creating a spreadsheet](./topics/creating-spreadsheet.md), [worksheets](./topics/worksheets.md), [accessing cells](./topics/accessing-cells.md) and [reading and writing to files](./topics/reading-and-writing-to-file.md). Or browse the [API documentation](https://phpoffice.github.io/PhpSpreadsheet). # Credits Please refer to the [contributor list](https://github.com/PHPOffice/PhpSpreadsheet/graphs/contributors) for up-to-date credits. ================================================ FILE: docs/references/features-cross-reference.md ================================================ # Features cross reference - Supported - Partially supported - Not supported - N/A Cannot be supported ## Readers
Readers
XLS XLSX Excel2003XML Ods Gnumeric CSV SYLK HTML
Reader Options N/A N/A
Read Charts N/A N/A
Read Data Only (no formatting) N/A N/A
Read Only Specified Worksheets N/A N/A
Read Only Specified Cells
Read External Images 9 N/A N/A 9
Document Properties N/A N/A
Standard Properties N/A N/A
Creator N/A N/A
Creation Date/Time N/A N/A
Modifier N/A N/A N/A N/A
Modified Date/Time N/A N/A N/A
Title N/A N/A
Description N/A N/A
Subject N/A N/A
Keywords N/A N/A
Extended Properties N/A N/A N/A
Category N/A N/A N/A
Company N/A N/A N/A
Manager N/A N/A N/A
User-Defined (Custom) Properties N/A N/A N/A
Text Properties N/A N/A N/A
Number Properties N/A N/A N/A
Date Properties N/A N/A N/A
Yes/No (Boolean) Properties N/A N/A N/A
Cell Data Types
Empty/NULL
Boolean
Integer
Floating Point
String
Error
Formula
Array Formula N/A N/A
Rich Text
Conditional Formatting N/A N/A
Rows and Column Properties N/A N/A
Row Height/Column Width N/A N/A
Hidden N/A N/A
Worksheet Properties N/A N/A
Frozen Panes N/A N/A N/A
Hidden Worksheets N/A N/A
Coloured Tabs N/A N/A N/A
Drawing hyperlink N/A N/A
Cell Formatting N/A 7
Number Format Mask 6 N/A
Alignment N/A 7
Horizontal N/A
Vertical N/A
Wrapping N/A
Shrink-to-Fit N/A
Indent N/A
Background Colour N/A 7
Patterned N/A N/A
Font Attributes N/A 7
Font Face N/A
Font Size N/A
Bold N/A
Italic N/A
Strikethrough N/A
Underline N/A
Superscript N/A
Subscript N/A
Borders N/A 7
Line Style N/A
Position N/A
Diagonal N/A
Hyperlinks
http N/A
Merged Cells N/A
Cell Comments N/A
Rich Text 2 N/A N/A
Alignment 3 N/A
Background Image N/A
Cell Validation N/A N/A N/A
AutoFilters N/A N/A N/A
AutoFilter Expressions N/A N/A N/A
Filter N/A N/A N/A
Custom Filter N/A N/A N/A
Date Filter N/A N/A N/A
Dynamic Filter N/A N/A N/A
Colour Filter N/A N/A N/A
Icon Filter N/A N/A N/A
Top 10 Filter N/A N/A N/A
Macros 5
Form Controls 4
Security
Protection (prevent editing)
Encryption (prevent viewing)
XLS XLSX Excel2003XML Ods Gnumeric CSV SYLK HTML
Readers
1. Only text contents 2. Only BIFF8 files support Rich Text. Prior to that, comments could only be plain text 3. Only BIFF8 files support alignment and rotation. Prior to that, comments could only be unformatted text 4. Xlsx forms and controls can be read and written but not otherwise manipulated 5. Xlsx macros can be read and written; their values can be retrieved and changed, but only in a binary form which is unlikely to be useful 6. There is very limited support for reading styles from an Ods spreadsheet before release 5.5.0. Writing styles has much better support. Starting with release 5.5.0, Number Format Writer supports many common styles, and users may extend support to additional styles; Reader support for Number Formats is improved but still imperfect; for other styles, it is much improved. 7. In most cases, Html reader processes only inline styles; styles provided by Css classes may be ignored. 8. Code must [opt in](../topics/recipes.md#array-formulas) to array output. 9. Use with caution - allowing external images may can subject the caller to security exploits. Starting with release 4.5.0 (also earlier releases 3.9.3, 2.3.10, 2.1.11, and 1.29.12), code can allow or not external images. In those starting releases, and in earlier releases which do not offer an option, default is to allow it. In release 5+ (and earlier supported versions 1.30+, 2.1.12+, 2.4+, and 3.10+), the default is to not allow it. ## Writers
Writers
XLS XLSX Ods CSV HTML PDF
Document Properties
Standard Properties
Creator N/A
Creation Date/Time N/A
Modifier N/A
Modified Date/Time N/A
Title N/A
Description N/A
Subject N/A
Keywords N/A
Extended Properties
Category N/A
Company N/A
Manager N/A
User-Defined (Custom) Properties N/A N/A
Rich Text N/A
Conditional Formatting
Array Formula8
Rows and Column Properties
Row Height/Column Width N/A
Hidden N/A
Worksheet Properties
Frozen Panes N/A
Hidden Worksheets N/A
Coloured Tabs N/A
Drawing hyperlink N/A
Cell Formatting
Number Format Mask 6 N/A
Alignment N/A
Horizontal N/A
Vertical N/A
Wrapping N/A
Shrink-to-Fit N/A
Indent N/A
Background Colour N/A
Patterned N/A N/A
Font Attributes
Font Face N/A
Font Size N/A
Bold N/A
Italic N/A
Strikethrough N/A
Underline N/A
Superscript N/A
Subscript N/A
Borders
Line Style N/A
Position N/A
Diagonal N/A
Hyperlinks N/A
http N/A
Merged Cells N/A
Cell Comments N/A 1 N/A
Rich Text N/A N/A
Alignment N/A N/A
Background Image
Cell Validation N/A N/A N/A
AutoFilters
AutoFilter Expressions N/A N/A N/A
Filter N/A N/A N/A
Custom Filter N/A N/A N/A
DateGroup Filter N/A N/A N/A
Dynamic Filter N/A N/A N/A
Colour Filter N/A N/A N/A
Icon Filter N/A N/A N/A
Top 10 Filter N/A N/A N/A
Macros 5 N/A
Form Controls 4 N/A
Security
Protection (prevent editing) N/A
Encryption (prevent viewing) N/A
XLS XLSX Ods CSV HTML PDF
Writers
## Setters and Getters
Methods
Getters Setters
Reader Options
Read Data Only (no formatting) $reader->getReadDataOnly() $reader->setReadDataOnly()
Read Only Specified Worksheets $reader->getLoadSheetsOnly() $reader->setLoadSheetsOnly()
$reader->setLoadAllSheets()
Read Only Specified Cells $reader->getReadFilter() $reader->setReadFilter()
Document Properties
Standard Properties
Creator $spreadsheet->getProperties()->getCreator() $spreadsheet->getProperties()->setCreator()
Creation Date/Time $spreadsheet->getProperties()->getCreated() $spreadsheet->getProperties()->setCreated()
Modifier $spreadsheet->getProperties()->getLastModifiedBy() $spreadsheet->getProperties()->setLastModifiedBy()
Modified Date/Time $spreadsheet->getProperties()->getModified() $spreadsheet->getProperties()->setModified()
Title $spreadsheet->getProperties()->getTitle() $spreadsheet->getProperties()->setTitle()
Description $spreadsheet->getProperties()->getDescription() $spreadsheet->getProperties()->setDescription()
Subject $spreadsheet->getProperties()->getSubject() $spreadsheet->getProperties()->setSubject()
Keywords $spreadsheet->getProperties()->getKeywords() $spreadsheet->getProperties()->setKeywords()
Extended Properties
Category $spreadsheet->getProperties()->getCategory() $spreadsheet->getProperties()->setCategory()
Company $spreadsheet->getProperties()->getCompany() $spreadsheet->getProperties()->setCompany()
Manager $spreadsheet->getProperties()->getManager() $spreadsheet->getProperties()->setManager()
User-Defined (Custom) Properties $spreadsheet->getProperties()->getCustomProperties()
$spreadsheet->getProperties()->isCustomPropertySet()
$spreadsheet->getProperties()->getCustomPropertyValue()
$spreadsheet->getProperties()->getCustomPropertyType()
$spreadsheet->getProperties()->setCustomProperty()
$drawing->getHyperlink()->getUrl() $drawing->setHyperlink()->setUrl($url)
$cell->getHyperlink()->getUrl($url) $cell->getHyperlink()->setUrl($url)
Cell Comments
Background Image $comment->getBackgroundImage() $comment->setBackgroundImage()
Cell Validation $cell->getDataValidation() $cell->setDataValidation()
AutoFilters $sheet->getAutoFilter() $sheet->setAutoFilter()
Macros $spreadsheet->getMacrosCode();5 $spreadsheet->setMacrosCode();5
Security
Protection (prevent editing) $sheet->getProtection() $sheet->getProtection()->setSheet(true)
Getters Setters
Methods
================================================ FILE: docs/references/function-list-by-category.md ================================================ # Function list by category ## CATEGORY_CUBE Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- CUBEKPIMEMBER | **Not yet Implemented** CUBEMEMBER | **Not yet Implemented** CUBEMEMBERPROPERTY | **Not yet Implemented** CUBERANKEDMEMBER | **Not yet Implemented** CUBESET | **Not yet Implemented** CUBESETCOUNT | **Not yet Implemented** CUBEVALUE | **Not yet Implemented** ## CATEGORY_DATABASE Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- DAVERAGE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage::evaluate DCOUNT | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCount::evaluate DCOUNTA | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCountA::evaluate DGET | \PhpOffice\PhpSpreadsheet\Calculation\Database\DGet::evaluate DMAX | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMax::evaluate DMIN | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMin::evaluate DPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\Database\DProduct::evaluate DSTDEV | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDev::evaluate DSTDEVP | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDevP::evaluate DSUM | \PhpOffice\PhpSpreadsheet\Calculation\Database\DSum::evaluate DVAR | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVar::evaluate DVARP | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVarP::evaluate ## CATEGORY_DATE_AND_TIME Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- DATE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Date::fromYMD DATEDIF | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Difference::interval DATESTRING | **Not yet Implemented** DATEVALUE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateValue::fromString DAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::day DAYS | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days::between DAYS360 | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days360::between EDATE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::adjust EOMONTH | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::lastDay HOUR | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::hour ISOWEEKNUM | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::isoWeekNumber MINUTE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::minute MONTH | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::month NETWORKDAYS | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\NetworkDays::count NETWORKDAYS.INTL | **Not yet Implemented** NOW | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::now SECOND | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::second THAIDAYOFWEEK | **Not yet Implemented** THAIMONTHOFYEAR | **Not yet Implemented** THAIYEAR | **Not yet Implemented** TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Time::fromHMS TIMEVALUE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeValue::fromString TODAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::today WEEKDAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::day WEEKNUM | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::number WORKDAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\WorkDay::date WORKDAY.INTL | **Not yet Implemented** YEAR | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::year YEARFRAC | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\YearFrac::fraction ## CATEGORY_ENGINEERING Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- BESSELI | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselI::BESSELI BESSELJ | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselJ::BESSELJ BESSELK | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselK::BESSELK BESSELY | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselY::BESSELY BIN2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toDecimal BIN2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toHex BIN2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toOctal BITAND | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITAND BITLSHIFT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITLSHIFT BITOR | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITOR BITRSHIFT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITRSHIFT BITXOR | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITXOR COMPLEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::COMPLEX CONVERT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertUOM::CONVERT DEC2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toBinary DEC2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toHex DEC2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toOctal DELTA | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::DELTA ERF | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERF ERF.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERFPRECISE ERFC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC ERFC.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC GESTEP | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::GESTEP HEX2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toBinary HEX2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toDecimal HEX2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toOctal IMABS | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMABS IMAGINARY | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMAGINARY IMARGUMENT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMARGUMENT IMCONJUGATE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCONJUGATE IMCOS | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOS IMCOSH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOSH IMCOT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOT IMCSC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSC IMCSCH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSCH IMDIV | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMDIV IMEXP | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMEXP IMLN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLN IMLOG10 | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG10 IMLOG2 | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG2 IMPOWER | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMPOWER IMPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMPRODUCT IMREAL | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMREAL IMSEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSEC IMSECH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSECH IMSIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSIN IMSINH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSINH IMSQRT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSQRT IMSUB | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUB IMSUM | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUM IMTAN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMTAN OCT2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toBinary OCT2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toDecimal OCT2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toHex ## CATEGORY_FINANCIAL Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ACCRINT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::periodic ACCRINTM | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::atMaturity AMORDEGRC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORDEGRC AMORLINC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORLINC COUPDAYBS | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYBS COUPDAYS | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYS COUPDAYSNC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYSNC COUPNCD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNCD COUPNUM | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNUM COUPPCD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPPCD CUMIPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::interest CUMPRINC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::principal DB | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DB DDB | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DDB DISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::discount DOLLARDE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::decimal DOLLARFR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::fractional DURATION | **Not yet Implemented** EFFECT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::effective FV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::futureValue FVSCHEDULE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::futureValue INTRATE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::interest IPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::payment IRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::rate ISPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::schedulePayment MDURATION | **Not yet Implemented** MIRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::modifiedRate NOMINAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::nominal NPER | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::periods NPV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::presentValue ODDFPRICE | **Not yet Implemented** ODDFYIELD | **Not yet Implemented** ODDLPRICE | **Not yet Implemented** ODDLYIELD | **Not yet Implemented** PDURATION | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::periods PMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::annuity PPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::interestPayment PRICE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::price PRICEDISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceDiscounted PRICEMAT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceAtMaturity PV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::presentValue RATE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::rate RECEIVED | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::received RRI | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::interestRate SLN | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SLN SYD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SYD TBILLEQ | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::bondEquivalentYield TBILLPRICE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::price TBILLYIELD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::yield USDOLLAR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::format VDB | **Not yet Implemented** XIRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::rate XNPV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::presentValue YIELD | **Not yet Implemented** YIELDDISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldDiscounted YIELDMAT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldAtMaturity ## CATEGORY_INFORMATION Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- CELL | **Not yet Implemented** ERROR.TYPE | \PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError::type INFO | \PhpOffice\PhpSpreadsheet\Calculation\Information\Info::getInfo ISBLANK | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isBlank ISERR | \PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue::isErr ISERROR | \PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue::isError ISEVEN | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isEven ISFORMULA | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isFormula ISLOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isLogical ISNA | \PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue::isNa ISNONTEXT | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isNonText ISNUMBER | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isNumber ISODD | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isOdd ISOMITTED | **Not yet Implemented** ISREF | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isRef ISTEXT | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isText N | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::asNumber NA | \PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError::NA SHEET | **Not yet Implemented** SHEETS | **Not yet Implemented** TYPE | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::type ## CATEGORY_LOGICAL Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- AND | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalAnd BYCOL | **Not yet Implemented** BYROW | **Not yet Implemented** FALSE | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::FALSE IF | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementIf IFERROR | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFERROR IFNA | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFNA IFS | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFS LAMBDA | **Not yet Implemented** LET | **Not yet Implemented** MAKEARRAY | **Not yet Implemented** MAP | **Not yet Implemented** NOT | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::NOT OR | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalOr REDUCE | **Not yet Implemented** SCAN | **Not yet Implemented** SWITCH | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementSwitch TRUE | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::TRUE XOR | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalXor ## CATEGORY_LOOKUP_AND_REFERENCE Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ADDRESS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address::cell AREAS | **Not yet Implemented** CHOOSE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Selection::CHOOSE CHOOSECOLS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::chooseCols CHOOSEROWS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::chooseRows COLUMN | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMN COLUMNS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMNS DROP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::drop EXPAND | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::expand FILTER | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Filter::filter FORMULATEXT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Formula::text GETPIVOTDATA | **Not yet Implemented** GROUPBY | **Not yet Implemented** HLOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup::lookup HSTACK | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Hstack::hstack HYPERLINK | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Hyperlink::set INDEX | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::index INDIRECT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect::INDIRECT LOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup::lookup MATCH | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ExcelMatch::MATCH OFFSET | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset::OFFSET ROW | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROW ROWS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROWS RTD | **Not yet Implemented** SORT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Sort::sort SORTBY | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Sort::sortBy TAKE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::take TOCOL | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\TorowTocol::tocol TOROW | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\TorowTocol::torow TRANSPOSE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::transpose UNIQUE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Unique::unique VLOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup::lookup VSTACK | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Vstack::vstack XLOOKUP | **Not yet Implemented** XMATCH | **Not yet Implemented** ## CATEGORY_MATH_AND_TRIG Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ABS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Absolute::evaluate ACOS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acos ACOSH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acosh ACOT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acot ACOTH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acoth AGGREGATE | **Not yet Implemented** ARABIC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Arabic::evaluate ASIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asin ASINH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asinh ATAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan ATAN2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan2 ATANH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atanh BASE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Base::evaluate CEILING | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::ceiling CEILING.MATH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::math CEILING.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::precise COMBIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withoutRepetition COMBINA | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withRepetition COS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cos COSH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cosh COT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::cot COTH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::coth CSC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csc CSCH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csch DECIMAL | **Not yet Implemented** DEGREES | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toDegrees ECMA.CEILING | **Not yet Implemented** EVEN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::even EXP | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp::evaluate FACT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::fact FACTDOUBLE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::factDouble FLOOR | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::floor FLOOR.MATH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::math FLOOR.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::precise GCD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Gcd::evaluate INT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\IntClass::evaluate ISO.CEILING | **Not yet Implemented** LCM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Lcm::evaluate LN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::natural LOG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::withBase LOG10 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::base10 MDETERM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::determinant MINVERSE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::inverse MMULT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::multiply MOD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::mod MROUND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::multiple MULTINOMIAL | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::multinomial MUNIT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::identity ODD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::odd PI | pi POWER | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::power PRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::product QUOTIENT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::quotient RADIANS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toRadians RAND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::rand RANDARRAY | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::randArray RANDBETWEEN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::randBetween ROMAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Roman::evaluate ROUND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::round ROUNDBAHTDOWN | **Not yet Implemented** ROUNDBAHTUP | **Not yet Implemented** ROUNDDOWN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::down ROUNDUP | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::up SEC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sec SECH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sech SEQUENCE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::sequence SERIESSUM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SeriesSum::evaluate SIGN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sign::evaluate SIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sin SINH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sinh SQRT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::sqrt SQRTPI | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::pi SUBTOTAL | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Subtotal::evaluate SUM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::sumErroringStrings SUMIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIF SUMIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIFS SUMPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::product SUMSQ | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumSquare SUMX2MY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredMinusYSquared SUMX2PY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredPlusYSquared SUMXMY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXMinusYSquared TAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tan TANH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tanh TRUNC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trunc::evaluate WRAPCOLS | **Not yet Implemented** WRAPROWS | **Not yet Implemented** ## CATEGORY_STATISTICAL Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- AVEDEV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageDeviations AVERAGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::average AVERAGEA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageA AVERAGEIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIF AVERAGEIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIFS BETA.DIST | **Not yet Implemented** BETA.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse BETADIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::distribution BETAINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse BINOM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution BINOM.DIST.RANGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::range BINOM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse BINOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution CHIDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail CHIINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail CHISQ.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionLeftTail CHISQ.DIST.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail CHISQ.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseLeftTail CHISQ.INV.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail CHISQ.TEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test CHITEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test CONFIDENCE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE CONFIDENCE.NORM | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE CONFIDENCE.T | **Not yet Implemented** CORREL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL COUNT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNT COUNTA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTA COUNTBLANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTBLANK COUNTIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIF COUNTIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIFS COVAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR COVARIANCE.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR COVARIANCE.S | **Not yet Implemented** CRITBINOM | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse DEVSQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::sumSquares EXPON.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution EXPONDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution F.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F::distribution F.DIST.RT | **Not yet Implemented** F.INV | **Not yet Implemented** F.INV.RT | **Not yet Implemented** F.TEST | **Not yet Implemented** FDIST | **Not yet Implemented** FINV | **Not yet Implemented** FISHER | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::distribution FISHERINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::inverse FORECAST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST FORECAST.ETS | **Not yet Implemented** FORECAST.ETS.CONFINT | **Not yet Implemented** FORECAST.ETS.SEASONALITY | **Not yet Implemented** FORECAST.ETS.STAT | **Not yet Implemented** FORECAST.LINEAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST FREQUENCY | **Not yet Implemented** FTEST | **Not yet Implemented** GAMMA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::gamma GAMMA.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution GAMMA.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse GAMMADIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution GAMMAINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse GAMMALN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln GAMMALN.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln GAUSS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::gauss GEOMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::geometric GROWTH | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::GROWTH HARMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::harmonic HYPGEOM.DIST | **Not yet Implemented** HYPGEOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\HyperGeometric::distribution INTERCEPT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::INTERCEPT KURT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::kurtosis LARGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::large LINEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LINEST LOGEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LOGEST LOGINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse LOGNORM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::distribution LOGNORM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse LOGNORMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::cumulative MAX | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::max MAXA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::maxA MAXIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MAXIFS MEDIAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::median MEDIANIF | **Not yet Implemented** MIN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::min MINA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::minA MINIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MINIFS MODE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode MODE.MULT | **Not yet Implemented** MODE.SNGL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode NEGBINOM.DIST | **Not yet Implemented** NEGBINOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::negative NORM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution NORM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse NORM.S.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::distribution NORM.S.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse NORMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution NORMINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse NORMSDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::cumulative NORMSINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse PEARSON | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL PERCENTILE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE PERCENTILE.EXC | **Not yet Implemented** PERCENTILE.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE PERCENTRANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK PERCENTRANK.EXC | **Not yet Implemented** PERCENTRANK.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK PERMUT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUT PERMUTATIONA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUTATIONA PHI | **Not yet Implemented** POISSON | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution POISSON.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution PROB | **Not yet Implemented** QUARTILE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE QUARTILE.EXC | **Not yet Implemented** QUARTILE.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE RANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK RANK.AVG | **Not yet Implemented** RANK.EQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK RSQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::RSQ SKEW | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::skew SKEW.P | **Not yet Implemented** SLOPE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::SLOPE SMALL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::small STANDARDIZE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Standardize::execute STDEV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV STDEV.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP STDEV.S | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV STDEVA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVA STDEVP | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP STDEVPA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVPA STEYX | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::STEYX T.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotDist T.DIST.2T | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotDistDot2T T.DIST.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotDistDotRT T.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotInv T.INV.2T | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse T.TEST | **Not yet Implemented** TDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::distribution TINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse TREND | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::TREND TRIMMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::trim TTEST | **Not yet Implemented** VAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR VAR.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP VAR.S | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR VARA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARA VARP | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP VARPA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARPA WEIBULL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution WEIBULL.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution Z.TEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest ZTEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest ## CATEGORY_TEXT_AND_DATA Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ARRAYTOTEXT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::fromArray ASC | **Not yet Implemented** BAHTTEXT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Thai::getBahtText CHAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::character CLEAN | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::nonPrintable CODE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::code CONCAT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::CONCATENATE CONCATENATE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::actualCONCATENATE DBCS | **Not yet Implemented** DOLLAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::DOLLAR EXACT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::exact FIND | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive FINDB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive FIXED | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::FIXEDFORMAT ISTHAIDIGIT | **Not yet Implemented** JIS | **Not yet Implemented** LEFT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left LEFTB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left LEN | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length LENB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length LOWER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::lower MID | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid MIDB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid NUMBERSTRING | **Not yet Implemented** NUMBERVALUE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::NUMBERVALUE PHONETIC | **Not yet Implemented** PROPER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::proper REPLACE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace REPLACEB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace REPT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::builtinREPT RIGHT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right RIGHTB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right SEARCH | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive SEARCHB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive SUBSTITUTE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::substitute T | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::test TEXT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::TEXTFORMAT TEXTAFTER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::after TEXTBEFORE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::before TEXTJOIN | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::TEXTJOIN TEXTSPLIT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::split THAIDIGIT | **Not yet Implemented** THAINUMSOUND | **Not yet Implemented** THAINUMSTRING | **Not yet Implemented** THAISTRINGLENGTH | **Not yet Implemented** TRIM | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::spaces UNICHAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::characterUnicode UNICODE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::codeUnicode UPPER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::upper VALUE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::VALUE VALUETOTEXT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::valueToText ## CATEGORY_WEB Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ENCODEURL | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::urlEncode FILTERXML | **Not yet Implemented** WEBSERVICE | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::webService ## CATEGORY_UNCATEGORISED Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ## CATEGORY_MICROSOFT_INTERNAL Excel Function | PhpSpreadsheet Function -------------------------|-------------------------------------- ANCHORARRAY | \PhpOffice\PhpSpreadsheet\Calculation\Internal\ExcelArrayPseudoFunctions::anchorArray SINGLE | \PhpOffice\PhpSpreadsheet\Calculation\Internal\ExcelArrayPseudoFunctions::single ================================================ FILE: docs/references/function-list-by-name-compact.md ================================================ # Function list by name compact Category should be prefixed by `CATEGORY_` to match the values in \PhpOffice\PhpSpreadsheet\Calculation\Category Function should be prefixed by `PhpOffice\PhpSpreadsheet\Calculation\` A less compact list can be found [here](./function-list-by-name.md) ## A Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- ABS | MATH_AND_TRIG | MathTrig\Absolute::evaluate ACCRINT | FINANCIAL | Financial\Securities\AccruedInterest::periodic ACCRINTM | FINANCIAL | Financial\Securities\AccruedInterest::atMaturity ACOS | MATH_AND_TRIG | MathTrig\Trig\Cosine::acos ACOSH | MATH_AND_TRIG | MathTrig\Trig\Cosine::acosh ACOT | MATH_AND_TRIG | MathTrig\Trig\Cotangent::acot ACOTH | MATH_AND_TRIG | MathTrig\Trig\Cotangent::acoth ADDRESS | LOOKUP_AND_REFERENCE | LookupRef\Address::cell AGGREGATE | MATH_AND_TRIG | **Not yet Implemented** AMORDEGRC | FINANCIAL | Financial\Amortization::AMORDEGRC AMORLINC | FINANCIAL | Financial\Amortization::AMORLINC ANCHORARRAY | MICROSOFT_INTERNAL | Internal\ExcelArrayPseudoFunctions::anchorArray AND | LOGICAL | Logical\Operations::logicalAnd ARABIC | MATH_AND_TRIG | MathTrig\Arabic::evaluate AREAS | LOOKUP_AND_REFERENCE | **Not yet Implemented** ARRAYTOTEXT | TEXT_AND_DATA | TextData\Text::fromArray ASC | TEXT_AND_DATA | **Not yet Implemented** ASIN | MATH_AND_TRIG | MathTrig\Trig\Sine::asin ASINH | MATH_AND_TRIG | MathTrig\Trig\Sine::asinh ATAN | MATH_AND_TRIG | MathTrig\Trig\Tangent::atan ATAN2 | MATH_AND_TRIG | MathTrig\Trig\Tangent::atan2 ATANH | MATH_AND_TRIG | MathTrig\Trig\Tangent::atanh AVEDEV | STATISTICAL | Statistical\Averages::averageDeviations AVERAGE | STATISTICAL | Statistical\Averages::average AVERAGEA | STATISTICAL | Statistical\Averages::averageA AVERAGEIF | STATISTICAL | Statistical\Conditional::AVERAGEIF AVERAGEIFS | STATISTICAL | Statistical\Conditional::AVERAGEIFS ## B Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- BAHTTEXT | TEXT_AND_DATA | TextData\Thai::getBahtText BASE | MATH_AND_TRIG | MathTrig\Base::evaluate BESSELI | ENGINEERING | Engineering\BesselI::BESSELI BESSELJ | ENGINEERING | Engineering\BesselJ::BESSELJ BESSELK | ENGINEERING | Engineering\BesselK::BESSELK BESSELY | ENGINEERING | Engineering\BesselY::BESSELY BETA.DIST | STATISTICAL | **Not yet Implemented** BETA.INV | STATISTICAL | Statistical\Distributions\Beta::inverse BETADIST | STATISTICAL | Statistical\Distributions\Beta::distribution BETAINV | STATISTICAL | Statistical\Distributions\Beta::inverse BIN2DEC | ENGINEERING | Engineering\ConvertBinary::toDecimal BIN2HEX | ENGINEERING | Engineering\ConvertBinary::toHex BIN2OCT | ENGINEERING | Engineering\ConvertBinary::toOctal BINOM.DIST | STATISTICAL | Statistical\Distributions\Binomial::distribution BINOM.DIST.RANGE | STATISTICAL | Statistical\Distributions\Binomial::range BINOM.INV | STATISTICAL | Statistical\Distributions\Binomial::inverse BINOMDIST | STATISTICAL | Statistical\Distributions\Binomial::distribution BITAND | ENGINEERING | Engineering\BitWise::BITAND BITLSHIFT | ENGINEERING | Engineering\BitWise::BITLSHIFT BITOR | ENGINEERING | Engineering\BitWise::BITOR BITRSHIFT | ENGINEERING | Engineering\BitWise::BITRSHIFT BITXOR | ENGINEERING | Engineering\BitWise::BITXOR BYCOL | LOGICAL | **Not yet Implemented** BYROW | LOGICAL | **Not yet Implemented** ## C Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- CEILING | MATH_AND_TRIG | MathTrig\Ceiling::ceiling CEILING.MATH | MATH_AND_TRIG | MathTrig\Ceiling::math CEILING.PRECISE | MATH_AND_TRIG | MathTrig\Ceiling::precise CELL | INFORMATION | **Not yet Implemented** CHAR | TEXT_AND_DATA | TextData\CharacterConvert::character CHIDIST | STATISTICAL | Statistical\Distributions\ChiSquared::distributionRightTail CHIINV | STATISTICAL | Statistical\Distributions\ChiSquared::inverseRightTail CHISQ.DIST | STATISTICAL | Statistical\Distributions\ChiSquared::distributionLeftTail CHISQ.DIST.RT | STATISTICAL | Statistical\Distributions\ChiSquared::distributionRightTail CHISQ.INV | STATISTICAL | Statistical\Distributions\ChiSquared::inverseLeftTail CHISQ.INV.RT | STATISTICAL | Statistical\Distributions\ChiSquared::inverseRightTail CHISQ.TEST | STATISTICAL | Statistical\Distributions\ChiSquared::test CHITEST | STATISTICAL | Statistical\Distributions\ChiSquared::test CHOOSE | LOOKUP_AND_REFERENCE | LookupRef\Selection::CHOOSE CHOOSECOLS | LOOKUP_AND_REFERENCE | LookupRef\ChooseRowsEtc::chooseCols CHOOSEROWS | LOOKUP_AND_REFERENCE | LookupRef\ChooseRowsEtc::chooseRows CLEAN | TEXT_AND_DATA | TextData\Trim::nonPrintable CODE | TEXT_AND_DATA | TextData\CharacterConvert::code COLUMN | LOOKUP_AND_REFERENCE | LookupRef\RowColumnInformation::COLUMN COLUMNS | LOOKUP_AND_REFERENCE | LookupRef\RowColumnInformation::COLUMNS COMBIN | MATH_AND_TRIG | MathTrig\Combinations::withoutRepetition COMBINA | MATH_AND_TRIG | MathTrig\Combinations::withRepetition COMPLEX | ENGINEERING | Engineering\Complex::COMPLEX CONCAT | TEXT_AND_DATA | TextData\Concatenate::CONCATENATE CONCATENATE | TEXT_AND_DATA | TextData\Concatenate::actualCONCATENATE CONFIDENCE | STATISTICAL | Statistical\Confidence::CONFIDENCE CONFIDENCE.NORM | STATISTICAL | Statistical\Confidence::CONFIDENCE CONFIDENCE.T | STATISTICAL | **Not yet Implemented** CONVERT | ENGINEERING | Engineering\ConvertUOM::CONVERT CORREL | STATISTICAL | Statistical\Trends::CORREL COS | MATH_AND_TRIG | MathTrig\Trig\Cosine::cos COSH | MATH_AND_TRIG | MathTrig\Trig\Cosine::cosh COT | MATH_AND_TRIG | MathTrig\Trig\Cotangent::cot COTH | MATH_AND_TRIG | MathTrig\Trig\Cotangent::coth COUNT | STATISTICAL | Statistical\Counts::COUNT COUNTA | STATISTICAL | Statistical\Counts::COUNTA COUNTBLANK | STATISTICAL | Statistical\Counts::COUNTBLANK COUNTIF | STATISTICAL | Statistical\Conditional::COUNTIF COUNTIFS | STATISTICAL | Statistical\Conditional::COUNTIFS COUPDAYBS | FINANCIAL | Financial\Coupons::COUPDAYBS COUPDAYS | FINANCIAL | Financial\Coupons::COUPDAYS COUPDAYSNC | FINANCIAL | Financial\Coupons::COUPDAYSNC COUPNCD | FINANCIAL | Financial\Coupons::COUPNCD COUPNUM | FINANCIAL | Financial\Coupons::COUPNUM COUPPCD | FINANCIAL | Financial\Coupons::COUPPCD COVAR | STATISTICAL | Statistical\Trends::COVAR COVARIANCE.P | STATISTICAL | Statistical\Trends::COVAR COVARIANCE.S | STATISTICAL | **Not yet Implemented** CRITBINOM | STATISTICAL | Statistical\Distributions\Binomial::inverse CSC | MATH_AND_TRIG | MathTrig\Trig\Cosecant::csc CSCH | MATH_AND_TRIG | MathTrig\Trig\Cosecant::csch CUBEKPIMEMBER | CUBE | **Not yet Implemented** CUBEMEMBER | CUBE | **Not yet Implemented** CUBEMEMBERPROPERTY | CUBE | **Not yet Implemented** CUBERANKEDMEMBER | CUBE | **Not yet Implemented** CUBESET | CUBE | **Not yet Implemented** CUBESETCOUNT | CUBE | **Not yet Implemented** CUBEVALUE | CUBE | **Not yet Implemented** CUMIPMT | FINANCIAL | Financial\CashFlow\Constant\Periodic\Cumulative::interest CUMPRINC | FINANCIAL | Financial\CashFlow\Constant\Periodic\Cumulative::principal ## D Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- DATE | DATE_AND_TIME | DateTimeExcel\Date::fromYMD DATEDIF | DATE_AND_TIME | DateTimeExcel\Difference::interval DATESTRING | DATE_AND_TIME | **Not yet Implemented** DATEVALUE | DATE_AND_TIME | DateTimeExcel\DateValue::fromString DAVERAGE | DATABASE | Database\DAverage::evaluate DAY | DATE_AND_TIME | DateTimeExcel\DateParts::day DAYS | DATE_AND_TIME | DateTimeExcel\Days::between DAYS360 | DATE_AND_TIME | DateTimeExcel\Days360::between DB | FINANCIAL | Financial\Depreciation::DB DBCS | TEXT_AND_DATA | **Not yet Implemented** DCOUNT | DATABASE | Database\DCount::evaluate DCOUNTA | DATABASE | Database\DCountA::evaluate DDB | FINANCIAL | Financial\Depreciation::DDB DEC2BIN | ENGINEERING | Engineering\ConvertDecimal::toBinary DEC2HEX | ENGINEERING | Engineering\ConvertDecimal::toHex DEC2OCT | ENGINEERING | Engineering\ConvertDecimal::toOctal DECIMAL | MATH_AND_TRIG | **Not yet Implemented** DEGREES | MATH_AND_TRIG | MathTrig\Angle::toDegrees DELTA | ENGINEERING | Engineering\Compare::DELTA DEVSQ | STATISTICAL | Statistical\Deviations::sumSquares DGET | DATABASE | Database\DGet::evaluate DISC | FINANCIAL | Financial\Securities\Rates::discount DMAX | DATABASE | Database\DMax::evaluate DMIN | DATABASE | Database\DMin::evaluate DOLLAR | TEXT_AND_DATA | TextData\Format::DOLLAR DOLLARDE | FINANCIAL | Financial\Dollar::decimal DOLLARFR | FINANCIAL | Financial\Dollar::fractional DPRODUCT | DATABASE | Database\DProduct::evaluate DROP | LOOKUP_AND_REFERENCE | LookupRef\ChooseRowsEtc::drop DSTDEV | DATABASE | Database\DStDev::evaluate DSTDEVP | DATABASE | Database\DStDevP::evaluate DSUM | DATABASE | Database\DSum::evaluate DURATION | FINANCIAL | **Not yet Implemented** DVAR | DATABASE | Database\DVar::evaluate DVARP | DATABASE | Database\DVarP::evaluate ## E Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- ECMA.CEILING | MATH_AND_TRIG | **Not yet Implemented** EDATE | DATE_AND_TIME | DateTimeExcel\Month::adjust EFFECT | FINANCIAL | Financial\InterestRate::effective ENCODEURL | WEB | Web\Service::urlEncode EOMONTH | DATE_AND_TIME | DateTimeExcel\Month::lastDay ERF | ENGINEERING | Engineering\Erf::ERF ERF.PRECISE | ENGINEERING | Engineering\Erf::ERFPRECISE ERFC | ENGINEERING | Engineering\ErfC::ERFC ERFC.PRECISE | ENGINEERING | Engineering\ErfC::ERFC ERROR.TYPE | INFORMATION | Information\ExcelError::type EVEN | MATH_AND_TRIG | MathTrig\Round::even EXACT | TEXT_AND_DATA | TextData\Text::exact EXP | MATH_AND_TRIG | MathTrig\Exp::evaluate EXPAND | LOOKUP_AND_REFERENCE | LookupRef\ChooseRowsEtc::expand EXPON.DIST | STATISTICAL | Statistical\Distributions\Exponential::distribution EXPONDIST | STATISTICAL | Statistical\Distributions\Exponential::distribution ## F Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- F.DIST | STATISTICAL | Statistical\Distributions\F::distribution F.DIST.RT | STATISTICAL | **Not yet Implemented** F.INV | STATISTICAL | **Not yet Implemented** F.INV.RT | STATISTICAL | **Not yet Implemented** F.TEST | STATISTICAL | **Not yet Implemented** FACT | MATH_AND_TRIG | MathTrig\Factorial::fact FACTDOUBLE | MATH_AND_TRIG | MathTrig\Factorial::factDouble FALSE | LOGICAL | Logical\Boolean::FALSE FDIST | STATISTICAL | **Not yet Implemented** FILTER | LOOKUP_AND_REFERENCE | LookupRef\Filter::filter FILTERXML | WEB | **Not yet Implemented** FIND | TEXT_AND_DATA | TextData\Search::sensitive FINDB | TEXT_AND_DATA | TextData\Search::sensitive FINV | STATISTICAL | **Not yet Implemented** FISHER | STATISTICAL | Statistical\Distributions\Fisher::distribution FISHERINV | STATISTICAL | Statistical\Distributions\Fisher::inverse FIXED | TEXT_AND_DATA | TextData\Format::FIXEDFORMAT FLOOR | MATH_AND_TRIG | MathTrig\Floor::floor FLOOR.MATH | MATH_AND_TRIG | MathTrig\Floor::math FLOOR.PRECISE | MATH_AND_TRIG | MathTrig\Floor::precise FORECAST | STATISTICAL | Statistical\Trends::FORECAST FORECAST.ETS | STATISTICAL | **Not yet Implemented** FORECAST.ETS.CONFINT | STATISTICAL | **Not yet Implemented** FORECAST.ETS.SEASONALITY | STATISTICAL | **Not yet Implemented** FORECAST.ETS.STAT | STATISTICAL | **Not yet Implemented** FORECAST.LINEAR | STATISTICAL | Statistical\Trends::FORECAST FORMULATEXT | LOOKUP_AND_REFERENCE | LookupRef\Formula::text FREQUENCY | STATISTICAL | **Not yet Implemented** FTEST | STATISTICAL | **Not yet Implemented** FV | FINANCIAL | Financial\CashFlow\Constant\Periodic::futureValue FVSCHEDULE | FINANCIAL | Financial\CashFlow\Single::futureValue ## G Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- GAMMA | STATISTICAL | Statistical\Distributions\Gamma::gamma GAMMA.DIST | STATISTICAL | Statistical\Distributions\Gamma::distribution GAMMA.INV | STATISTICAL | Statistical\Distributions\Gamma::inverse GAMMADIST | STATISTICAL | Statistical\Distributions\Gamma::distribution GAMMAINV | STATISTICAL | Statistical\Distributions\Gamma::inverse GAMMALN | STATISTICAL | Statistical\Distributions\Gamma::ln GAMMALN.PRECISE | STATISTICAL | Statistical\Distributions\Gamma::ln GAUSS | STATISTICAL | Statistical\Distributions\StandardNormal::gauss GCD | MATH_AND_TRIG | MathTrig\Gcd::evaluate GEOMEAN | STATISTICAL | Statistical\Averages\Mean::geometric GESTEP | ENGINEERING | Engineering\Compare::GESTEP GETPIVOTDATA | LOOKUP_AND_REFERENCE | **Not yet Implemented** GROUPBY | LOOKUP_AND_REFERENCE | **Not yet Implemented** GROWTH | STATISTICAL | Statistical\Trends::GROWTH ## H Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- HARMEAN | STATISTICAL | Statistical\Averages\Mean::harmonic HEX2BIN | ENGINEERING | Engineering\ConvertHex::toBinary HEX2DEC | ENGINEERING | Engineering\ConvertHex::toDecimal HEX2OCT | ENGINEERING | Engineering\ConvertHex::toOctal HLOOKUP | LOOKUP_AND_REFERENCE | LookupRef\HLookup::lookup HOUR | DATE_AND_TIME | DateTimeExcel\TimeParts::hour HSTACK | LOOKUP_AND_REFERENCE | LookupRef\Hstack::hstack HYPERLINK | LOOKUP_AND_REFERENCE | LookupRef\Hyperlink::set HYPGEOM.DIST | STATISTICAL | **Not yet Implemented** HYPGEOMDIST | STATISTICAL | Statistical\Distributions\HyperGeometric::distribution ## I Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- IF | LOGICAL | Logical\Conditional::statementIf IFERROR | LOGICAL | Logical\Conditional::IFERROR IFNA | LOGICAL | Logical\Conditional::IFNA IFS | LOGICAL | Logical\Conditional::IFS IMABS | ENGINEERING | Engineering\ComplexFunctions::IMABS IMAGINARY | ENGINEERING | Engineering\Complex::IMAGINARY IMARGUMENT | ENGINEERING | Engineering\ComplexFunctions::IMARGUMENT IMCONJUGATE | ENGINEERING | Engineering\ComplexFunctions::IMCONJUGATE IMCOS | ENGINEERING | Engineering\ComplexFunctions::IMCOS IMCOSH | ENGINEERING | Engineering\ComplexFunctions::IMCOSH IMCOT | ENGINEERING | Engineering\ComplexFunctions::IMCOT IMCSC | ENGINEERING | Engineering\ComplexFunctions::IMCSC IMCSCH | ENGINEERING | Engineering\ComplexFunctions::IMCSCH IMDIV | ENGINEERING | Engineering\ComplexOperations::IMDIV IMEXP | ENGINEERING | Engineering\ComplexFunctions::IMEXP IMLN | ENGINEERING | Engineering\ComplexFunctions::IMLN IMLOG10 | ENGINEERING | Engineering\ComplexFunctions::IMLOG10 IMLOG2 | ENGINEERING | Engineering\ComplexFunctions::IMLOG2 IMPOWER | ENGINEERING | Engineering\ComplexFunctions::IMPOWER IMPRODUCT | ENGINEERING | Engineering\ComplexOperations::IMPRODUCT IMREAL | ENGINEERING | Engineering\Complex::IMREAL IMSEC | ENGINEERING | Engineering\ComplexFunctions::IMSEC IMSECH | ENGINEERING | Engineering\ComplexFunctions::IMSECH IMSIN | ENGINEERING | Engineering\ComplexFunctions::IMSIN IMSINH | ENGINEERING | Engineering\ComplexFunctions::IMSINH IMSQRT | ENGINEERING | Engineering\ComplexFunctions::IMSQRT IMSUB | ENGINEERING | Engineering\ComplexOperations::IMSUB IMSUM | ENGINEERING | Engineering\ComplexOperations::IMSUM IMTAN | ENGINEERING | Engineering\ComplexFunctions::IMTAN INDEX | LOOKUP_AND_REFERENCE | LookupRef\Matrix::index INDIRECT | LOOKUP_AND_REFERENCE | LookupRef\Indirect::INDIRECT INFO | INFORMATION | Information\Info::getInfo INT | MATH_AND_TRIG | MathTrig\IntClass::evaluate INTERCEPT | STATISTICAL | Statistical\Trends::INTERCEPT INTRATE | FINANCIAL | Financial\Securities\Rates::interest IPMT | FINANCIAL | Financial\CashFlow\Constant\Periodic\Interest::payment IRR | FINANCIAL | Financial\CashFlow\Variable\Periodic::rate ISBLANK | INFORMATION | Information\Value::isBlank ISERR | INFORMATION | Information\ErrorValue::isErr ISERROR | INFORMATION | Information\ErrorValue::isError ISEVEN | INFORMATION | Information\Value::isEven ISFORMULA | INFORMATION | Information\Value::isFormula ISLOGICAL | INFORMATION | Information\Value::isLogical ISNA | INFORMATION | Information\ErrorValue::isNa ISNONTEXT | INFORMATION | Information\Value::isNonText ISNUMBER | INFORMATION | Information\Value::isNumber ISO.CEILING | MATH_AND_TRIG | **Not yet Implemented** ISODD | INFORMATION | Information\Value::isOdd ISOMITTED | INFORMATION | **Not yet Implemented** ISOWEEKNUM | DATE_AND_TIME | DateTimeExcel\Week::isoWeekNumber ISPMT | FINANCIAL | Financial\CashFlow\Constant\Periodic\Interest::schedulePayment ISREF | INFORMATION | Information\Value::isRef ISTEXT | INFORMATION | Information\Value::isText ISTHAIDIGIT | TEXT_AND_DATA | **Not yet Implemented** ## J Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- JIS | TEXT_AND_DATA | **Not yet Implemented** ## K Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- KURT | STATISTICAL | Statistical\Deviations::kurtosis ## L Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- LAMBDA | LOGICAL | **Not yet Implemented** LARGE | STATISTICAL | Statistical\Size::large LCM | MATH_AND_TRIG | MathTrig\Lcm::evaluate LEFT | TEXT_AND_DATA | TextData\Extract::left LEFTB | TEXT_AND_DATA | TextData\Extract::left LEN | TEXT_AND_DATA | TextData\Text::length LENB | TEXT_AND_DATA | TextData\Text::length LET | LOGICAL | **Not yet Implemented** LINEST | STATISTICAL | Statistical\Trends::LINEST LN | MATH_AND_TRIG | MathTrig\Logarithms::natural LOG | MATH_AND_TRIG | MathTrig\Logarithms::withBase LOG10 | MATH_AND_TRIG | MathTrig\Logarithms::base10 LOGEST | STATISTICAL | Statistical\Trends::LOGEST LOGINV | STATISTICAL | Statistical\Distributions\LogNormal::inverse LOGNORM.DIST | STATISTICAL | Statistical\Distributions\LogNormal::distribution LOGNORM.INV | STATISTICAL | Statistical\Distributions\LogNormal::inverse LOGNORMDIST | STATISTICAL | Statistical\Distributions\LogNormal::cumulative LOOKUP | LOOKUP_AND_REFERENCE | LookupRef\Lookup::lookup LOWER | TEXT_AND_DATA | TextData\CaseConvert::lower ## M Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- MAKEARRAY | LOGICAL | **Not yet Implemented** MAP | LOGICAL | **Not yet Implemented** MATCH | LOOKUP_AND_REFERENCE | LookupRef\ExcelMatch::MATCH MAX | STATISTICAL | Statistical\Maximum::max MAXA | STATISTICAL | Statistical\Maximum::maxA MAXIFS | STATISTICAL | Statistical\Conditional::MAXIFS MDETERM | MATH_AND_TRIG | MathTrig\MatrixFunctions::determinant MDURATION | FINANCIAL | **Not yet Implemented** MEDIAN | STATISTICAL | Statistical\Averages::median MEDIANIF | STATISTICAL | **Not yet Implemented** MID | TEXT_AND_DATA | TextData\Extract::mid MIDB | TEXT_AND_DATA | TextData\Extract::mid MIN | STATISTICAL | Statistical\Minimum::min MINA | STATISTICAL | Statistical\Minimum::minA MINIFS | STATISTICAL | Statistical\Conditional::MINIFS MINUTE | DATE_AND_TIME | DateTimeExcel\TimeParts::minute MINVERSE | MATH_AND_TRIG | MathTrig\MatrixFunctions::inverse MIRR | FINANCIAL | Financial\CashFlow\Variable\Periodic::modifiedRate MMULT | MATH_AND_TRIG | MathTrig\MatrixFunctions::multiply MOD | MATH_AND_TRIG | MathTrig\Operations::mod MODE | STATISTICAL | Statistical\Averages::mode MODE.MULT | STATISTICAL | **Not yet Implemented** MODE.SNGL | STATISTICAL | Statistical\Averages::mode MONTH | DATE_AND_TIME | DateTimeExcel\DateParts::month MROUND | MATH_AND_TRIG | MathTrig\Round::multiple MULTINOMIAL | MATH_AND_TRIG | MathTrig\Factorial::multinomial MUNIT | MATH_AND_TRIG | MathTrig\MatrixFunctions::identity ## N Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- N | INFORMATION | Information\Value::asNumber NA | INFORMATION | Information\ExcelError::NA NEGBINOM.DIST | STATISTICAL | **Not yet Implemented** NEGBINOMDIST | STATISTICAL | Statistical\Distributions\Binomial::negative NETWORKDAYS | DATE_AND_TIME | DateTimeExcel\NetworkDays::count NETWORKDAYS.INTL | DATE_AND_TIME | **Not yet Implemented** NOMINAL | FINANCIAL | Financial\InterestRate::nominal NORM.DIST | STATISTICAL | Statistical\Distributions\Normal::distribution NORM.INV | STATISTICAL | Statistical\Distributions\Normal::inverse NORM.S.DIST | STATISTICAL | Statistical\Distributions\StandardNormal::distribution NORM.S.INV | STATISTICAL | Statistical\Distributions\StandardNormal::inverse NORMDIST | STATISTICAL | Statistical\Distributions\Normal::distribution NORMINV | STATISTICAL | Statistical\Distributions\Normal::inverse NORMSDIST | STATISTICAL | Statistical\Distributions\StandardNormal::cumulative NORMSINV | STATISTICAL | Statistical\Distributions\StandardNormal::inverse NOT | LOGICAL | Logical\Operations::NOT NOW | DATE_AND_TIME | DateTimeExcel\Current::now NPER | FINANCIAL | Financial\CashFlow\Constant\Periodic::periods NPV | FINANCIAL | Financial\CashFlow\Variable\Periodic::presentValue NUMBERSTRING | TEXT_AND_DATA | **Not yet Implemented** NUMBERVALUE | TEXT_AND_DATA | TextData\Format::NUMBERVALUE ## O Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- OCT2BIN | ENGINEERING | Engineering\ConvertOctal::toBinary OCT2DEC | ENGINEERING | Engineering\ConvertOctal::toDecimal OCT2HEX | ENGINEERING | Engineering\ConvertOctal::toHex ODD | MATH_AND_TRIG | MathTrig\Round::odd ODDFPRICE | FINANCIAL | **Not yet Implemented** ODDFYIELD | FINANCIAL | **Not yet Implemented** ODDLPRICE | FINANCIAL | **Not yet Implemented** ODDLYIELD | FINANCIAL | **Not yet Implemented** OFFSET | LOOKUP_AND_REFERENCE | LookupRef\Offset::OFFSET OR | LOGICAL | Logical\Operations::logicalOr ## P Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- PDURATION | FINANCIAL | Financial\CashFlow\Single::periods PEARSON | STATISTICAL | Statistical\Trends::CORREL PERCENTILE | STATISTICAL | Statistical\Percentiles::PERCENTILE PERCENTILE.EXC | STATISTICAL | **Not yet Implemented** PERCENTILE.INC | STATISTICAL | Statistical\Percentiles::PERCENTILE PERCENTRANK | STATISTICAL | Statistical\Percentiles::PERCENTRANK PERCENTRANK.EXC | STATISTICAL | **Not yet Implemented** PERCENTRANK.INC | STATISTICAL | Statistical\Percentiles::PERCENTRANK PERMUT | STATISTICAL | Statistical\Permutations::PERMUT PERMUTATIONA | STATISTICAL | Statistical\Permutations::PERMUTATIONA PHI | STATISTICAL | **Not yet Implemented** PHONETIC | TEXT_AND_DATA | **Not yet Implemented** PI | MATH_AND_TRIG | pi PMT | FINANCIAL | Financial\CashFlow\Constant\Periodic\Payments::annuity POISSON | STATISTICAL | Statistical\Distributions\Poisson::distribution POISSON.DIST | STATISTICAL | Statistical\Distributions\Poisson::distribution POWER | MATH_AND_TRIG | MathTrig\Operations::power PPMT | FINANCIAL | Financial\CashFlow\Constant\Periodic\Payments::interestPayment PRICE | FINANCIAL | Financial\Securities\Price::price PRICEDISC | FINANCIAL | Financial\Securities\Price::priceDiscounted PRICEMAT | FINANCIAL | Financial\Securities\Price::priceAtMaturity PROB | STATISTICAL | **Not yet Implemented** PRODUCT | MATH_AND_TRIG | MathTrig\Operations::product PROPER | TEXT_AND_DATA | TextData\CaseConvert::proper PV | FINANCIAL | Financial\CashFlow\Constant\Periodic::presentValue ## Q Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- QUARTILE | STATISTICAL | Statistical\Percentiles::QUARTILE QUARTILE.EXC | STATISTICAL | **Not yet Implemented** QUARTILE.INC | STATISTICAL | Statistical\Percentiles::QUARTILE QUOTIENT | MATH_AND_TRIG | MathTrig\Operations::quotient ## R Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- RADIANS | MATH_AND_TRIG | MathTrig\Angle::toRadians RAND | MATH_AND_TRIG | MathTrig\Random::rand RANDARRAY | MATH_AND_TRIG | MathTrig\Random::randArray RANDBETWEEN | MATH_AND_TRIG | MathTrig\Random::randBetween RANK | STATISTICAL | Statistical\Percentiles::RANK RANK.AVG | STATISTICAL | **Not yet Implemented** RANK.EQ | STATISTICAL | Statistical\Percentiles::RANK RATE | FINANCIAL | Financial\CashFlow\Constant\Periodic\Interest::rate RECEIVED | FINANCIAL | Financial\Securities\Price::received REDUCE | LOGICAL | **Not yet Implemented** REPLACE | TEXT_AND_DATA | TextData\Replace::replace REPLACEB | TEXT_AND_DATA | TextData\Replace::replace REPT | TEXT_AND_DATA | TextData\Concatenate::builtinREPT RIGHT | TEXT_AND_DATA | TextData\Extract::right RIGHTB | TEXT_AND_DATA | TextData\Extract::right ROMAN | MATH_AND_TRIG | MathTrig\Roman::evaluate ROUND | MATH_AND_TRIG | MathTrig\Round::round ROUNDBAHTDOWN | MATH_AND_TRIG | **Not yet Implemented** ROUNDBAHTUP | MATH_AND_TRIG | **Not yet Implemented** ROUNDDOWN | MATH_AND_TRIG | MathTrig\Round::down ROUNDUP | MATH_AND_TRIG | MathTrig\Round::up ROW | LOOKUP_AND_REFERENCE | LookupRef\RowColumnInformation::ROW ROWS | LOOKUP_AND_REFERENCE | LookupRef\RowColumnInformation::ROWS RRI | FINANCIAL | Financial\CashFlow\Single::interestRate RSQ | STATISTICAL | Statistical\Trends::RSQ RTD | LOOKUP_AND_REFERENCE | **Not yet Implemented** ## S Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- SCAN | LOGICAL | **Not yet Implemented** SEARCH | TEXT_AND_DATA | TextData\Search::insensitive SEARCHB | TEXT_AND_DATA | TextData\Search::insensitive SEC | MATH_AND_TRIG | MathTrig\Trig\Secant::sec SECH | MATH_AND_TRIG | MathTrig\Trig\Secant::sech SECOND | DATE_AND_TIME | DateTimeExcel\TimeParts::second SEQUENCE | MATH_AND_TRIG | MathTrig\MatrixFunctions::sequence SERIESSUM | MATH_AND_TRIG | MathTrig\SeriesSum::evaluate SHEET | INFORMATION | **Not yet Implemented** SHEETS | INFORMATION | **Not yet Implemented** SIGN | MATH_AND_TRIG | MathTrig\Sign::evaluate SIN | MATH_AND_TRIG | MathTrig\Trig\Sine::sin SINGLE | MICROSOFT_INTERNAL | Internal\ExcelArrayPseudoFunctions::single SINH | MATH_AND_TRIG | MathTrig\Trig\Sine::sinh SKEW | STATISTICAL | Statistical\Deviations::skew SKEW.P | STATISTICAL | **Not yet Implemented** SLN | FINANCIAL | Financial\Depreciation::SLN SLOPE | STATISTICAL | Statistical\Trends::SLOPE SMALL | STATISTICAL | Statistical\Size::small SORT | LOOKUP_AND_REFERENCE | LookupRef\Sort::sort SORTBY | LOOKUP_AND_REFERENCE | LookupRef\Sort::sortBy SQRT | MATH_AND_TRIG | MathTrig\Sqrt::sqrt SQRTPI | MATH_AND_TRIG | MathTrig\Sqrt::pi STANDARDIZE | STATISTICAL | Statistical\Standardize::execute STDEV | STATISTICAL | Statistical\StandardDeviations::STDEV STDEV.P | STATISTICAL | Statistical\StandardDeviations::STDEVP STDEV.S | STATISTICAL | Statistical\StandardDeviations::STDEV STDEVA | STATISTICAL | Statistical\StandardDeviations::STDEVA STDEVP | STATISTICAL | Statistical\StandardDeviations::STDEVP STDEVPA | STATISTICAL | Statistical\StandardDeviations::STDEVPA STEYX | STATISTICAL | Statistical\Trends::STEYX SUBSTITUTE | TEXT_AND_DATA | TextData\Replace::substitute SUBTOTAL | MATH_AND_TRIG | MathTrig\Subtotal::evaluate SUM | MATH_AND_TRIG | MathTrig\Sum::sumErroringStrings SUMIF | MATH_AND_TRIG | Statistical\Conditional::SUMIF SUMIFS | MATH_AND_TRIG | Statistical\Conditional::SUMIFS SUMPRODUCT | MATH_AND_TRIG | MathTrig\Sum::product SUMSQ | MATH_AND_TRIG | MathTrig\SumSquares::sumSquare SUMX2MY2 | MATH_AND_TRIG | MathTrig\SumSquares::sumXSquaredMinusYSquared SUMX2PY2 | MATH_AND_TRIG | MathTrig\SumSquares::sumXSquaredPlusYSquared SUMXMY2 | MATH_AND_TRIG | MathTrig\SumSquares::sumXMinusYSquared SWITCH | LOGICAL | Logical\Conditional::statementSwitch SYD | FINANCIAL | Financial\Depreciation::SYD ## T Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- T | TEXT_AND_DATA | TextData\Text::test T.DIST | STATISTICAL | Statistical\Distributions\StudentT::tDotDist T.DIST.2T | STATISTICAL | Statistical\Distributions\StudentT::tDotDistDot2T T.DIST.RT | STATISTICAL | Statistical\Distributions\StudentT::tDotDistDotRT T.INV | STATISTICAL | Statistical\Distributions\StudentT::tDotInv T.INV.2T | STATISTICAL | Statistical\Distributions\StudentT::inverse T.TEST | STATISTICAL | **Not yet Implemented** TAKE | LOOKUP_AND_REFERENCE | LookupRef\ChooseRowsEtc::take TAN | MATH_AND_TRIG | MathTrig\Trig\Tangent::tan TANH | MATH_AND_TRIG | MathTrig\Trig\Tangent::tanh TBILLEQ | FINANCIAL | Financial\TreasuryBill::bondEquivalentYield TBILLPRICE | FINANCIAL | Financial\TreasuryBill::price TBILLYIELD | FINANCIAL | Financial\TreasuryBill::yield TDIST | STATISTICAL | Statistical\Distributions\StudentT::distribution TEXT | TEXT_AND_DATA | TextData\Format::TEXTFORMAT TEXTAFTER | TEXT_AND_DATA | TextData\Extract::after TEXTBEFORE | TEXT_AND_DATA | TextData\Extract::before TEXTJOIN | TEXT_AND_DATA | TextData\Concatenate::TEXTJOIN TEXTSPLIT | TEXT_AND_DATA | TextData\Text::split THAIDAYOFWEEK | DATE_AND_TIME | **Not yet Implemented** THAIDIGIT | TEXT_AND_DATA | **Not yet Implemented** THAIMONTHOFYEAR | DATE_AND_TIME | **Not yet Implemented** THAINUMSOUND | TEXT_AND_DATA | **Not yet Implemented** THAINUMSTRING | TEXT_AND_DATA | **Not yet Implemented** THAISTRINGLENGTH | TEXT_AND_DATA | **Not yet Implemented** THAIYEAR | DATE_AND_TIME | **Not yet Implemented** TIME | DATE_AND_TIME | DateTimeExcel\Time::fromHMS TIMEVALUE | DATE_AND_TIME | DateTimeExcel\TimeValue::fromString TINV | STATISTICAL | Statistical\Distributions\StudentT::inverse TOCOL | LOOKUP_AND_REFERENCE | LookupRef\TorowTocol::tocol TODAY | DATE_AND_TIME | DateTimeExcel\Current::today TOROW | LOOKUP_AND_REFERENCE | LookupRef\TorowTocol::torow TRANSPOSE | LOOKUP_AND_REFERENCE | LookupRef\Matrix::transpose TREND | STATISTICAL | Statistical\Trends::TREND TRIM | TEXT_AND_DATA | TextData\Trim::spaces TRIMMEAN | STATISTICAL | Statistical\Averages\Mean::trim TRUE | LOGICAL | Logical\Boolean::TRUE TRUNC | MATH_AND_TRIG | MathTrig\Trunc::evaluate TTEST | STATISTICAL | **Not yet Implemented** TYPE | INFORMATION | Information\Value::type ## U Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- UNICHAR | TEXT_AND_DATA | TextData\CharacterConvert::characterUnicode UNICODE | TEXT_AND_DATA | TextData\CharacterConvert::codeUnicode UNIQUE | LOOKUP_AND_REFERENCE | LookupRef\Unique::unique UPPER | TEXT_AND_DATA | TextData\CaseConvert::upper USDOLLAR | FINANCIAL | Financial\Dollar::format ## V Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- VALUE | TEXT_AND_DATA | TextData\Format::VALUE VALUETOTEXT | TEXT_AND_DATA | TextData\Format::valueToText VAR | STATISTICAL | Statistical\Variances::VAR VAR.P | STATISTICAL | Statistical\Variances::VARP VAR.S | STATISTICAL | Statistical\Variances::VAR VARA | STATISTICAL | Statistical\Variances::VARA VARP | STATISTICAL | Statistical\Variances::VARP VARPA | STATISTICAL | Statistical\Variances::VARPA VDB | FINANCIAL | **Not yet Implemented** VLOOKUP | LOOKUP_AND_REFERENCE | LookupRef\VLookup::lookup VSTACK | LOOKUP_AND_REFERENCE | LookupRef\Vstack::vstack ## W Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- WEBSERVICE | WEB | Web\Service::webService WEEKDAY | DATE_AND_TIME | DateTimeExcel\Week::day WEEKNUM | DATE_AND_TIME | DateTimeExcel\Week::number WEIBULL | STATISTICAL | Statistical\Distributions\Weibull::distribution WEIBULL.DIST | STATISTICAL | Statistical\Distributions\Weibull::distribution WORKDAY | DATE_AND_TIME | DateTimeExcel\WorkDay::date WORKDAY.INTL | DATE_AND_TIME | **Not yet Implemented** WRAPCOLS | MATH_AND_TRIG | **Not yet Implemented** WRAPROWS | MATH_AND_TRIG | **Not yet Implemented** ## X Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- XIRR | FINANCIAL | Financial\CashFlow\Variable\NonPeriodic::rate XLOOKUP | LOOKUP_AND_REFERENCE | **Not yet Implemented** XMATCH | LOOKUP_AND_REFERENCE | **Not yet Implemented** XNPV | FINANCIAL | Financial\CashFlow\Variable\NonPeriodic::presentValue XOR | LOGICAL | Logical\Operations::logicalXor ## Y Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- YEAR | DATE_AND_TIME | DateTimeExcel\DateParts::year YEARFRAC | DATE_AND_TIME | DateTimeExcel\YearFrac::fraction YIELD | FINANCIAL | **Not yet Implemented** YIELDDISC | FINANCIAL | Financial\Securities\Yields::yieldDiscounted YIELDMAT | FINANCIAL | Financial\Securities\Yields::yieldAtMaturity ## Z Excel Function | Category | PhpSpreadsheet Function -------------------------|-----------------------|-------------------------------------- Z.TEST | STATISTICAL | Statistical\Distributions\StandardNormal::zTest ZTEST | STATISTICAL | Statistical\Distributions\StandardNormal::zTest ================================================ FILE: docs/references/function-list-by-name.md ================================================ # Function list by name A more compact list can be found [here](./function-list-by-name-compact.md) ## A Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- ABS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Absolute::evaluate ACCRINT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::periodic ACCRINTM | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::atMaturity ACOS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acos ACOSH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acosh ACOT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acot ACOTH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acoth ADDRESS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address::cell AGGREGATE | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** AMORDEGRC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORDEGRC AMORLINC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORLINC ANCHORARRAY | CATEGORY_MICROSOFT_INTERNAL | \PhpOffice\PhpSpreadsheet\Calculation\Internal\ExcelArrayPseudoFunctions::anchorArray AND | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalAnd ARABIC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Arabic::evaluate AREAS | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** ARRAYTOTEXT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::fromArray ASC | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** ASIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asin ASINH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asinh ATAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan ATAN2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan2 ATANH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atanh AVEDEV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageDeviations AVERAGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::average AVERAGEA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageA AVERAGEIF | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIF AVERAGEIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIFS ## B Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- BAHTTEXT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Thai::getBahtText BASE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Base::evaluate BESSELI | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselI::BESSELI BESSELJ | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselJ::BESSELJ BESSELK | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselK::BESSELK BESSELY | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselY::BESSELY BETA.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** BETA.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse BETADIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::distribution BETAINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse BIN2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toDecimal BIN2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toHex BIN2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toOctal BINOM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution BINOM.DIST.RANGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::range BINOM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse BINOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution BITAND | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITAND BITLSHIFT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITLSHIFT BITOR | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITOR BITRSHIFT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITRSHIFT BITXOR | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITXOR BYCOL | CATEGORY_LOGICAL | **Not yet Implemented** BYROW | CATEGORY_LOGICAL | **Not yet Implemented** ## C Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- CEILING | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::ceiling CEILING.MATH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::math CEILING.PRECISE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::precise CELL | CATEGORY_INFORMATION | **Not yet Implemented** CHAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::character CHIDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail CHIINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail CHISQ.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionLeftTail CHISQ.DIST.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail CHISQ.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseLeftTail CHISQ.INV.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail CHISQ.TEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test CHITEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test CHOOSE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Selection::CHOOSE CHOOSECOLS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::chooseCols CHOOSEROWS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::chooseRows CLEAN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::nonPrintable CODE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::code COLUMN | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMN COLUMNS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMNS COMBIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withoutRepetition COMBINA | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withRepetition COMPLEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::COMPLEX CONCAT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::CONCATENATE CONCATENATE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::actualCONCATENATE CONFIDENCE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE CONFIDENCE.NORM | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE CONFIDENCE.T | CATEGORY_STATISTICAL | **Not yet Implemented** CONVERT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertUOM::CONVERT CORREL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL COS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cos COSH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cosh COT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::cot COTH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::coth COUNT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNT COUNTA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTA COUNTBLANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTBLANK COUNTIF | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIF COUNTIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIFS COUPDAYBS | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYBS COUPDAYS | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYS COUPDAYSNC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYSNC COUPNCD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNCD COUPNUM | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNUM COUPPCD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPPCD COVAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR COVARIANCE.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR COVARIANCE.S | CATEGORY_STATISTICAL | **Not yet Implemented** CRITBINOM | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse CSC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csc CSCH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csch CUBEKPIMEMBER | CATEGORY_CUBE | **Not yet Implemented** CUBEMEMBER | CATEGORY_CUBE | **Not yet Implemented** CUBEMEMBERPROPERTY | CATEGORY_CUBE | **Not yet Implemented** CUBERANKEDMEMBER | CATEGORY_CUBE | **Not yet Implemented** CUBESET | CATEGORY_CUBE | **Not yet Implemented** CUBESETCOUNT | CATEGORY_CUBE | **Not yet Implemented** CUBEVALUE | CATEGORY_CUBE | **Not yet Implemented** CUMIPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::interest CUMPRINC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::principal ## D Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- DATE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Date::fromYMD DATEDIF | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Difference::interval DATESTRING | CATEGORY_DATE_AND_TIME | **Not yet Implemented** DATEVALUE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateValue::fromString DAVERAGE | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage::evaluate DAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::day DAYS | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days::between DAYS360 | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days360::between DB | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DB DBCS | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** DCOUNT | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCount::evaluate DCOUNTA | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCountA::evaluate DDB | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DDB DEC2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toBinary DEC2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toHex DEC2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toOctal DECIMAL | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** DEGREES | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toDegrees DELTA | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::DELTA DEVSQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::sumSquares DGET | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DGet::evaluate DISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::discount DMAX | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMax::evaluate DMIN | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMin::evaluate DOLLAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::DOLLAR DOLLARDE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::decimal DOLLARFR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::fractional DPRODUCT | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DProduct::evaluate DROP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::drop DSTDEV | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDev::evaluate DSTDEVP | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDevP::evaluate DSUM | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DSum::evaluate DURATION | CATEGORY_FINANCIAL | **Not yet Implemented** DVAR | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVar::evaluate DVARP | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVarP::evaluate ## E Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- ECMA.CEILING | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** EDATE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::adjust EFFECT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::effective ENCODEURL | CATEGORY_WEB | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::urlEncode EOMONTH | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::lastDay ERF | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERF ERF.PRECISE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERFPRECISE ERFC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC ERFC.PRECISE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC ERROR.TYPE | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError::type EVEN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::even EXACT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::exact EXP | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp::evaluate EXPAND | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::expand EXPON.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution EXPONDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution ## F Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- F.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F::distribution F.DIST.RT | CATEGORY_STATISTICAL | **Not yet Implemented** F.INV | CATEGORY_STATISTICAL | **Not yet Implemented** F.INV.RT | CATEGORY_STATISTICAL | **Not yet Implemented** F.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** FACT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::fact FACTDOUBLE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::factDouble FALSE | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::FALSE FDIST | CATEGORY_STATISTICAL | **Not yet Implemented** FILTER | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Filter::filter FILTERXML | CATEGORY_WEB | **Not yet Implemented** FIND | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive FINDB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive FINV | CATEGORY_STATISTICAL | **Not yet Implemented** FISHER | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::distribution FISHERINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::inverse FIXED | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::FIXEDFORMAT FLOOR | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::floor FLOOR.MATH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::math FLOOR.PRECISE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::precise FORECAST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST FORECAST.ETS | CATEGORY_STATISTICAL | **Not yet Implemented** FORECAST.ETS.CONFINT | CATEGORY_STATISTICAL | **Not yet Implemented** FORECAST.ETS.SEASONALITY | CATEGORY_STATISTICAL | **Not yet Implemented** FORECAST.ETS.STAT | CATEGORY_STATISTICAL | **Not yet Implemented** FORECAST.LINEAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST FORMULATEXT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Formula::text FREQUENCY | CATEGORY_STATISTICAL | **Not yet Implemented** FTEST | CATEGORY_STATISTICAL | **Not yet Implemented** FV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::futureValue FVSCHEDULE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::futureValue ## G Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- GAMMA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::gamma GAMMA.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution GAMMA.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse GAMMADIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution GAMMAINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse GAMMALN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln GAMMALN.PRECISE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln GAUSS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::gauss GCD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Gcd::evaluate GEOMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::geometric GESTEP | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::GESTEP GETPIVOTDATA | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** GROUPBY | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** GROWTH | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::GROWTH ## H Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- HARMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::harmonic HEX2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toBinary HEX2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toDecimal HEX2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toOctal HLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup::lookup HOUR | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::hour HSTACK | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Hstack::hstack HYPERLINK | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Hyperlink::set HYPGEOM.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** HYPGEOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\HyperGeometric::distribution ## I Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- IF | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementIf IFERROR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFERROR IFNA | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFNA IFS | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFS IMABS | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMABS IMAGINARY | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMAGINARY IMARGUMENT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMARGUMENT IMCONJUGATE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCONJUGATE IMCOS | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOS IMCOSH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOSH IMCOT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOT IMCSC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSC IMCSCH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSCH IMDIV | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMDIV IMEXP | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMEXP IMLN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLN IMLOG10 | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG10 IMLOG2 | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG2 IMPOWER | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMPOWER IMPRODUCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMPRODUCT IMREAL | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMREAL IMSEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSEC IMSECH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSECH IMSIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSIN IMSINH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSINH IMSQRT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSQRT IMSUB | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUB IMSUM | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUM IMTAN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMTAN INDEX | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::index INDIRECT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect::INDIRECT INFO | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Info::getInfo INT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\IntClass::evaluate INTERCEPT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::INTERCEPT INTRATE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::interest IPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::payment IRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::rate ISBLANK | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isBlank ISERR | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue::isErr ISERROR | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue::isError ISEVEN | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isEven ISFORMULA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isFormula ISLOGICAL | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isLogical ISNA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue::isNa ISNONTEXT | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isNonText ISNUMBER | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isNumber ISO.CEILING | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** ISODD | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isOdd ISOMITTED | CATEGORY_INFORMATION | **Not yet Implemented** ISOWEEKNUM | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::isoWeekNumber ISPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::schedulePayment ISREF | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isRef ISTEXT | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::isText ISTHAIDIGIT | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** ## J Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- JIS | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** ## K Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- KURT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::kurtosis ## L Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- LAMBDA | CATEGORY_LOGICAL | **Not yet Implemented** LARGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::large LCM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Lcm::evaluate LEFT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left LEFTB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left LEN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length LENB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length LET | CATEGORY_LOGICAL | **Not yet Implemented** LINEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LINEST LN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::natural LOG | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::withBase LOG10 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::base10 LOGEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LOGEST LOGINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse LOGNORM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::distribution LOGNORM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse LOGNORMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::cumulative LOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup::lookup LOWER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::lower ## M Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- MAKEARRAY | CATEGORY_LOGICAL | **Not yet Implemented** MAP | CATEGORY_LOGICAL | **Not yet Implemented** MATCH | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ExcelMatch::MATCH MAX | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::max MAXA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::maxA MAXIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MAXIFS MDETERM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::determinant MDURATION | CATEGORY_FINANCIAL | **Not yet Implemented** MEDIAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::median MEDIANIF | CATEGORY_STATISTICAL | **Not yet Implemented** MID | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid MIDB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid MIN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::min MINA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::minA MINIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MINIFS MINUTE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::minute MINVERSE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::inverse MIRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::modifiedRate MMULT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::multiply MOD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::mod MODE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode MODE.MULT | CATEGORY_STATISTICAL | **Not yet Implemented** MODE.SNGL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode MONTH | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::month MROUND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::multiple MULTINOMIAL | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::multinomial MUNIT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::identity ## N Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- N | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::asNumber NA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError::NA NEGBINOM.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** NEGBINOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::negative NETWORKDAYS | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\NetworkDays::count NETWORKDAYS.INTL | CATEGORY_DATE_AND_TIME | **Not yet Implemented** NOMINAL | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::nominal NORM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution NORM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse NORM.S.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::distribution NORM.S.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse NORMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution NORMINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse NORMSDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::cumulative NORMSINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse NOT | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::NOT NOW | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::now NPER | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::periods NPV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::presentValue NUMBERSTRING | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** NUMBERVALUE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::NUMBERVALUE ## O Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- OCT2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toBinary OCT2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toDecimal OCT2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toHex ODD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::odd ODDFPRICE | CATEGORY_FINANCIAL | **Not yet Implemented** ODDFYIELD | CATEGORY_FINANCIAL | **Not yet Implemented** ODDLPRICE | CATEGORY_FINANCIAL | **Not yet Implemented** ODDLYIELD | CATEGORY_FINANCIAL | **Not yet Implemented** OFFSET | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset::OFFSET OR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalOr ## P Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- PDURATION | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::periods PEARSON | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL PERCENTILE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE PERCENTILE.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** PERCENTILE.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE PERCENTRANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK PERCENTRANK.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** PERCENTRANK.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK PERMUT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUT PERMUTATIONA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUTATIONA PHI | CATEGORY_STATISTICAL | **Not yet Implemented** PHONETIC | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** PI | CATEGORY_MATH_AND_TRIG | pi PMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::annuity POISSON | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution POISSON.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution POWER | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::power PPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::interestPayment PRICE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::price PRICEDISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceDiscounted PRICEMAT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceAtMaturity PROB | CATEGORY_STATISTICAL | **Not yet Implemented** PRODUCT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::product PROPER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::proper PV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::presentValue ## Q Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- QUARTILE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE QUARTILE.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** QUARTILE.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE QUOTIENT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::quotient ## R Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- RADIANS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toRadians RAND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::rand RANDARRAY | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::randArray RANDBETWEEN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::randBetween RANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK RANK.AVG | CATEGORY_STATISTICAL | **Not yet Implemented** RANK.EQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK RATE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::rate RECEIVED | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::received REDUCE | CATEGORY_LOGICAL | **Not yet Implemented** REPLACE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace REPLACEB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace REPT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::builtinREPT RIGHT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right RIGHTB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right ROMAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Roman::evaluate ROUND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::round ROUNDBAHTDOWN | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** ROUNDBAHTUP | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** ROUNDDOWN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::down ROUNDUP | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::up ROW | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROW ROWS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROWS RRI | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::interestRate RSQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::RSQ RTD | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** ## S Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- SCAN | CATEGORY_LOGICAL | **Not yet Implemented** SEARCH | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive SEARCHB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive SEC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sec SECH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sech SECOND | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::second SEQUENCE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::sequence SERIESSUM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SeriesSum::evaluate SHEET | CATEGORY_INFORMATION | **Not yet Implemented** SHEETS | CATEGORY_INFORMATION | **Not yet Implemented** SIGN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sign::evaluate SIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sin SINGLE | CATEGORY_MICROSOFT_INTERNAL | \PhpOffice\PhpSpreadsheet\Calculation\Internal\ExcelArrayPseudoFunctions::single SINH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sinh SKEW | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::skew SKEW.P | CATEGORY_STATISTICAL | **Not yet Implemented** SLN | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SLN SLOPE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::SLOPE SMALL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::small SORT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Sort::sort SORTBY | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Sort::sortBy SQRT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::sqrt SQRTPI | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::pi STANDARDIZE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Standardize::execute STDEV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV STDEV.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP STDEV.S | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV STDEVA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVA STDEVP | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP STDEVPA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVPA STEYX | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::STEYX SUBSTITUTE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::substitute SUBTOTAL | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Subtotal::evaluate SUM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::sumErroringStrings SUMIF | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIF SUMIFS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIFS SUMPRODUCT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::product SUMSQ | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumSquare SUMX2MY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredMinusYSquared SUMX2PY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredPlusYSquared SUMXMY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXMinusYSquared SWITCH | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementSwitch SYD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SYD ## T Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- T | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::test T.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotDist T.DIST.2T | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotDistDot2T T.DIST.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotDistDotRT T.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::tDotInv T.INV.2T | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse T.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** TAKE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ChooseRowsEtc::take TAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tan TANH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tanh TBILLEQ | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::bondEquivalentYield TBILLPRICE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::price TBILLYIELD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::yield TDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::distribution TEXT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::TEXTFORMAT TEXTAFTER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::after TEXTBEFORE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::before TEXTJOIN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::TEXTJOIN TEXTSPLIT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::split THAIDAYOFWEEK | CATEGORY_DATE_AND_TIME | **Not yet Implemented** THAIDIGIT | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** THAIMONTHOFYEAR | CATEGORY_DATE_AND_TIME | **Not yet Implemented** THAINUMSOUND | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** THAINUMSTRING | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** THAISTRINGLENGTH | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** THAIYEAR | CATEGORY_DATE_AND_TIME | **Not yet Implemented** TIME | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Time::fromHMS TIMEVALUE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeValue::fromString TINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse TOCOL | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\TorowTocol::tocol TODAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::today TOROW | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\TorowTocol::torow TRANSPOSE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::transpose TREND | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::TREND TRIM | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::spaces TRIMMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::trim TRUE | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::TRUE TRUNC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trunc::evaluate TTEST | CATEGORY_STATISTICAL | **Not yet Implemented** TYPE | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Information\Value::type ## U Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- UNICHAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::characterUnicode UNICODE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::codeUnicode UNIQUE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Unique::unique UPPER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::upper USDOLLAR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::format ## V Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- VALUE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::VALUE VALUETOTEXT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::valueToText VAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR VAR.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP VAR.S | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR VARA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARA VARP | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP VARPA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARPA VDB | CATEGORY_FINANCIAL | **Not yet Implemented** VLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup::lookup VSTACK | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Vstack::vstack ## W Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- WEBSERVICE | CATEGORY_WEB | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::webService WEEKDAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::day WEEKNUM | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::number WEIBULL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution WEIBULL.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution WORKDAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\WorkDay::date WORKDAY.INTL | CATEGORY_DATE_AND_TIME | **Not yet Implemented** WRAPCOLS | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** WRAPROWS | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** ## X Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- XIRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::rate XLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** XMATCH | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** XNPV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::presentValue XOR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalXor ## Y Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- YEAR | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::year YEARFRAC | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\YearFrac::fraction YIELD | CATEGORY_FINANCIAL | **Not yet Implemented** YIELDDISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldDiscounted YIELDMAT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldAtMaturity ## Z Excel Function | Category | PhpSpreadsheet Function -------------------------|--------------------------------|-------------------------------------- Z.TEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest ZTEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest ================================================ FILE: docs/topics/Behind the Mask.md ================================================ # Behind the Mask When we look at a spreadsheet in MS Excel, we normally see it neatly formatted so that it is easy for a human to read. Internally, that spreadsheet comprises a set of values that are normally either numbers or text (occasionally boolean `TRUE` or `FALSE`); or a formula that results in a number, text or boolean value. Unlike PHP, MS Excel doesn't differentiate between `integer` or `float`; but all numbers can be presented as integer or with decimals, as dates or percentages, as currency, even made to look like telephone numbers. A zero value can be made to look like `0` or `0.00`, like `-`, or even like a text string `zero`. Positive values can be displayed in one colour, negative values in another. ![Stock Portfolio.png](images/Behind the Mask/Stock Portfolio.png) Behind this Stock Portfolio table example, with the exception of the headings and the stock symbols, every value is a number; but each column is rendered in a manner that provides meaning to our human eye - `Purchase Date` as a day-month-year date; `Purchase Price` and `Current Price` as monetary values with a currency code; `Purchase Quantity` as an integer value and `Difference` as a float with 2 decimals; `% Return` as a percentage; and `Profit/Loss` as a monetary value with a currency code, thousands separator, and negative values highlighted in red; `Stdev` with 3 decimals - and all styled by using a Number Format Mask. ## Reading a Cell Value PhpSpreadsheet provides three methods for reading a Cell value. If we use the Cell's `getValue()` method, we are retrieving the underlying value (or the formula) for that cell. If the Cell contains a formula, then we can use the `getCalculatedValue()` method to see the result of evaluating that formula. If we want to see the value as it is displayed in MS Excel, then we need to use `getFormattedValue()`. Reading Cells from the Worksheet shown above: ```php var_dump($worksheet->getCell('C4')->getValue()); var_dump($worksheet->getCell('C4')->getCalculatedValue()); var_dump($worksheet->getCell('C4')->getFormattedValue()); var_dump($worksheet->getCell('H4')->getValue()); var_dump($worksheet->getCell('H4')->getCalculatedValue()); var_dump($worksheet->getCell('H4')->getFormattedValue()); ``` we see the different results for cell `C4` (a simple numeric value formatted as a Currency) and cell `H4` (a formula that evaluates to a numeric value, and formatted as a Currency): ``` float(26.19) float(26.19) string(9) "€ 26.19" string(8) "=$F4*$D4" float(-170) string(11) "€ -170.00" ``` Note that getting the formatted value will always evaluate a formula to render the result. ### Reading a Cell's Formatting Mask PhpSpreadsheet also provides methods that allow us to look at the format mask itself: ```php var_dump($worksheet->getCell('C4') ->getStyle()->getNumberFormat()->getFormatCode()); var_dump($worksheet->getCell('H4') ->getStyle()->getNumberFormat()->getFormatCode()); ``` and we can see the Format Masks for those cells: ``` string(20) "[$€-413]\ #,##0.00" string(48) "[$€-413]\ #,##0.00;[Red][$€-413]\ \-#,##0.00" ``` > **Note**: that the space and sign in the mask are non-breaking characters, so they are rendered to output as "\ " and "\-" respectively when var_dumped. This prevents breaking the displayed value across two lines. ## Setting a Cell's Formatting Mask When you are using a spreadsheet application like MS Excel, the application will try to decide what Format Mask should be used for a cell as you enter the value, based on that value and your locale settings; and with varying degrees of success. If the value looks like a Currency, then it will be converted to a number and an appropriate Currency Mask set; similarly if you type something that looks like a percentage; and it is often a joke that Excel identifies many values as Dates (even if that was never the intent), and sets a Date Format Mask. The default Mask if no specific type can be identified from the value is "General". PhpSpreadsheet doesn't do this by default. If you enter a value in a cell, then it will not convert that value from a string containing a currency symbol to a number: it will remain a string. Nor will it change any existing Format Mask: and if that value is a new cell, then it will be assigned a default Format Mask of "General". It will convert a string value to a numeric if it looks like a number with or without decimals (but without leading zeroes), or in scientific format; but it still won't change the Format Mask. ```php // Set Cell C21 using a formatted string value $worksheet->getCell('C20')->setValue('€ -1234.567'); // The Cell value should be the string that we set var_dump($worksheet->getCell('C20')->getValue()); // The Format Mask should be "General" var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // The formatted value should still be the string that we set var_dump($worksheet->getCell('C20')->getFormattedValue()); // Set Cell C21 using a numeric value $worksheet->getCell('C21')->setValue('-1234.567'); // The numeric string value should have been converted to a float var_dump($worksheet->getCell('C21')->getValue()); // The Format Mask should be "General" var_dump($worksheet->getCell('C21') ->getStyle()->getNumberFormat()->getFormatCode()); var_dump($worksheet->getCell('C21')->getFormattedValue()); // Change the Format Mask for C21 to a Currency mask $worksheet->getCell('C21') ->getStyle()->getNumberFormat()->setFormatCode('€ #,##0;€ -#,##0'); // The float value should still be the same var_dump($worksheet->getCell('C21')->getValue()); // The Format Mask should be the new mask that we set var_dump($worksheet->getCell('C21') ->getStyle()->getNumberFormat()->getFormatCode()); // The value should now be formatted as a Currency var_dump($worksheet->getCell('C21')->getFormattedValue()); ``` giving ```php string(13) "€ -1234.567" string(7) "General" string(13) "€ -1234.567" float(-1234.567) string(7) "General" string(9) "-1234.567" float(-1234.567) string(20) "€ #,##0;€ -#,##0" string(10) "€ -1,235" ``` If you wish to emulate the MS Excel behaviour, and automatically convert string values that represent Currency, Dates, Fractions, Percentages, etc. then the Advanced Value Binder attempts to identify these, to convert to a number, and to set an appropriate Format Mask. You can do this by changing the Value Binder, which will then apply every time you set a Cell value. ```php // Old method using static property Cell::setValueBinder(new AdvancedValueBinder()); // Preferred method using dynamic property since 3.4.0 $spreadsheet->setValueBinder(new AdvancedValueBinder()); // Set Cell C21 using a formatted string value $worksheet->getCell('C20')->setValue('€ -12345.6789'); // The Cell value is a float of -12345.6789 var_dump($worksheet->getCell('C20')->getValue()); // The format code is "[$€]#,##0.00_-" var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // The formatted value is "€-12,345.68 " var_dump($worksheet->getCell('C20')->getFormattedValue()); ``` Or (since version 1.28.0) you can specify a Value Binder to use just for that one call to set the Cell's value. ```php // Set Cell C21 using a formatted string value, but using a Value Binder $worksheet->getCell('C20')->setValue('€ -12345.6789', new AdvancedValueBinder()); // The Cell value is a float of -12345.6789 var_dump($worksheet->getCell('C20')->getValue()); // The format code is "[$€]#,##0.00_-" var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // The formatted value is "€-12,345.68 " var_dump($worksheet->getCell('C20')->getFormattedValue()); ``` While PhpSpreadsheet's Advanced Value Binder isn't as "sophisticated" as MS Excel at recognising formats that should be converted to numbers, or at setting a mask that exactly matches the entered value, it can simplify entering data from formatted strings; and is particularly useful when reading untyped or loosely formatted files like a CSV. > **Warning**: Remember that setting a Cell value explicitly bypasses the Value Binder, so you will always have to set the Format Mask manually if you are using `setValueExplicit()` to set Cell values. ## Using Formatting Masks in the TEXT() Function We can also use Number Formatting Masks directly in Excel's `TEXT()` Function, without setting the mask for a Cell. ```php $worksheet->getCell('A1')->setValue(12345.678); $worksheet->getCell('B1') ->setValue('#.00" Surplus";-#.00" Deficit";"Out of Stock"'); $worksheet->getCell('C1')->setValue('=TEXT(A1,B1)'); var_dump($worksheet->getCell('C1')->getCalculatedValue()); // 12,345.68 Surplus $worksheet->getCell('A2')->setValue(-12345.678); $worksheet->getCell('C2') ->setValue('=TEXT(A2,"#,##0.00"" Surplus"";-#,##0.00"" Deficit"";""Out of Stock""")'); var_dump($worksheet->getCell('C2')->getCalculatedValue()); // -12,345.68 Deficit ``` Remember that you'll need to escape double quotes in the mask argument by double double-quoting them if you pass the mask directly as an string. It's generally easier to read if you store the mask as text in a cell, and then pass the cell reference as the mask argument. ## Changing a Cell's Formatting Mask In PhpSpreadsheet we can change a Cell's Formatting Mask at any time just by setting a new FormatCode for that Cell. The library provides a number of "pre-defined" Masks as Constants in the `NumberFormat` class, prefixed with 'FORMAT_', but isn't limited to these values - the mask itself is just a string value - and the value passed to `setFormatCode()` can be any valid Excel Format Mask string. > **Note**: The Mask value isn't validated: it's up to you, as the developer, to ensure that you set a meaningful Mask value. And while Excel applies an initial Mask to every Cell when we enter a value (even if it's just the default "General"), we can still always change that Mask. This is managed through the "Number" block in the "Home" ribbon. ![Excel Number Format.png](images/Behind the Mask/Excel Number Format.png) This provides us with some simple options for increasing or decreasing the number of decimals displayed, if we want a thousands separator, a currency code to use, etc. But if we use the "pull down" for that block, we access the "Number" tab of "Format Cells" that provides a lot more options. ![Excel Number Format - General.png](images/Behind the Mask/Excel Number Format - General.png) This gives us access to a number of "Wizards" for different "Categories" of masking, as well as "Custom", which allows us to build our own masks. Since version 1.28.0, PhpSpreadsheet has also provided a set of "Wizards", allowing for the easier creation of Mask values for most Categories. In many cases, you will need to enable PHP's `Intl` extension in order to use the Wizards. ## Mask Categories I'll describe "Custom" Mask values later in this article; but let's take a look at the "Wizard" options for each "Category" first. ### General This is the default Mask, and is "adaptive". Numbers will appear with as many decimals as have been entered for the value (to the limit of a 9 or 10 digit display; additional decimals will be rounded), while very large or very small values will display in Scientific format. ### Number Excel's Number "Wizard" allows you to specify the number of decimals, and whether to use a thousands separator (or not). It also offers a few ways to display negative values (with or without a sign, highlighted in red). ![Excel Number Format - Number.png](images/Behind the Mask/Excel Number Format - Number.png) A typical mask will look something like '0.00' (2 decimals, with no thousands separator) or '#,##0.000' (3 decimals with a thousands separator). The PhpSpreadsheet Number "Wizard" allows you to specify the number of decimals, and the use of a thousands separator. The defaults are 2 decimal places, and to use a thousands separator. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number; // Set Cell value $worksheet->getCell('C20')->setValue(-12345.67890); // Set Cell Style using the Number Wizard to build the Format Mask $worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->setFormatCode((string) new Number(3, Number::WITH_THOUSANDS_SEPARATOR)); var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // "#,##0.000" var_dump($worksheet->getCell('C20')->getFormattedValue()); // "-12,345.679" ``` PhpSpreadsheet's Number Wizard doesn't yet offer options for displaying negative values; they will simply be masked so that they always display the sign. But alternative masking for negative values is an option that may be added in the future. ### Currency The Currency "Wizard" in MS Excel has similar options to the Number "Wizard", but also requires that you specify a currency code. ![Excel Number Format - Currency.png](images/Behind the Mask/Excel Number Format - Currency.png) The "Symbol" dropdown provides a lot of locale-specific variants of the same currencies - for example '€ Netherlands', where the currency symbol is displayed before the value, and any negative sign appears before the currency "-€ 12,345.68"; or '€ France', where the symbol is displayed after the value "-12,345.68 €". The PhpSpreadsheet Currency "Wizard" allows you to specify the currency code, number of decimals, and the use of a thousands separator. In addition, optionally, you can also specify whether the currency symbol should be leading or trailing, and whether it should be separated from the value or not. Finally, you have a choice of 4 ways of specifying negative values - minus sign, minus sign with the field in red, parentheses, and parentheses with the field in red. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number; // Set Cell value $worksheet->getCell('C20')->setValue(-12345.67890); // Set Cell Style using the Currency Wizard to build the Format Mask $currencyMask = new Currency( '€', 2, Number::WITH_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING ); $worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->setFormatCode($currencyMask); var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // #,##0.00 € var_dump($worksheet->getCell('C20')->getFormattedValue()); // -12,345.68 € ``` A typical Currency mask might look something like '#,##0.00 €', with the currency symbol as a literal. The Currency Code itself may be a literal character, as here with the `€` symbol; or it can be wrapped in square braces with a `$` symbol to indicate that this is a currency and the next character as the currency symbol to use, and then (optionally) a locale code or an LCID (Locale ID) like `[$€-de-DE]` or `[$€-1031]`. I wouldn't recommend using LCIDs in your code, a locale code is a lot easier to recognise and understand; but if you do need to reference LCIDs, then you can find a list [here](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a). Alternatively, if you have PHP's `Intl` extension installed, you can specify a currency code and a locale code. If you use this option, then locale values must be a valid formatted locale string (e.g. `en-GB`, `fr`, `uz-Arab-AF`); and the Wizard will use the format defined in ICU (International Components for Unicode): any values that you provide for placement of the currency symbol, etc. will be ignored. The only argument that won't be ignored is an explicit value of 0 for the decimals, which will create a mask to display only major currency units. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number; // Set Cell value $worksheet->getCell('C21')->setValue(-12345.67890); // Set Cell Style using the Currency Wizard to build the Format Mask for a locale $localeCurrencyMask = new Currency( '€', locale: 'de_DE' ); $worksheet->getCell('C21') ->getStyle()->getNumberFormat() ->setFormatCode($localeCurrencyMask); var_dump($worksheet->getCell('C21') ->getStyle()->getNumberFormat()->getFormatCode()); // #,##0.00 [$€-de-DE] var_dump($worksheet->getCell('C21')->getFormattedValue()); // -12,345.68 € ``` If we use the locale in the "Wizard", then a typical mask might look like '#,##0.00 [$€-de-DE]', with the currency wrapped in braces, a `$` to indicate that this is a localised value, and the locale included. > Note: The Wizard does not accept LCIDs. ### Accounting Excel's Accounting "Wizard" is like the Currency "Wizard", but without the options for presenting negative values. Presentation of zero and negative values is dependent on the currency and locale. ![Excel Number Format - Accounting.png](images/Behind the Mask/Excel Number Format - Accounting.png) The options available for the PhpSpreadsheet Accounting "Wizard" are identical to those of the Currency "Wizard"; although the generated Mask is different. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Accounting; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number; // Set Cell value $worksheet->getCell('C20')->setValue(-12345.67890); // Set Cell Style using the Accounting Wizard to build the Format Mask $currencyMask = new Accounting( '€', 2, Number::WITH_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING ); $worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->setFormatCode($currencyMask); var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // _-#,##0.00 €*_- var_dump($worksheet->getCell('C20')->getFormattedValue()); // -12,345.68 € ``` A typical Accounting mask might look something like '_-#,##0.00 €*_-', with the currency symbol as a literal; and with placement indicators like `_-`, that ensure the alignment of the currency symbols and decimal points of numbers in a column. As with using a locale with the Currency "Wizard", when you use a locale with the Accounting "Wizard" the locale value must be valid, and any additional options will be ignored. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Accounting; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number; // Set Cell value $worksheet->getCell('C21')->setValue(-12345.67890); // Set Cell Style using the Accounting Wizard to build the Format Mask for a locale $localeCurrencyMask = new Accounting( '€', locale: 'nl_NL' ); $worksheet->getCell('C21') ->getStyle()->getNumberFormat() ->setFormatCode($localeCurrencyMask); var_dump($worksheet->getCell('C21') ->getStyle()->getNumberFormat()->getFormatCode()); // [$€-nl-NL] #,##0.00;([$€-nl-NL] #,##0.00) var_dump($worksheet->getCell('C21')->getFormattedValue()); // (€ 12,345.68) ``` If we use the locale in the "Wizard", then a typical mask might look like '[$€-nl-NL] #,##0.00;([$€-nl-NL] #,##0.00)', with the currency wrapped in braces, with a `$` to indicate that this is a localised value, and the locale included. And in this case, there is masking for zero and for negative values, although without colour. An option to add colour to values is an option that may be added in a future release. > **Warning**: Not all versions of the ICU (International Components for Unicode) support Accounting formats, so even if your PHP does have 'Intl' enabled, it may still not allow the use of locale for generating an Accounting Mask. ### Date When you use the Excel Date "Wizard", you can select a locale and you'll then be presented with a number of date format options that are appropriate for that locale. ![Excel Number Format - Date.png](images/Behind the Mask/Excel Number Format - Date.png) I've written in detail about Date Format Masks elsewhere in "The Dating Game"; but to summarise, here are the Mask codes used for Date formatting. | Code | Description | Example (January 3, 2023) | |-------|-------------------------------------|---------------------------------------| | m | Month number without a leading zero | 1 | | mm | Month number with a leading zero | 01 | | mmm | Month name, short form | Jan | | mmmm | Month name, full form | January | | mmmmm | Month as the first letter | J (stands for January, June and July) | | d | Day number without a leading zero | 3 | | dd | Day number with a leading zero | 03 | | ddd | Day of the week, short form | Tue | | dddd | Day of the week, full form | Tuesday | | yy | Year (last 2 digits) | 23 | | yyyy | Year (4 digits) | 2023 | ### Time As with Dates, when you use the Excel Time "Wizard", you can select a locale and you'll then be presented with a number of time format options that are appropriate for that locale. ![Excel Number Format - Time.png](images/Behind the Mask/Excel Number Format - Time.png) I've written in detail about Time Format Masks elsewhere in "The Dating Game"; but to summarise, here are the Mask codes used for Time formatting. | Code | Description | Displays as | |--------|--------------------------------------------------------------------|-------------| | h | Hours without a leading zero | 0-23 | | hh | Hours with a leading zero | 00-23 | | m | Minutes without a leading zero | 0-59 | | mm | Minutes with a leading zero | 00-59 | | s | Seconds without a leading zero | 0-59 | | ss | Seconds with a leading zero | 00-59 | | AM/PM | Periods of the day
(if omitted, 24-hour time format is used) | AM or PM | Excel also supports Masks for Time Durations (note that spreadsheets using the 1904 base date can display negative durations, but those using the 1900 base date cannot). There is no "Wizard" for this; but the following Mask codes can be used to display Durations. | Code | Description | Displays as | |---------|----------------------------------------------------------------|-------------| | [h]:mm | Elapsed time in hours | e.g. 25:02 | | [hh]:mm | Elapsed time in hours
with a leading zero if less than 10 | e.g. 05:02 | | [mm]:ss | Elapsed time in minutes | e.g. 63:46 | | [m]:ss | Elapsed time in minutes
with a leading zero if less than 10 | e.g. 03:46 | | [s] | Elapsed time in seconds | | | [ss] | Elapsed time in seconds
with a leading zero if less than 10 | | ### Percentage This is among the simplest of the Excel "Wizards", only allowing you to specify the number of decimals to be displayed. ![Excel Number Format - Percentage.png](images/Behind the Mask/Excel Number Format - Percentage.png) The Percentage mask looks like '0.00%'. Using the `%` code in a mask will multiply the value by 100 before rendering it, and it will always also display the `%` sign. The PhpSpreadsheet "Wizard" replicates this simple option; but also provides a locale option that allows locale-specific formatting, because there are a few locales where the percentage sign appears before the value rather than after it. As with all locale use for the PhpSpreadsheet "Wizard", this is dependent on having the `Intl` extension enabled. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Percentage; // Set Cell value $worksheet->getCell('C21')->setValue(-12345.67890); // Set Cell Style using the Percentage Wizard to build the Format Mask for a locale $localeCurrencyMask = new Percentage( locale: 'tr_TR' ); $worksheet->getCell('C21') ->getStyle()->getNumberFormat() ->setFormatCode($localeCurrencyMask); var_dump($worksheet->getCell('C21') ->getStyle()->getNumberFormat()->getFormatCode()); // %#,##0.00 var_dump($worksheet->getCell('C21')->getFormattedValue()); // %-12,345.68 ``` ### Fraction MS Excel presents two different options for fractions: the first where the denominator is calculated internally to either 1, 2 or 3 digits; and the second (introduced only recently) where the denominator is fixed as 2, 4, 8 or 16. ![Excel Number Format - Fraction.png](images/Behind the Mask/Excel Number Format - Fraction.png) The Fraction mask looks like '# ?/???' where `#` indicates that the integer part of the value should be displayed, and then `?/???` to display the fraction with up to 3 digits in the denominator. The mask using a fixed-denominator looks like '# ?/16', with the denominator value replacing the variable `?`. If you use digit placeholders (`/??`) for the denominator, then Excel will calculate the lowest denominator that it can use for the fractional value. If you specify a fixed denominator (e.g. `/8`) then Excel will calculate the fraction in eighths. > **Note:** The internal renderer in PhpSpreadsheet does not consider the number of digits for the denominator, but will simply try to identify the lowest value denominator that it can use. There is currently no PhpSpreadsheet "Wizard" for Fraction Masks. ### Scientific This is among the simplest of the Excel "Wizards", only allowing you to specify the number of decimals to be displayed. ![Excel Number Format - Scientific.png](images/Behind the Mask/Excel Number Format - Scientific.png) The Scientific mask looks like '0.00E+00'. > **Note**: The internal rendering used by PhpSpreadsheet will display only as many digits as necessary for the exponent; while the Excel mask specifies a minimum of 2 digits, with a leading zero if necessary. The PhpSpreadsheet "Wizard" replicates this simple option. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Scientific; // Set Cell value $worksheet->getCell('C20')->setValue(-12345.67890); // Set Cell Style using the Scientific Wizard to build the Format Mask $scientificMask = new Scientific( 4, ); $worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->setFormatCode($scientificMask); var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat()->getFormatCode()); // 0.0000E+00 var_dump($worksheet->getCell('C20')->getFormattedValue()); // -1.2346E+4 // Set Cell value $worksheet->getCell('C21')->setValue(-12345.67890); // Set Cell Style using the Scientific Wizard to build the Format Mask for a locale $localeScientificMask = new Scientific( 3, locale: 'nl_NL' ); $worksheet->getCell('C21') ->getStyle()->getNumberFormat() ->setFormatCode($localeScientificMask); var_dump($worksheet->getCell('C21') ->getStyle()->getNumberFormat()->getFormatCode()); // 0.000E+00 var_dump($worksheet->getCell('C21')->getFormattedValue()); // -1.235E+4 ``` If you specify a number of decimals to display, then the Scientific "Wizard" will apply that value, even when using a locale. ### Text MS Excel's Text "Wizard" has no options, but simply sets a mask to `@`, meaning display the value exactly as it is entered. Unlike `General`, which is adaptive, `@` will not change the displayed value in any way, except in one exceptional case (see note below). Very large or very small values will not be displayed in Scientific format, and leading zeroes will be displayed. >**Note:** If your cell contains Rich Text, then using `@` in a format mask will display it using the basic cell styling, ignoring the Rich Text styling. ![Excel Number Format - Text.png](images/Behind the Mask/Excel Number Format - Text.png) PhpSpreadsheet doesn't emulate this behaviour; it simply displays the value as PHP would render that value cast to a string, which mimics Excel's quirk with Rich Text values. There is no PhpSpreadsheet "Wizard" for Text Masks. ### Special Excel's Special format "Wizard" is a recent introduction: select a locale, and then you may be offered a number of options for formatting values in a manner that is appropriate to that locale, such as US phone numbers, social security numbers, or zip codes; typically with separators between groups of digits. At this time, most locales have no special formats defined. ![Excel Number Format - Special.png](images/Behind the Mask/Excel Number Format - Special.png) There is no PhpSpreadsheet "Wizard" for Special Masks. ## Custom Format Masks The Custom "Wizard" really isn't a Wizard at all, just an editing field that allows you to pre-populate from a list of common format masks before editing. ![Excel Number Format - Custom.png](images/Behind the Mask/Excel Number Format - Custom.png) It does mean that you need to understand the rules for defining masks when you use this. When you create custom number formats, you can specify up to four sections of format code. These sections of code must be separated by semicolons (`;`). ### Sections for Composite Masks Sections of the mask define the formats for positive numbers, negative numbers, zero values, and text, in that order. ![Mask Sections.png](images/Behind the Mask/Mask Sections.png) 1. Format for Positive values 2. Format for Negative values 3. Format for Zero values 4. Format for Text If you specify only one section of format code, the code in that section is used for all numbers. If you specify two sections of format code, the first section of code is used for positive numbers and zeros, and the second section of code is used for negative numbers. If you specify a third section, then the first applies to positive values, the second to negative values, and the third to zero values. The fourth section only applies if the value is not numeric. If you skip code sections in the format mask, then you must include a semicolon for each of the missing sections. When you skip code sections in the format mask, then you must include a semicolon for each of the missing sections. Use `;` to indicate that a section exists, but with an empty mask; and that can be used to hide values that match the criteria for that section. ![Hiding Values.png](images/Behind the Mask/Hiding Values.png) > **Note:** Negative values aren't shown with a sign when we use the negative value section. If we want the value to display with a sign, then we need to include an explicit '-' character in the Mask for that section (";-0;"). ### Basic Masking Symbols Three basic masking symbols are used to display numbers, and they differ in the way that they display leading or trailing zeroes. The fourth basic masking symbol is the text placeholder, which can be used to wrap the cell value within additional formatting. | Code | Description | Examples | |------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| | 0 | Digit placeholder that displays insignificant zeros. | #.00 - always displays 2 decimal places.

If you type 5.5 in a cell, it will display as 5.50. | | # | Digit placeholder that represents optional digits and does not display extra zeros.

That is, if a number doesn't need a certain digit, it won't be displayed. | #.## - displays up to 2 decimal places.

If you type 5.5 in a cell, it will display as 5.5.

If you type 5.555, it will display as 5.56. | | ? | Digit placeholder that leaves a space for insignificant zeros on either side of the decimal point but doesn't display them. It is often used to align numbers in a column by decimal point. | #.??? - displays a maximum of 3 decimal places and aligns numbers in a column by decimal point. | | @ | Text placeholder | 0.00; -0.00; 0; [Red]@ - applies the red font colour for text values. | If a number entered in a cell has more digits to the right of the decimal point than there are placeholders in the format, the number is "rounded" to as many decimal places as there are placeholders. For example, if you have a value of `2.25` in a cell with '#.#' format, then the number will be rounded to 1 decimal, and will display as `2.3`. Digits to the left of the decimal point are always displayed regardless of the number of placeholders. For example, if the value in a cell is `202.25` with '#.#' format, the number will display as `202.3`. ![Digit Placeholders.png](images/Behind the Mask/Digit Placeholders.png) To display leading zeroes for a numeric value, you might create a mask like '0000', which will always display at least 4 digits, padding the value with leading zeroes if it is less than 1000. ### Other Special Codes In addition to the masking symbols listed above, the following codes also enable special rendering of the value. | Code | Description | Example | |----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------| | . (period) | Decimal point. | ##0.00?? | | , (comma) | Thousands Separator.
A comma that follows a digit placeholder scales the number by a thousand. | #,##0
0.000,
Described below. | | \ | Text Escape Character that displays the character that follows it. | ##0\°
Described below. | | " " | Display any text that is enclosed in the double quotes. | ##0"°C"
Described below. | | % | Multiplies the value stored in the cell by 100 and display it with the percentage sign. | Examples provided in the "Wizard" section above. | | / | Display the value as a fraction. | Examples provided in the "Wizard" section above. | | E | Display the value in Scientific Format. | Examples provided in the "Wizard" section above. | | _ (underscore) | Space pad to the width of the next character in the mask.
It is commonly used in combination with parentheses to add left and right indents, `_(` and `_)` respectively. | Described below. | | * (asterisk) | Repeats the character that follows it until the width of the cell is filled.
It is often used in combination with the space character to change alignment. | Described below. | Simple examples of using these codes for Percentages, Fractions and Scientific Format can be found in the descriptions of those "Wizards". The other codes are described in detail below. ### Thousands Separator and Scaling To create an Excel custom number format with a thousands separator, include a comma (`,`) in the format code. For example: - #,### - display a thousands separator and no decimal places. - #,##0.00 - display a thousands separator and 2 decimal places. Microsoft Excel separates thousands by commas: if a comma is enclosed by any digit placeholders - the pound sign (`#`), question mark (`?`) or zero (`0`). But if no digit placeholder follows a comma, it scales the number by a thousand, two consecutive commas scale the number by a million, and so on. For example, if a cell format is '#.00,' and the cell value is `5000`, then the number `5.00` is displayed. ![Scaling Example.png](images/Behind the Mask/Scaling Example.png) ### Formatting with Text If you want to include text in your format mask with numeric values, then there are two basic options. To add a single character, then you can prefix that character with a backslash ('\'), e.g. '#.00,\K' or '#.00,,\M'. ![Text Single Character Example.png](images/Behind the Mask/Text Single Character Example.png) You don't need the backslash ('\') prefix for the following list of characters: | Character | Description | |-----------|----------------------------------| | + and - | Plus and Minus Signs | | ( and ) | Left and Right Parenthesis | | : | Colon | | ^ | Caret | | ' | Apostrophe | | { and } | Curly Braces | | < and > | Less Than and Greater than Signs | | = | Equals Sign | | / | Forward Slash | | ! | Exclamation Mark | | & | Ampersand | | ~ | Tilde | | | Space Character | You can also use additional padding characters if you want to break a number into groups. For example, to display a number as a phone number, you might use a mask like '00-0000-0000' or '(++00) 00-0000-0000'. It's a common practise in Accounting formats to wrap negative values in brackets; so you might use '([$€-nl-NL] #,##0.00)' for that section of the mask. To add words or for phrases to the mask, you should wrap the text in quotes: e.g. '#.00" Surplus";-#.00" Deficit";"Out of Stock"'. ![Text String Example.png](images/Behind the Mask/Text String Example.png) ### Indents, Spacing and Alignment If you're wrapping negative values in brackets, you might like like to align your positive values with your negative values on the decimal, then you need to apply indents to the positive values to match the width of the bracket characters. The underscore code (`_`) tells Excel to pad the display to the width of the next character in the mask, so '_)' would tell Excel to pad to the width of ')' character like '[$€-nl-NL] _(#,##0.00_);[$€-nl-NL] (#,##0.00)'. ![Indent.png](images/Behind the Mask/Indent.png) Accountants might also appreciate if the Currency symbols were also all aligned; so we can use the `*` code followed by a repeated character; and that will pad the width of the cell with the specified character. Typically, although not always, this will be a space character, '* '. ![Padding.png](images/Behind the Mask/Padding.png) Which aligns all our currency symbols to the left of the cell, while displaying the value right-aligned in the cell, and all the decimal points neatly aligned. The `*` code can also be used to change the alignment of a value in a cell. If we want text to be rendered right aligned, even though the cell is left aligned, we can use '* @' as the mask, and this will push the display to the right of the cell. ![Right Align.png](images/Behind the Mask/Right Align.png) Note that padding is not supported by PhpSpreadsheet's internal renderer for the cell's `getFormattedValue()` method, because the renderer is unaware of font or cell width, so it will simply add a single space in the formatted result. Nor will it change alignment in any way. ### Colours You can use format masks to change the font colour for a certain value with a custom number format. e.g. '[Red]@' Masking supports the following 8 main colours. - Black - Red - Green - Blue - Cyan - Yellow - Magenta - White To specify the colour, just type one of those colour names in the appropriate section of your number format code, wrapped in square braces (e.g. '[red]'). This colour code must be at the very start of the section, before any other formatting characters or instructions. The colour name is case-insensitive. If we wanted to show positive values in green and negative values in red we could apply different colours to the different sections of the mask, e.g. "[Green]#,##0.00;[Red]#,##0.00;0.00". > **Warning**: Colour masking doesn't apply when using Excel's `TEXT()` function; only when it is applied to a Cell's Format Mask. ### Conditional Formatting Not to be confused with actual Conditional Formatting in MS Excel; but we can apply some limited condition checks in normal Cell Format Masks, and apply different masking based on those conditions. While by default the different sections are interpreted by Excel as positive, negative, zero and text, we can override these definitions with conditions. We do this by defining the condition for matching against the value inside square braces. ![Conditional 1.png](images/Behind the Mask/Conditional 1.png) The mask that we're using here is `[Red][<65]"Fail";[Blue]"Pass"`. This tells Excel to display the text "Fail" if the value in the Cell is less than 65, otherwise to display "Pass". The symbols allowed for comparison in Conditions are the standard mathematical comparison operators: | Symbol | Meaning | |--------|-----------------------| | \> | Greater than | | \>= | Greater than or Equal | | < | Less than | | <= | Less than or Equal | | = | Equal | | <\> | Not Equal | In this next example, we've created an additional condition, so we have three sections in the mask: the "Pass" grade is now any student that hasn't failed, but whose score is less than 85; the last section awards a grade of "Distinction" to any student whose score doesn't match the criteria for "Pass" or "Fail" (i.e. exceeds 85). `[Red][<65]"Fail";[Blue][<85]"Pass";"Distinction"` ![Conditional 2.png](images/Behind the Mask/Conditional 2.png) We do need to be careful about the order that we define the conditions, because Excel will apply the mask for the first condition that matches the Cell value. > **Note**: Conditional Formatting using the Number Mask will also work with the TEXT() Function, although not with colour highlighting. We can also use Conditional Formatting to display Lakh, the different grouping often found in India and the countries of that region. While the thousands separator normally represents grouping to powers of 3 (103, 106, 109, etc), the Lakh is 103, 105, 107, etc. and is written as `1,00,000`. After the first 1000, the comma separator is used to represent groups of 2 digits, not groups of 3 digits. 150,000 rupees is 1.5 lakh rupees, and is written as `₹1,50,000` or `INR 1,50,000`. The mask used to represent lakh is: [>=10000000][$₹]##\,##\,##\,##0;[>=100000][$₹]##\,##\,##0;[$₹]##,##0 Note that we're only using the `,` for thousands grouping in the final block, to represent values less than 100,000 where we would only display a single `,` as a thousands separator. For the `,` in higher values, we are displaying a string literal `,` identified as such by the '\' immediately before it in the mask. ## Building Composite Masks using PhpSpreadsheet's Wizards Even though PhpSpreadsheet's Wizards don't yet support building sections with different masks for positive, negative, zero, and text, you can still create these using the Wizards as building blocks. ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number; // Set Cell value $worksheet->getCell('C20')->setValue(-12345.67890); // Set Cell Style using the Currency Wizard to build the Format Mask $currencyMask = new Currency( '€', 2, Number::WITH_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING ); // Build the composite mask applying colours to the different sections $compositeCurrencyMask = [ '[Green]' . $currencyMask, '[Red]' . $currencyMask, $currencyMask, ]; $worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->setFormatCode(implode(';', $compositeCurrencyMask)); var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->getFormatCode()); // [Green]#,##0.00 €;[Red]#,##0.00 €;#,##0.00 € ``` We repeat the mask that's generated by the "Wizard" for each section of the composite mask, adding the required colour to each section. If we've used a locale to build a mask, then we may already have multiple sections: ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency; // Set Cell value $worksheet->getCell('C20')->setValue(-12345.67890); // Set Cell Style using the Currency Wizard to build the Format Mask $currencyMask = new Currency( '€', locale: 'nl_NL' ); // Split the generated mask into sections // This particular mask already has positive and negative value sections, // but does not have a zero value section // Other locales may only have a positive section; or may already have a zero section $currencyMaskSections = explode(';', $currencyMask); // Recreate the modified mask applying colours to the different sections $compositeCurrencyMask = [ '[Green]' . $currencyMaskSections[0], '[Red]' . $currencyMaskSections[1] ?? $currencyMaskSections[0], $currencyMaskSections[2] ?? $currencyMaskSections[0], ]; $worksheet->getCell('C20') ->getStyle()->getNumberFormat() ->setFormatCode(implode(';', $compositeCurrencyMask)); var_dump($worksheet->getCell('C20') ->getStyle()->getNumberFormat() // [Green][$€-nl-NL] #,##0.00;[Red][$€-nl-NL] -#,##0.00;[$€-nl-NL] #,##0.00 ->getFormatCode()); ``` If the locale-generated mask already has a section defined, then we use that, otherwise we use the positive section (section 0) that will always exist as the base for each section. > **Warning:** You might need to add an explicit `-` for the negative section if that needs to be created. ## Summary Even though Excel displays the formatted value in the grid, the underlying value in the cell is unchanged. The value being displayed as a date is still an Excel Serialized Timestamp, even though it is being displayed as '2023-02-28'; the student grade is still a number, even though it is being displayed as "Distinction"/"Pass"/"Fail"; and the cell that looks empty may not be as empty as you think. The edit bar still shows us the value in the cell, not the formatted value; and we can still use that underlying value in formulae. ![Summary - Still a numeric value.png](images/Behind the Mask/Summary - Still a numeric value.png) And we can even format the cell containing the result of that formula. Number format masks allow us to present the spreadsheet data in a format that makes it easy for the user to interpret; so they add a lot of value to the spreadsheets that we create. We just need to understand how to use them well to unlock that value. ================================================ FILE: docs/topics/Excel Anomalies.md ================================================ # Excel Anomalies This is documentation for some behavior in Excel itself which we just do not understand, or which may come as a surprise to the user. ## Date Number Format My system short date format is set to `yyyy-mm-dd`. Excel, for a very long time, did not include that amongst its formatting choices for dates, so it needed to be added as a custom format - no big deal. It has recently been added to the list of date formats, but ... I used Excel to create a spreadsheet, and included some dates, specifying `yyyy-mm-dd` formatting. When I looked at the resulting spreadsheet, I was surprised to see that Excel had stored the style not as `yyyy-mm-dd`, but rather as builtin style 14 (system short date format). Apparently the fact that the Excel styling matched my system choice was sufficient for it to override my choice! This is an astonishingly user-hostile implementation. Even though there are formats which, by design, "respond to changes in regional date and time settings", and even though the format I selected was not among those, Excel decided it was appropriate to vary the display even when I said I wanted an unvarying format. I assume, but have not confirmed, that this applies to formats other than `yyyy-mm-dd`. Note that this is not a problem when using PhpSpreadsheet to set the style, only when you let Excel do it. And, in that case, after a little experimentation, I figured out a format that Excel doesn't sabotage `[Black]yyyy-mm-dd`. If you have a spreadsheet that has been altered in this way, it can be fixed with the following PhpSpreadsheet code: ```php foreach ($spreadsheet->getCellXfCollection() as $style) { $numberFormat = $style->getNumberFormat(); // okay to use NumberFormat::SHORT_DATE_INDEX below if ($numberFormat->getBuiltInFormatCode() === 14) { $numberFormat->setFormatCode('yyyy-mm-dd'); } } ``` Starting with PhpSpreadsheet 4.5.0, this can be simplified to: ```php $spreadsheet->replaceBuiltinNumberFormat( \PhpOffice\PhpSpreadsheet\Style\NumberFormat::SHORT_DATE_INDEX, 'yyyy-mm-dd' ); ``` ## Negative Time Intervals You have a time in one cell, and a time in another, and you want to subtract and display the result in `h:mm` format. No problem if the result is positive. But, if it's negative, Excel just fills the cell with `#`. There is a solution of sorts. If you use a 1904 base date (default on Mac), the negative interval will work just fine. Alas, no dice if you use a 1900 base data (default on Windows). No idea why they can't fix that - the existing implementation can't really be something that anybody actually wants. Note that it is *not* safe to change the base date for an existing spreadsheet, so, if this is something you want to do, make sure you change the base date before populating any data. ## Long-ago Dates Excel does not support dates before either 1900-01-01 (Windows default) or 1904-01-01 (Mac default). For the 1900 base year, there is the additional problem that non-existent date 1900-02-29 is squeezed between 1900-02-28 and 1900-03-01. ## Weird Fractions Similar fraction formats have inconsistent results in Excel. For example, if a cell contains the value 1 and the cell's format is `0 0/0`, it will display as `1 0/1`. But, if the cell's format is `? ??/???`, it will display as `1`. See [this issue](https://github.com/PHPOffice/PhpSpreadsheet/issues/3625), which remains open because, in the absence of usable documentation, we aren't sure how to handle things. ## COUNTIF and Text Cells In Excel, COUNTIF appears to ignore text cells, behavior which doesn't seem to be documented anywhere. See [this issue](https://github.com/PHPOffice/PhpSpreadsheet/issues/3802), which remains open because, in the absence of usable documentation, we aren't sure how to handle things. ## SORT on Different DataTypes Excel appears to sort so that numbers are lowest in sort order, strings are next, booleans are next (LibreOffice treats booleans as ints), and null is highest. In addition, if your sort includes a numeric string with a leading plus or minus sign, the plus sign will be considered part of the string (so that `"+1"` will sort before `"0"`), but the minus sign will be ignored (so that `"-3"` will sort between `"25"` and `"40"`). There might be nuances I haven't thought of yet. PhpSpreadsheet will not necessarily duplicate Excel's behavior. The best advice we can offer is to make sure that arrays you wish to sort consist of a single datatype, and don't contain numeric strings. Samples samples/LookupRef/SortExcel and SortExcelCols are added to give an idea of how you might emulate Excel's behavior. I am not yet convinced that there is a use case for adding it as a class member in the src tree. ================================================ FILE: docs/topics/Looping the Loop.md ================================================ # Looping the Loop PhpSpreadsheet uses a lot of memory to maintain the Spreadsheet model; but I regularly see developers loading a Spreadsheet file and then calling the `toArray()` methods so that they can loop through the rows and columns of a worksheet. PHP arrays are also notoriously memory-intensive, so creating a large array duplicating the data that is already in the Spreadsheet model is a very inefficient use of memory. Generally, unless we are always working with very small spreadsheets, we would want to avoid this. So in this article, I'm going to look at a number of different ways of iterating through a worksheet to access the row and cell data; at their limitations; and at some of the options that each provides. ## Using `toArray()` Using a sample data file from Microsoft and available at https://go.microsoft.com/fwlink/?LinkID=521962, I can load up the file, call `toArray()` to return the worksheet data in an array, and iterate over the rows and cells of that array with the following code. ```php $inputFileType = 'Xlsx'; $inputFileName = __DIR__ . '/../Financial Sample.xlsx'; $reader = IOFactory::createReader($inputFileType); $spreadsheet = $reader->load($inputFileName); $worksheet = $spreadsheet->getActiveSheet(); $dataArray = $worksheet->toArray(); foreach ($dataArray as $row) { foreach ($row as $cellValue) { // Do something with the cell data here. } } ``` The Financial Sample spreadsheet is fairly small, 701 rows (including a heading row) and 16 columns; and is predominantly numeric data. To simulate a larger worksheet, I've duplicated that data to give 7001 rows; but this is still a small worksheet as MS Excel xlsx files can contain 1 million rows in each of several worksheets. If we look at the timings and memory usage for this process with my extended MS Financial Sample spreadsheet: ``` Current memory usage: 47104 KB Call time to build array was 0.6603 seconds Call time to iterate array rows was 0.0130 seconds Current memory usage: 57344 KB Peak memory usage: 57344 KB ``` We can see that using `toArray()` increases memory usage by 10240KB (10MB): that is the memory used by the array for a relatively small worksheet (less than 120,000 cells). For larger worksheets, with more rows and columns, and with more text than numeric values, this memory overhead can grow significantly larger. And while iteration over the array is very quick, it still takes 0.6603 seconds to build the array before we can start iterating over those rows and cells. --- The `toArray()` method is easy to use: but not only is it increasing the memory overhead, especially with larger worksheets; but it also lacks flexibility. It provides limited control over how the data from each cell is returned in the array. It can return the raw cell value (which isn't particularly useful if the cell contains a formula, or if the value should be interpreted as a date); it can force PhpSpreadsheet to calculate formulae and return the calculated value; or it can return the formatted cell value (which includes calculating any formulae) so that date values are presented in a human-readable format, but which will also format numeric values with thousand separators where the cell style applies that. | Argument Name | DataType | Default | Purpose | |--------------------|----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | $nullValue | mixed | null | A value to be returned in the array if a cell doesn't exist. | | $calculateFormulas | boolean | false | Flag to indicate if formula values should be calculated before returning. | | $formatData | boolean | false | Flag to request that values should be formatting before returning. | | $returnCellRef | boolean | false | False - Return a simple enumerated array of rows and columns (indexed by number counting from zero)
True - Return rows and columns indexed by their actual row and column IDs. | | $ignoreHidden | boolean | false | True - Ignore hidden rows and columns. | | $reduceArrays | boolean | false | True - If calculated value is an array, reduce it to top leftmost value. | | $lessFloatPrecision | boolean | false | True - PhpSpreadsheet 5.2+ - Floats, if formatted, will display as a more human-friendly but possibly less accurate value. | ### Dealing with empty rows The example spreadsheet that I've used here is well behaved, with no empty rows. Empty rows can cause problems, even when working in Excel itself. Let's take a look at a worksheet of Sales Data, where we're missing the returns for a couple of months: ![Empty Rows.png](images/Looping the Loop/Empty Rows.png) If we're using MS Excel, and we hit `Ctrl-T` to create a table from this data, we might expect Excel to build that table from all rows up to `Dec`; but it won't, it will only build the table up to the next empty row. ![Table with Empty Rows.png](images/Looping the Loop/Table with Empty Rows.png) And unless we're careful, we might not even notice that the last few months of the year are omitted. So empty rows can create problems even in MS Excel itself; and we certainly need to have some way of identifying them when we're processing a worksheet using PhpSpreadsheet. --- While we're iterating through a spreadsheet with PhpSpreadsheet, we might want to avoid trying to process blank data if we reach a row that is empty; or we might want to terminate iterating when we encounter an empty row. If we've created an array from a worksheet, then an empty row will be a row where every cell/column entry has a null value (unless called specifying an alternative value using the `$nullValue` argument). We can filter the row to eliminate null values, then count the length of that filtered array: if there are no remaining cells, then the row is empty. We can then skip that row in our code using `continue`. ```php foreach ($dataArray as $row) { // Check for empty rows if (count(array_filter($row, function ($value) { return $value !== null; })) === 0) { continue; // Ignore empty rows } foreach ($row as $cellValue) { // Do something with the cell data here. } } ``` Or if we want to terminate iterating when we encounter an empty row, use `break` rather than `continue`. ```php foreach ($dataArray as $row) { // Check for empty rows if (count(array_filter($row, function ($value) { return $value !== null; })) === 0) { break; // Stop at the first empty row } foreach ($row as $cellValue) { // Do something with the cell data here. } } ``` Using `toArray()` won't change anything in the worksheet model: it won't modify values or create new cells. It will return a row/column entry for every cell that can exist, even if that cell doesn't exist in the worksheet, or is part of a merge range. > **Note**: It is possible for several cells in a merge range to have a value. Although MS Excel doesn't allow you to set data like this, the option is available in other Spreadsheet software, and if the file is saved as an xlsx file, then the data for those cells is retained in the file, even though only the top left cell of a merge range shows a value in MS Excel. In PhpSpreadsheet, accessing those cells (including using `toArray()`) will return the "hidden" value. One useful factor about returning an array of arrays is if we want to populate a data model from that row before persisting to a database, for example. We don't need to iterate the columns in that row, but can work directly with the column array for each row. ```php class MonthlySales { private function __construct( public readonly string $month, public readonly array $sales, ) {} public static function fromExcel(array $values, array $headers): self { $month = array_shift($values); return new self($month, array_combine($headers, $values)); } } $monthlySalesData = new MonthlySalesCollection(); // Read from the header row of the worksheet $excelHeaderRow = ['Jones', 'Sorvino', 'Gupta', 'Choi']; $dataArray = $worksheet->toArray(formatData: true); foreach ($dataArray as $excelDataRow) { // Check for empty rows if (count(array_filter($excelDataRow, function ($value) { return $value !== null; })) === 0) { continue; // Ignore empty rows } $monthlySalesData->add(MonthlySales::fromExcel( $excelDataRow, $excelHeaderRow )); } ``` We can pass the row array directly to the static `MonthlySales::fromExcel()` constructor for our data object, handling any validation and manipulation of the structure there, to map the Excel data row to that object properties, handling filtering within the business logic of the Monthly Sales object's static constructor. --- And remember that by default, `toArray()` returns a simple enumerated array of enumerated arrays, to reflect rows and columns. You can modify this using the `$returnCellRef` argument to the method: set `$returnCellRef` to true, and the array indexes will be the row number (with 1 as the first row) and the column address ('A', 'B', 'C', etc); which can be useful if you want to do some processing of the cells based on that column address. ```php class MonthlySales { private function __construct( public readonly string $month, public readonly array $sales, ) {} public static function fromExcel(array $values, array $headers): self { $month = array_shift($values); $salesValues = []; foreach ($values as $column => $value) { // Ignore salespeople who have null sales values if ($value !== null) { $salesValues[$headers[$column]] = $value; } } return new self($month, $salesValues); } } $monthlySalesData = new MonthlySalesCollection(); // Read from the header row of the worksheet $excelHeaderRow = [ 'B' => 'Jones', 'C' => 'Sorvino', 'D' => 'Gupta', 'E' => 'Choi' ]; $dataArray = $worksheet->toArray(formatData: true, returnCellRef: true); foreach ($dataArray as $excelDataRow) { // Check for empty rows if (count(array_filter($excelDataRow, function ($value) { return $value !== null; })) === 0) { continue; // Ignore empty rows } $monthlySalesData->add(MonthlySales::fromExcel( $excelDataRow, $excelHeaderRow )); } ``` ## Using `rangeToArray()` The `toArray()` method uses information from the loaded file to identify the range of rows and columns to populate the array. `toArray()` uses two cached values to identify the range of cells to populate the array, values that are returned by the `getHighestRow()` and `getHighestColumn()` methods. But many worksheets do have trailing empty rows (or columns); and it is quite common for an Excel spreadsheet to have only a few rows or columns of data, but for the spreadsheet itself to claim that the highest row is 1,048,576 or that the highest column is XFD. Features such as Data Validation or Conditional Formatting that can also artificially inflate/increase the values returned by `getHighestRow()` and `getHighestColumn()` methods. If we use `toArray()` to build an array from the worksheet in this case, then it will build a 1,048,576x16,384 array, filled with null values, that will almost certainly exceed PHP's memory limits, and take a long time to do so. And if we do have enough memory to build the array, we will still be iterating over a lot more array entries than we want. Even if we're skipping empty rows, we're still testing every row to see if it's empty. Where possible, it's better to specify the limit of rows and columns that we want to use to build an array, and PhpSpreadsheet provides the `rangeToArray()` for that purpose. One option to reduce a large array using a lot of PHP memory would be to run a loop using `rangeToArray()` to build smaller arrays for blocks of perhaps 100 rows at a time. This will still take a while to run if we have a lot of trailing empty rows, but it won't exceed PHP's memory limits. ```php $startRow = 1; $batchSize = 100; while ($startRow <= $maxRow) { $endRow = min($startRow + $batchSize, $maxRow); $dataArray = $worksheet->rangeToArray("A{$startRow}:{$maxColumn}{$endRow}"); $startRow += $batchSize; foreach ($dataArray as $row) { // Check for empty rows if (count(array_filter($row, function ($value) { return $value !== null; })) === 0) { continue; // Ignore empty rows } foreach ($row as $cellValue) { // Do something with the cell data here. } } } ``` Alternatively, we can identify the highest row and highest column that actually contain cell data using the `getHighestDataRow()` and `getHighestDataColumn()` methods. This allows us to specify a range to pass to the `rangeToArray()` method. ```php $maxDataRow = $worksheet->getHighestDataRow(); $maxDataColumn = $worksheet->getHighestDataColumn(); $dataArray = $worksheet->rangeToArray("A1:{$maxDataColumn}{$maxDataRow}"); foreach ($dataArray as $row) { // Check for empty rows if (count(array_filter($row, function ($value) { return $value !== null; })) === 0) { continue; // Ignore empty rows } foreach ($row as $cellValue) { // Do something with the cell data here. } } ``` There might still be some empty rows in this array, so we still want to test for empty rows; but we won't have any trailing empty rows at the end of our data, so the iteration will terminate at the end of our specified row range, when we know we have no further data. And if there is a row or two of column headers that we want to ignore, we can modify the specified range to exclude them by adjusting the starting row of the range (e.g. `"A3:{$maxDataColumn}{$maxDataRow}"`); Because we're only building the array for a specified range of rows and columns, the array that the method builds will often be smaller than the array created by `toArray()`, using less memory; and it will often be faster iterating just the subset of rows that we've requested. A combination of these approaches - batching and using the 'getHighestDataRow()' value, will be more memory-efficient, and possibly faster, than using 'toArray()'. ```php $startRow = 1; $batchSize = 100; while ($startRow <= $maxDataRow) { $endRow = min($startRow + $batchSize, $maxDataRow); $dataArray = $worksheet->rangeToArray("A{$startRow}:{$maxDataColumn}{$endRow}"); $startRow += $batchSize; foreach ($dataArray as $row) { // Check for empty rows if (count(array_filter($row, function ($value) { return $value !== null; })) === 0) { continue; // Ignore empty rows } foreach ($row as $cellValue) { // Do something with the cell data here. } } } ``` How does this approach compare with using 'toArray()' in terms of memory and speed? Here are the details for using `rangeToArray()` with a batched approach: ``` Current memory usage: 47104 KB Call time to batch iterate array rows was 0.6844 seconds Current memory usage: 47104 KB Peak memory usage: 49152 KB ``` While the total time is 0.6844 seconds, that included building the smaller batched arrays, so its speed is comparable to the total time of 0.6733 seconds using `toArray()`. But a peak memory usage of 49,152KB compared with the 57,344KB used by `toArray()` make this approach a lot more memory efficient. Like `toArray()`, `rangeToArray()` is easy to use, but it has the same limitations for flexibility. It provides the same limited control over how the data from each cell is returned in the array as `toArray()`. The same additional arguments that can be provided for the `toArray()` method can also be provided to `rangeToArray()`. ## Using `rangeToArrayYieldRows()` Since v2.1.0 the worksheet method `rangeToArrayYieldRows()` is available. It allows you to iterate over all sheet's rows with little memory consumption, while obtaining each row as an array: ```php $rowGenerator = $sheet->rangeToArrayYieldRows( 'A1:' . $sheet->getHighestDataColumn() . $sheet->getHighestDataRow(), null, false, false ); foreach ($rowGenerator as $row) { echo $row[0] . ' | ' . $row[1] . "\n"; } ``` See `samples/Reader2/23_iterateRowsYield.php`. ## Using Iterators You don't need to build an array from the worksheet to loop through the rows and columns and do whatever processing you need; you can loop through the rows and columns in the Worksheet directly and more efficiently using PhpSpreadsheet's built-in iterators. And this also gives a lot more flexibility in how you can present the cell values, because the iterator will return the Cell itself, not a representation of its value. You can read its value, check its style, identify if it is part of a merge range. ```php $rowIterator = $worksheet->getRowIterator(); foreach ($rowIterator as $row) { $columnIterator = $row->getCellIterator(); foreach ($columnIterator as $cell) { // Do something with the cell here. } } ``` Let's look at the memory usage and timings for using PhpSpreadsheet's Iterators, as we did for building and iterating through the array. ``` Current memory usage: 47104 KB Call time to iterate rows was 0.0930 seconds Current memory usage: 47104 KB Peak memory usage: 47104 KB ``` Using the PhpSpreadsheet Iterators isn't as fast as iterating over an array; but it doesn't have the time or memory overheads of actually building that array from the worksheet. Using the same example spreadsheet, it only took 0.0130 seconds to iterate every cell of that array, but 0.6603 seconds to build the array, a total of 0.6733 seconds; but using the Iterator has performed the equivalent task in just 0.0930 seconds; about 7 times faster and without the increased memory overhead of the array. ### Dealing with empty rows As, when we were iterating over the array, we might want to identify empty rows so that we can avoid trying to process them. The Row Iterator provides a method to identify empty rows. ```php $rowIterator = $worksheet->getRowIterator(); foreach ($rowIterator as $row) { if ($row->isEmpty()) { // Ignore empty rows continue; } $columnIterator = $row->getCellIterator(); foreach ($columnIterator as $cell) { // Do something with the cell here. } } ``` One additional feature when using the Iterator to determine whether a row is empty or not is that we can set our own rules to define "empty". The default rule is if there is no entry for the Cell in the Cell Collection. If we also want to skip any Cell that contains a null value, then we can pass an argument using the pre-defined constant `CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL`. If we also want to skip any Cell that contains an empty string, then we can pass an argument using the pre-defined constant `CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL`. And we can combine those rules: ```php if ($row->isEmpty( CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL | CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL) ) { // Ignore empty rows continue; } ``` Since PhpSpreadsheet 1.27.0, we can take this empty test one step further. If we look at a slightly modified version of the Sales Data worksheet, rows 7 and 10 have no sales data, but they aren't empty because there is a month value in column A. ![Empty Rows 2.png](images/Looping the Loop/Empty Rows 2.png) But we can tell the `isEmpty()` method to only check if a specified range of columns is empty in a row. ```php if ($row->isEmpty(startColumn: 'B', endColumn: 'E') { // Ignore empty rows where columns B to E are empty values // even though there is a value in Column A. continue; } ``` --- Like `toArray()`, the Iterators use the `getHighestRow()` and `getHighestColumn()` methods to identify the maximum row and column values for iterating; so it can still iterate over a lot of trailing empty rows and columns. But that is just a default behaviour. Similarly to `rangeToArray()` we can specify a range of rows, and a range of columns to iterate. ```php $maxDataRow = $worksheet->getHighestDataRow(); $maxDataColumn = $worksheet->getHighestDataColumn(); $rowIterator = $worksheet->getRowIterator(1, $maxDataRow); foreach ($rowIterator as $row) { if ($row->isEmpty()) { // Ignore empty rows continue; } $columnIterator = $row->getCellIterator('A', $maxDataColumn); foreach ($columnIterator as $cell) { // Do something with the cell here. } } ``` and if we have heading rows at the top of the worksheet that we want to ignore: ```php $rowIterator = $worksheet->getRowIterator(3, $maxDataRow); ``` And if we want to return only cells that aren't empty in the row, then we can tell the Cell Iterator to skip empty cells. ```php $rowIterator = $worksheet->getRowIterator(1, $maxDataRow); foreach ($rowIterator as $row) { $columnIterator = $row->getCellIterator(); $columnIterator->setIterateOnlyExistingCells(true); foreach ($columnIterator as $cell) { // Do something with the cell here. } } ``` Alongside the speed and memory benefits, another big advantage of using the Iterators (Row and Cell, or Column and Cell) is that we get direct access to the cell itself. We can look at its value, its style; we can identify if it is a formula, or formatted as a date/time, whether it is part of a merge range: we can choose exactly what we want to do with it. --- One drawback of the Cell Iterator is that it will create a new cell if none exists (by default) unless we're skipping empty cells. Until PhpSpreadsheet 1.27.0, the Cell Iterator would always create a new Cell if one didn't exist in the Cell Collection when it was required to access it. And this can lead to increasing memory consumption. PhpSpreadsheet 1.27.0 introduced the option to return a null value rather than to create and return a new Cell. ```php $rowIterator = $worksheet->getRowIterator(1, $maxDataRow); foreach ($rowIterator as $row) { $columnIterator = $row->getCellIterator(); $columnIterator->setIfNotExists(CellIterator::IF_NOT_EXISTS_RETURN_NULL); foreach ($columnIterator as $cell) { if ($cell !== null) { // Do something with the cell here. } } } ``` The default Iterator behaviour is still to create a new Cell, to retain backward compatibility; but the option to return a null value instead of a new empty cell now exists. > **Note**: This default behaviour is likely to be reversed with the eventual release of PhpSpreadsheet 2.0, with a null value as the default return, but with the option to create a new empty cell. ## Summary of Performance and Benefits So here is a quick summary of timing and memory usage for the three different approaches to iterating through the rows and cells of the 7000 row sample worksheet. Memory usage is adjusted for the 47,104 KB baseline of the loaded file. | Approach | Total Time (s) | Memory (KB) | |------------------------|----------------|-------------| | toArray() | 0.6733 | 10,240 | | rangeToArray (Batched) | 0.6844 | 2,048 | | Iterators | 0.0930 | 0 | These figures are all based on a well-formed spreadsheet, with no trailing empty rows, or empty rows within the dataset. Empty rows within a dataset can be identified by all three approaches, although only Iterators have a built-in method to identify an empty row. Using `toArray()` is not good for controlling memory usage, especially if there are trailing empty rows, so it should generally be avoided; but both `rangeToArray()` and the Iterators can exclude trailing rows by setting their scope based on the `getHighestDataRow()` and `getHighestDataColumn()` values. Batching rows with `rangeToArray()` is useful for keeping memory usage under control if you want to work with arrays. But using the Iterators is significantly faster than either "array" approach, with no memory overhead (especially if using the option of a null return for Cells that don't exist that was made available in PhpSpreadsheet 1.27.0); and as the Iterators return the Cell object rather than simply a cell value, they provide a lot more flexibility in how to process that cell. The flexibility to configure the definition of an empty row may also be useful to developers using this approach to iterating through a worksheet. ## Conclusions While it might require a little more userland code by developers using PhpSpreadsheet; because they are faster, have no additional memory overhead, and provide more flexibility, Iterators are the recommended approach for looping through the rows (and cells) of a worksheet. ================================================ FILE: docs/topics/The Dating Game.md ================================================ # The Dating Game Date and Time values are stored in different ways in spreadsheet files, depending on the file format; but internally when working in Excel the cell always contains a numeric value, representing the number of days since a baseline date, and formatted to appear as a human-readable date using a "Number Format Mask". This number is sometimes referred to as a serialized Excel date or timestamp. ## Dates That baseline date is normally 1st January 1900, although it can be 1st January 1904 (if the original spreadsheet file was created using the Mac version of MS Excel). Excel maintains a flag in the file indicating which baseline should be used; for file formats that don't provide this flag (such as .slk or .csv), the calendar defaults to the 1900 baseline. ![Date as a number.png](images/The Dating Game/Date as a number.png) Note that the baseline date itself is day 1; so strictly speaking, the base date 0 is '1899-12-31': Excel considers any value between 0 and 1 as purely a time value, trying to display 0 using a date format mask like 'yyyy-mm-dd' will show an invalid date like '1900-01-00' rather than '1899-12-31', but when using a time format mask like 'hh:mm:ss' it will appear as '00:00:00' (midnight). Values less than 0 are invalid as dates or as times, so a negative value in a cell with a date "Number Format Mask" will display as '############' in Excel. Open/Libre Office and Gnumeric don't have this limitation, and negative date/timestamp values are recognised and formatted correctly; but it is recommended that you don't rely on this when working with PhpSpreadsheet. To write a date in a cell using PhpSpreadsheet, we need to calculate the serialized Excel datestamp for that date. Methods to do this are available in the Shared\Date class, which provides a number of methods for conversion between different date options typically used in PHP applications (Unix timestamp, PHP DateTime objects and some recognisable formatted strings) and the Excel serialized value; and vice versa. - Shared\Date::convertIsoDate() - Converts a date/time in [ISO-8601 standard format](https://en.wikipedia.org/wiki/ISO_8601) to an Excel serialized timestamp - Shared\Date::PHPToExcel() - Converts a Unix timestamp, a PHP DateTime object, or a recognisable formatted string to an Excel serialized timestamp - Shared\Date::dateTimeToExcel() - Converts a Unix timestamp to an Excel serialized timestamp - Shared\Date::timestampToExcel() - Converts a PHP DateTime object to an Excel serialized timestamp - Shared\Date::formattedPHPToExcel() - Converts year, month, day, hour, minute, and second to an Excel serialized timestamp - Shared\Date::excelToDateTimeObject() - Converts an Excel serialized timestamp to a PHP DateTime object - Shared\Date::excelToTimestamp() - Converts an Excel serialized timestamp to a Unix timestamp. - The use of Unix timestamps, and therefore this function, is discouraged: they are not Y2038-safe on a 32-bit system, and have no timezone info. We probably also want to set the number format mask for the cell so that it will be displayed as a human-readable date. ```php use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate; // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Calculate today's date as an Excel serialized timestamp $today = SharedDate::PHPToExcel(new DateTime('today')); $data = [ ['Formatted Date', 'Numeric Value'], ['=C2', 1], ['=C3', 2], ['=C4', $today], ]; // Write our data to the worksheet $worksheet->fromArray($data, null, 'B1'); // Display values in column B as human-readable dates $worksheet->getStyle('B2:B4')->getNumberFormat()->setFormatCode('yyyy-mm-dd'); // Set some additional styling $worksheet->getStyle('B1:C1')->getFont()->setBold(true); $worksheet->getColumnDimension('B')->setAutoSize(true); ``` ## Times Dates are always the integer part of the value (1, 2, 44943): the fractional part of the value is used to represent the time as a fraction of the day. So a value of 0.5 is 12:00 midday; 0.25 is 06:00 in the morning and 0.75 is 18:00 in the evening. ![Time as a number.png](images/The Dating Game/Time as a number.png) A float value greater than 1, like 44943.5 is considered as a datetime value: 12:00 (midday) on the 17th of January 2023. As with dates, to write a time value to a cell in PhpSpreadsheet, we write the numeric value for that time (or date/time) to the cell, and then apply a number format mask to the cell so that it will be displayed in a human-readable format. ```php use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate; // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Calculate today's date as an Excel serialized timestamp $today = SharedDate::PHPToExcel(new DateTime('today')); $data = [ ['Formatted Time', 'Numeric Value'], ['=C2', 0], ['=C3', 0.25], ['=C4', 0.5], ['=C5', 0.75], ['=C6', $today + 0.5], ]; // Write our data to the worksheet $worksheet->fromArray($data, null, 'B1', true); // Display values in column B as human-readable dates $worksheet->getStyle('B2:B5')->getNumberFormat()->setFormatCode('hh:mm:ss'); $worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('yyyy-mm-dd hh:mm:ss'); // Set some additional styling $worksheet->getStyle('B1:C1')->getFont()->setBold(true); $worksheet->getColumnDimension('B')->setAutoSize(true); ``` The same `Shared\Date` functions that convert between Excel dates and Unix Timestamps or PHP DateTime objects can also be used to convert time values. ## Dates/Times and Value Binders It is a standing joke that MS Excel tries to identify date and time values as you are entering data in Excel, and often treats any value as a possible date, converting it to an Excel serialized timestamp and applying date/time formatting, even though that may not have been what was intended. ![StringDateValues.jpg](images/The Dating Game/StringDateValues.jpg) Any change to a cell value in PhpSpreadsheet that isn't made using the setCellValueExplicit() method is passed through a "Value Binder", which triggers additional settings for that cell. > **Note**: dates and times maintained in true spreadsheet format files are always correctly identified in the file, and setCellValueExplicit() is used to store those values, with the formatting mask defined in that file. However, non-spreadsheet files such as .csv don't identify dates/times, so the Value Binder behaviour applies when loading those files. The Default Value Binder attempts to identify the datatype of the value and sets the cell datatype accordingly: and if you pass a string value like '2023-01-18 12:15:00' then the Default Value Binder will simply treat it as a string, and set it accordingly. However, if you choose to use the Advanced Value Binder, then that contains logic which looks more closely at those string values, and tries to determine if they are likely to be formatted dates or times, and in that regard it emulates Excel's behaviour. If the string value looks like a date or time, then it is converted to a serialized Excel date/timestamp, and an appropriate format mask is set for that cell. While the logic of this isn't perfect, I'd like to believe that it is less error-prone than Excel's own logic; but it won't necessarily recognise ambiguous formats and values correctly like '1/7/2023' as dates. (Is that the 1st of July? Or the 7th of January?) ## Reading Dates and Times from cells When we read the value of a cell that contains a Date/Time value, we are only reading a number (the Excel serialized timestamp); it is only the Number Format Mask that allows us to say whether that number is simply a number, or is meant to be a Date/Time value. PhpSpreadsheet provides a number of methods to identify whether a Number Format Mask represents a Date/Time format mask, or whether a Cell is formatted as a Date/Time. - Shared\Date::isDateTimeFormat() - Identifies if a NumberFormat Style object is an Excel Date/Time style format mask. - Shared\Date::isDateTimeFormatCode() - Identifies if the string value of a Number Format mask is an Excel Date/Time style format mask. - Shared\Date::isDateTime() - Identifies if a Cell is styled with a Number Format mask is an Excel Date/Time style format mask.**** These functions allow you to identify whether a cell value should be converted to a Unix Timestamp or PHP DateTime object (using one of the conversion functions provided in `Shared\Date`) for processing in your script, or for formatting as a Date/Time value. ## Date Arithmetic Because dates and times are just numeric values in MS Excel, this makes date/time arithmetic very easy to calculate: to count the number of days (or a duration) between two dates, we can use a simple subtraction. ![Date Arithmetic.png](images/The Dating Game/Date Arithmetic.png) Similarly, we can add date/time values like adding a duration to a start date to calculate an end date. ![Date Arithmetic 2.png](images/The Dating Game/Date Arithmetic 2.png) ## Excel Date Functions MS Excel provides a number of functions that will return a date or a time value. It also recognises when one of these functions is the "outer" function in a formula, so the final result will always be a serialized date/time value, and sets an appropriate format mask for that value. This behaviour is not replicated in PhpSpreadsheet. If you set a formula for a cell through your code that will return a date or time value, then you will also need to set the format mask for that cell manually. ## Formatting Options PhpSpreadsheet provides a number of built-in format code constants for dates and times in the NumberFormat class, matching those defined in the OfficeOpenXML specification, but you can always just set the format to any valid Excel formatting string, the equivalent of setting a custom date format in Excel. ### Dates When setting up a custom date format in Excel, you can use the following codes. | Code | Description | Example (January 3, 2023) | |-------|-------------------------------------|---------------------------------------| | m | Month number without a leading zero | 1 | | mm | Month number with a leading zero | 01 | | mmm | Month name, short form | Jan | | mmmm | Month name, full form | January | | mmmmm | Month as the first letter | J (stands for January, June and July) | | d | Day number without a leading zero | 3 | | dd | Day number with a leading zero | 03 | | ddd | Day of the week, short form | Tue | | dddd | Day of the week, full form | Tuesday | | yy | Year (last 2 digits) | 23 | | yyyy | Year (4 digits) | 2023 | ### Times When setting up a custom time format in Excel, you can use the following codes. | Code | Description | Displays as | |--------|--------------------------------------------------------------------|-------------| | h | Hours without a leading zero | 0-23 | | hh | Hours with a leading zero | 00-23 | | m | Minutes without a leading zero | 0-59 | | mm | Minutes with a leading zero | 00-59 | | s | Seconds without a leading zero | 0-59 | | ss | Seconds with a leading zero | 00-59 | | AM/PM | Periods of the day
(if omitted, 24-hour time format is used) | AM or PM | > **Warning** MS Excel allows any separator character between hours/minutes/seconds; PhpSpreadsheet currently requires a colon (`:`) to correctly distinguish minutes from months when rendering a time format within PHP code, although it will correctly write the format to file if any other separator character is used. ### Duration (Elapsed Time) Excel also supports formatting a value as a duration; a total number of hours, minutes or seconds rather than a time of day. However, please note that negative durations are supported only if using base year 1904 (Mac default). | Code | Description | Displays as | |---------|----------------------------------------------------------------|-------------| | [h]:mm | Elapsed time in hours | e.g. 25:02 | | [hh]:mm | Elapsed time in hours
with a leading zero if less than 10 | e.g. 05:02 | | [mm]:ss | Elapsed time in minutes | e.g. 63:46 | | [m]:ss | Elapsed time in minutes
with a leading zero if less than 10 | e.g. 03:46 | | [s] | Elapsed time in seconds | | | [ss] | Elapsed time in seconds
with a leading zero if less than 10 | | If you want to display an elapsed time in days, then you can use a normal date mask like `d h:mm` (without month or year), with the limitation that it will not exceed 31 days. ### Localisation #### Built-in Formats Some of the Excel built-in format masks are locale-aware. ![Locale.png](images/The Dating Game/Locale.png) Those locale-aware formats are highlighted with a * in Excel's drop-down lists for Date and Time, and will adapt when viewed in MS Excel, based on the locale settings of that local PC. PhpSpreadsheet is not locale-aware, so it will not render these formats as locale-formats, just as generic Date/Time formats; and localisation will be not be saved when writing to a spreadsheet file. #### Custom Formats When you're displaying a date/time using a format mask that isn't locale-aware in MS Excel, the locale settings for Excel are applied. So if you're displaying a month or day name, these will appear in the appropriate language for the locale of your PC. ![Locale1.png](images/The Dating Game/Locale1.png) You can force the display for a specific locale by prefixing the format mask with a locale setting, so that Excel will render it using the appropriate language. The locale code should be enclosed in [square brackets] and preceded with the dollar sign ($) and a dash (-). In this example, I'm forcing Dutch Netherlands by prefixing the mask with `[$-nl-NL]`. As an alternative, I could also have used the Windows LCID for that locale (`[$-413]`). ![Locale2.png](images/The Dating Game/Locale2.png) Because PhpSpreadsheet is not locale-aware, displaying the formatted value for that cell in your PHP script won't show the locale date/time, only a generic date/time; but it will still be written correctly when the file is saved (as a spreadsheet format) for Excel to render correctly and in the appropriate language. If you need this, then you can find a list of Windows LCID values [here](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/a29e5c28-9fb9-4c49-8e43-4b9b8e733a05) ## Summary Example Let's summarise some of this information with a script that will build a project timesheet for a week of work on that project. I'll keep the basic data in arrays for simplicity. ```php // In a real application, we might read this data from a database to build a project timesheet $projectHeading = [['Project', 'PhpSpreadsheet - The Dating Game']]; $weekHeading = [ ['Week', '=ISOWEEKNUM(D3)', 'Start Date', '=DATE(2023,1,16)'], ['Day', 'Start Time', 'End Time', 'Hours Worked'], ]; $timesheetData = [ ['2023-01-16', '17:25', '20:15'], ['2023-01-16', '20:50', '23:35'], ['2023-01-17', '18:10', '19:35'], ['2023-01-17', '20:10', '22:15'], ['2023-01-17', '22:35', '23:45'], ['2023-01-18', '09:15', '11:25'], ]; ``` Because I've used string values for the dates and times, I'm going to use the Advanced Value Binder to populate the worksheet. The Binder will also format the time values in columns B and C; but I want to override the Binder formatting for date values in column A; and I'm using an Excel formula for the "start date" value in cell D3, so I have to set the format manually for that. ```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'); ``` And then the final formatting: ```php // Display values in column A as human-readable dates $worksheet->getStyle("A5:A{$row}")->getNumberFormat()->setFormatCode('dd (ddd)'); // Display values in column D as human-readable durations $worksheet->getStyle("D5:D{$totalRow}")->getNumberFormat()->setFormatCode('[h]:mm'); // Set some additional styling $worksheet->getStyle('D3')->getNumberFormat()->setFormatCode('yyyy-mm-dd'); $worksheet->getStyle('A1')->getFont()->setBold(true); $worksheet->getStyle('A3:D4')->getFont()->setBold(true); $worksheet->getStyle("A5:A{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT); $worksheet->getColumnDimension('D')->setAutoSize(true); $worksheet->getStyle("E{$totalRow}")->getFont()->setBold(true); ``` And the resulting spreadsheet will look something like: ![Timesheet.png](images/The Dating Game/Timesheet.png) ## Final Notes MS Excel is not Timezone aware, nor does it have any logic for handling Daylight Savings. Excel functions like the NOW() function return the serialized timestamp of the current date and time. The date and time are provided by the operating system, and that determines, according to the time zone and date of the year if Daylight Saving Time is in effect. So functions like NOW() include any DST offset, because it is automatically included by the OS. ================================================ FILE: docs/topics/accessing-cells.md ================================================ # Accessing cells Accessing cells in a Spreadsheet should be pretty straightforward. This topic lists some of the options to access a cell. For all of these, the cell can be accessed by coordinate (e.g. `B3`), by an array of column index (where A is 1) and row (e.g. `[2, 3]`), or as a CellAddress object (e.g. `new CellAddress('B3', /* optional */ $worksheet)`. ## Setting a cell value Setting a cell value can be done using the worksheet's `setCellValue()` method. ```php // Set cell A1 with a string value $spreadsheet->getActiveSheet()->setCellValue('A1', 'PhpSpreadsheet'); // Set cell A2 with a numeric value $spreadsheet->getActiveSheet()->setCellValue([1, 2], 12345.6789); // Set cell A3 with a boolean value $spreadsheet->getActiveSheet()->setCellValue(new CellAddress('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 object, and then call the cell’s `setValue()` method: ```php $spreadsheet->getActiveSheet() ->getCell('B8') ->setValue('Some value'); ``` ### Creating a new Cell If you make a call to `getCell()`, and the cell doesn't already exist, then PhpSpreadsheet will create that cell for you. ### Copying a Cell's Value And Style Adjusting Formulas If cell A1 contains `5`, cell A2 contains `10`, and cell `B1` contains `=A1`, the formula in B1 will be evaluated as `5`. In Excel, if you copy B1 to B2, B2 will wind up with the adjusted formula `=A2` and will be evaluated as 10. Until release 5.1.0, PhpSpreadsheet requires the program to perform its own formula adjustment. In 5.1.0, a new method is introduced to handle formula adjustments: ```php $worksheet->copyformula($fromCell, $toCell); ``` This will behave as Excel does. If $fromCell does not contain a formula, its contents will be copied as-is. If you also want to copy $fromCell's style, as Excel does, you can use the following (available in all supported releases): ```php $worksheet->duplicateStyle($fromCell->getStyle(), $toCell); ``` ### BEWARE: Cells and Styles assigned to variables as a Detached Reference As an "in-memory" model, PHPSpreadsheet can be very demanding of memory, particularly when working with large spreadsheets. One technique used to reduce this memory overhead is cell caching, so cells are actually maintained in a collection that may or may not be held in memory while you are working with the spreadsheet. Because of this, a call to `getCell()` (or any similar method) returns the cell data, and sets a cell pointer to that cell in the collection. While this is not normally an issue, it can become significant if you assign the result of a call to `getCell()` to a variable. Any subsequent calls to retrieve other cells will change that pointer, although the cell object will still retain its data values. This is also true when assigning a variable to the result of `getStyle()`. What does this mean? Consider the following code: ```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; ``` The call to `getCell('C1')` returns the cell at `C1` containing its value (`3`), together with its link to the collection (used to identify its address/coordinate `C1`). The subsequent call to access cell `A1` modifies the value of `$cellC1`, detaching its link to the collection. So when we try to display the value and address a second time, we can display its value, but trying to display its address/coordinate will throw an exception because that link has been set to null. __Note:__ There are some internal methods that will fetch other cells from the collection, and this too will detach the link to the collection from any cell that you might have assigned to a variable. ## Excel DataTypes MS Excel supports 7 basic datatypes: - string - number - boolean - null - formula - error - Inline (or rich text) string By default, when you call the worksheet's `setCellValue()` method or the cell's `setValue()` method, PhpSpreadsheet 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. Note that a numeric string that begins with a leading zero (that isn't immediately followed by a decimal separator) will not be converted to a numeric, so values like phone numbers (e.g. `01615991375``will remain as strings). 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 PhpSpreadsheet 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. Formats handled by the advanced value binder include: - TRUE or FALSE (dependent on locale settings) are converted to booleans. - Numeric strings identified as scientific (exponential) format are converted to numbers. - Fractions and vulgar fractions are converted to numbers, and an appropriate number format mask applied. - Percentages are converted to numbers, divided by 100, and an appropriate number format mask applied. - Dates and times are converted to Excel timestamp values (numbers), and an appropriate number format mask applied. - When strings contain a newline character (`\n`), then the cell styling is set to wrap. Basically, it attempts to mimic the behaviour of the MS Excel GUI. You can read more about value binders [later in this section of the documentation](#using-value-binders-to-facilitate-data-entry). ### Setting a formula in a Cell As stated above, if you store a string value with the first character an `=` in a cell. PHPSpreadsheet will treat that value as a formula, and then you can evaluate that formula by calling `getCalculatedValue()` against the cell. There may be times though, when you wish to store a value beginning with `=` as a string, and that you don't want PHPSpreadsheet to evaluate as though it was a formula. To do this, you need to "escape" the value by setting it as "quoted text". ```php // 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 calculated 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 value in a cell 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. ```php // Get the current date/time and convert to an Excel date/time $dateTimeNow = time(); $excelDateValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $dateTimeNow ); // Set cell A6 with the Excel date/time value $spreadsheet->getActiveSheet()->setCellValue( 'A6', $excelDateValue ); // Set the number format mask so that the excel timestamp will be displayed as a human-readable date/time $spreadsheet->getActiveSheet()->getStyle('A6') ->getNumberFormat() ->setFormatCode( \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME ); ``` ### Setting a number with leading zeroes By default, PhpSpreadsheet 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". 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. There are two ways you can force PhpSpreadsheet to override this behaviour. Firstly, you can set the datatype explicitly as a string so that it is not converted to a number. ```php // Set cell A8 with a numeric value, but tell PhpSpreadsheet it should be treated as a string $spreadsheet->getActiveSheet()->setCellValueExplicit( 'A8', "01513789642", \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING ); ``` Alternatively, you can use a number format mask to display the value with leading zeroes. ```php // Set cell A9 with a numeric value $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 masking, you can even break up the digits into groups to make the value more easily readable. ```php // Set cell A10 with a numeric value $spreadsheet->getActiveSheet()->setCellValue('A10', 1513789642); // Set a number format mask to display the value as 11 digits with leading zeroes $spreadsheet->getActiveSheet()->getStyle('A10') ->getNumberFormat() ->setFormatCode( '0000-000-0000' ); ``` ![07-simple-example-1.png](./images/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 for certain writers such as HTML or PDF, but it will work with the true spreadsheet writers (Xlsx and Xls). ## Setting a range of cells from an array 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. ```php $arrayData = [ [NULL, 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 set NULL, // Array values with this value will not be set 'C3' // Top left coordinate of the worksheet range where // we want to set these values (default is A1) ); ``` ![07-simple-example-2.png](./images/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 treated as a single row, which is particularly useful if you're fetching an array of data from a database. ```php $rowArray = ['Value1', 'Value2', 'Value3', 'Value4']; $spreadsheet->getActiveSheet() ->fromArray( $rowArray, // The data to set NULL, // Array values with this value will not be set 'C3' // Top left coordinate of the worksheet range where // we want to set these values (default is A1) ); ``` ![07-simple-example-3.png](./images/07-simple-example-3.png) 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: ```php $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 left coordinate of the worksheet range where // we want to set these values (default is A1) ); ``` ![07-simple-example-4.png](./images/07-simple-example-4.png) ## Retrieving a cell value 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. ```php // Get the value from cell A1 $cellValue = $spreadsheet->getActiveSheet()->getCell('A1')->getValue(); ``` This will retrieve the raw, unformatted value contained in the cell. 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 [the calculation engine](./calculation-engine.md). ```php // Get the value from cell A4 $cellValue = $spreadsheet->getActiveSheet()->getCell('A4')->getCalculatedValue(); ``` 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. ```php // Get the value from cell A6 $cellValue = $spreadsheet->getActiveSheet()->getCell('A6')->getFormattedValue(); ``` ## Retrieving a range of cell values to an array 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. ```php $dataArray = $spreadsheet->getActiveSheet() ->rangeToArray( 'C3:E5', // The worksheet range that we want to retrieve NULL, // Value that should be returned for empty cells TRUE, // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell) TRUE, // Should values be formatted (the equivalent of getFormattedValue() for each cell) TRUE // Should the array be indexed by cell row and cell column ); ``` 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`. ## Looping through cells ### Looping through cells using iterators 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. Below is an example where we read all the values in a worksheet and display them in a table. ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx"); $worksheet = $spreadsheet->getActiveSheet(); echo '' . PHP_EOL; foreach ($worksheet->getRowIterator() as $row) { echo '' . PHP_EOL; $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells, // even if a cell value is not set. // For 'TRUE', we loop through cells // only when their value is set. // If this method is not called, // the default value is 'false'. foreach ($cellIterator as $cell) { echo '' . PHP_EOL; } echo '' . PHP_EOL; } echo '
' . $cell->getValue() . '
' . PHP_EOL; ``` 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. The cell iterator will create a new empty cell in the worksheet if it doesn't exist; return a `null` as the cell value if it is not set in the worksheet; although we can also tell it to return a null value rather than returning a new empty cell. Setting the cell iterator's `setIterateOnlyExistingCells()` to `false` will loop all cells in the worksheet that can be available at that moment. If this is then set to create new cells if required, then it will likely increase memory usage! Only use it if it is intended to loop all cells that are possibly available; otherwise use the option to return a null value if a cell doesn't exist, or iterate only the cells that already exist. It is also possible to call the Row object's `isEmpty()` method to determine whether you need to instantiate the Cell Iterator for that Row. ### Looping through cells using indexes One can use the possibility to access cell values by column and row index like `[1, 1]` instead of `'A1'` for reading and writing cell values in loops. **Note:** In PhpSpreadsheet column index and row index are 1-based. That means `'A1'` ~ `[1, 1]` Below is an example where we read all the values in a worksheet and display them in a table. ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx"); $worksheet = $spreadsheet->getActiveSheet(); // Get the highest row and column numbers referenced in the worksheet $highestRow = $worksheet->getHighestDataRow(); // e.g. 10 $highestColumn = $worksheet->getHighestDataColumn(); // e.g 'F' $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5 echo '' . "\n"; for ($row = 1; $row <= $highestRow; ++$row) { echo '' . PHP_EOL; // Use StringHelper::stringIncrement($col) rather than ++$col if using Php8.5+. for ($col = 1; $col <= $highestColumnIndex; ++$col) { $value = $worksheet->getCell([$col, $row])->getValue(); echo '' . PHP_EOL; } echo '' . PHP_EOL; } echo '
' . $value . '
' . PHP_EOL; ``` Alternatively, you can take advantage of PHP's "Perl-style" character incrementors to loop through the cells by coordinate: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx"); $worksheet = $spreadsheet->getActiveSheet(); // Get the highest row number and column letter referenced in the worksheet $highestRow = $worksheet->getHighestDataRow(); // e.g. 10 $highestColumn = $worksheet->getHighestDataColumn(); // e.g 'F' // Increment the highest column letter ++$highestColumn; // StringHelper::stringIncrement($highestColumn); if using Php8.5+. echo '' . "\n"; for ($row = 1; $row <= $highestRow; ++$row) { echo '' . PHP_EOL; // Use StringHelper::stringIncrement($col) rather than ++$col if using Php8.5+. for ($col = 'A'; $col != $highestColumn; ++$col) { echo '' . PHP_EOL; } echo '' . PHP_EOL; } echo '
' . $worksheet->getCell($col . $row) ->getValue() . '
' . PHP_EOL; ``` 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. ## Using value binders to facilitate data entry Internally, PhpSpreadsheet uses a default `\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` implementation (\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder) to determine data types of entered data using a cell's `setValue()` method (the `setValueExplicit()` method bypasses this check). Optionally, the default behaviour of PhpSpreadsheet can be modified, allowing easier data entry. For example, a `\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder` class is available. It automatically converts percentages, numbers 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 PhpSpreadsheet: ```php // Older method using static property \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); // Create new Spreadsheet object $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); // Preferred method using dynamic property since 3.4.0 $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $spreadsheet->setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); // ... // Add some data, resembling some different data types $spreadsheet->getActiveSheet()->setCellValue('A4', 'Percentage value:'); // Converts the string value to 0.1 and sets percentage cell style $spreadsheet->getActiveSheet()->setCellValue('B4', '10%'); $spreadsheet->getActiveSheet()->setCellValue('A5', 'Date/time value:'); // Converts the string value to an Excel datestamp and sets the date format cell style $spreadsheet->getActiveSheet()->setCellValue('B5', '21 December 1983'); ``` Alternatively, a `\PhpOffice\PhpSpreadsheet\Cell\StringValueBinder` class is available if you want to preserve all content as strings. This might be appropriate if you were loading a file containing values that could be interpreted as numbers (e.g. numbers with leading sign such as international phone 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 it into a string. However, there are a number of settings which allow you to specify that certain datatypes shouldn't be cast to strings, but left "as is": ```php // Set value binder $stringValueBinder = new \PhpOffice\PhpSpreadsheet\Cell\StringValueBinder(); $stringValueBinder->setNumericConversion(false) ->setSetIgnoredErrors(true) // suppresses "number stored as text" indicators ->setBooleanConversion(false) ->setNullConversion(false) ->setFormulaConversion(false); // Older method using static property \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( $stringValueBinder ); // Preferred method using dynamic property since 3.4.0 $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $spreadsheet->setValueBinder( $stringValueBinder ); ``` You can override the current binder when setting individual cell values by specifying a different Binder to use in the Cell's `setValue()` or the Worksheet's `setCellValue()` methods. ```php $spreadsheet = new Spreadsheet(); // Old method using static property Cell::setValueBinder(new AdvancedValueBinder()); // Preferred method using dynamic property since 3.4.0 $spreadsheet->setValueBinder(new AdvancedValueBinder()); $value = '12.5%'; $cell = $spreadsheet->getActiveSheet()->getCell('A1'); // Value will be set as a number 0.125 with a format mask '0.00%' $cell->setValue($value); // Using the Advanced Value Binder $cell = $spreadsheet->getActiveSheet()->getCell('A2'); // Value will be set as a string '12.5%' with a format mask 'General' $cell->setValue($value, new StringValueBinder()); // Overriding the Advanced Value Binder ``` ### Creating your own value binder Creating your own value binder is relatively straightforward. When more specialised value binding is required, you can implement the `\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` interface or extend the existing `\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder` or `\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder` classes. ================================================ FILE: docs/topics/architecture.md ================================================ # Architecture ## Schematical ![01-schematic.png](./images/01-schematic.png "Basic Architecture Schematic") ## AutoLoader PhpSpreadsheet relies on Composer autoloader. So before working with PhpSpreadsheet in standalone, be sure to run `composer install`. Or add it to a pre-existing project with `composer require phpoffice/phpspreadsheet`. ## Spreadsheet in memory PhpSpreadsheet's architecture is built in a way that it can serve as an in-memory spreadsheet. This means that, if one would want to create a web based view of a spreadsheet which communicates with PhpSpreadsheet's object model, he would only have to write the front-end code. Just like desktop spreadsheet software, PhpSpreadsheet represents a spreadsheet containing one or more worksheets, which contain cells with data, formulas, images, ... ## Readers and writers On its own, the `Spreadsheet` class does not provide the functionality to read from or write to a persisted spreadsheet (on disk or in a database). To provide that functionality, readers and writers can be used. By default, the PhpSpreadsheet package provides some readers and writers, including one for the Open XML spreadsheet format (a.k.a. Excel 2007 file format). You are not limited to the default readers and writers, as you are free to implement the `\PhpOffice\PhpSpreadsheet\Reader\IReader` and `\PhpOffice\PhpSpreadsheet\Writer\IWriter` interface in a custom class. ![02-readers-writers.png](./images/02-readers-writers.png "Readers/Writers") ## Fluent interfaces PhpSpreadsheet supports fluent interfaces in most locations. This means that you can easily "chain" calls to specific methods without requiring a new PHP statement. For example, take the following code: ```php $spreadsheet->getProperties()->setCreator("Maarten Balliauw"); $spreadsheet->getProperties()->setLastModifiedBy("Maarten Balliauw"); $spreadsheet->getProperties()->setTitle("Office 2007 XLSX Test Document"); $spreadsheet->getProperties()->setSubject("Office 2007 XLSX Test Document"); $spreadsheet->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes."); $spreadsheet->getProperties()->setKeywords("office 2007 openxml php"); $spreadsheet->getProperties()->setCategory("Test result file"); ``` This can be rewritten as: ```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"); ``` > **Using fluent interfaces is not required** Fluent interfaces have > been implemented to provide a convenient programming API. Use of them > is not required, but can make your code easier to read and maintain. > It can also improve performance, as you are reducing the overall > number of calls to PhpSpreadsheet methods: in the above example, the > `getProperties()` method is being called only once rather than 7 times > in the non-fluent version. ================================================ FILE: docs/topics/autofilters.md ================================================ # AutoFilter Reference ## Introduction Each worksheet in an Excel Workbook can contain a single autoFilter range. Filtered data displays only the rows that meet criteria that you specify and hides rows that you do not want displayed. You can filter by more than one column: filters are additive, which means that each additional filter is based on the current filter and further reduces the subset of data. ![01-01-autofilter.png](./images/01-01-autofilter.png) When an AutoFilter is applied to a range of cells, the first row in an autofilter range will be the heading row, which displays the autoFilter dropdown icons. It is not part of the actual autoFiltered data. All subsequent rows are the autoFiltered data. So an AutoFilter range should always contain the heading row and one or more data rows (one data row is pretty meaningless), but PhpSpreadsheet won't actually stop you specifying a meaningless range: it's up to you as a developer to avoid such errors. To determine if a filter is applied, note the icon in the column heading. A drop-down arrow (![01-03-filter-icon-1.png](./images/01-03-filter-icon-1.png)) means that filtering is enabled but not applied. In MS Excel, when you hover over the heading of a column with filtering enabled but not applied, a screen tip displays the cell text for the first row in that column, and the message "(Showing All)". ![01-02-autofilter.png](./images/01-02-autofilter.png) A Filter button (![01-03-filter-icon-2.png](./images/01-03-filter-icon-2.png)) means that a filter is applied. When you hover over the heading of a filtered column, a screen tip displays the filter that has been applied to that column, such as "Equals a red cell color" or "Larger than 150". ![01-04-autofilter.png](./images/01-04-autofilter.png) ## Setting an AutoFilter area on a worksheet To set an autoFilter on a range of cells. ```php $spreadsheet->getActiveSheet()->setAutoFilter('A1:E20'); ``` The first row in an autofilter range will be the heading row, which displays the autoFilter dropdown icons. It is not part of the actual autoFiltered data. All subsequent rows are the autoFiltered data. So an AutoFilter range should always contain the heading row and one or more data rows (one data row is pretty meaningless, but PhpSpreadsheet won't actually stop you specifying a meaningless range: it's up to you as a developer to avoid such errors. If you want to set the whole worksheet as an autofilter region ```php $spreadsheet->getActiveSheet()->setAutoFilter( $spreadsheet->getActiveSheet() ->calculateWorksheetDimension() ); ``` This enables filtering, but does not actually apply any filters. After setting the range, you can change it so that the end row is the last row used on the worksheet: ```php $spreadsheet->getActiveSheet()->getAutoFilter()->setRangeToMaxRow(); ``` ## Autofilter Expressions PHPEXcel 1.7.8 introduced the ability to actually create, read and write filter expressions; initially only for Xlsx files, but later releases will extend this to other formats. To apply a filter expression to an autoFilter range, you first need to identify which column you're going to be applying this filter to. ```php $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $columnFilter = $autoFilter->getColumn('C'); ``` This returns an autoFilter column object, and you can then apply filter expressions to that column. There are a number of different types of autofilter expressions. The most commonly used are: - Simple Filters - DateGroup Filters - Custom filters - Dynamic Filters - Top Ten Filters These different types are mutually exclusive within any single column. You should not mix the different types of filter in the same column. PhpSpreadsheet will not actively prevent you from doing this, but the results are unpredictable. Other filter expression types (such as cell colour filters) are not yet supported. String comparisons in filters are case-insensitive. ### Simple filters In MS Excel, Simple Filters are a dropdown list of all values used in that column, and the user can select which ones they want to display and which ones they want to hide by ticking and unticking the checkboxes alongside each option. When the filter is applied, rows containing the checked entries will be displayed, rows that don't contain those values will be hidden. ![04-01-simple-autofilter.png](./images/04-01-simple-autofilter.png) To create a filter expression, we need to start by identifying the filter type. In this case, we're just going to specify that this filter is a standard filter. *Please note that Excel regards only tests for equal as a standard filter; all others, including tests for not equal, must be supplied as custom filters.* ```php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER ); ``` Now we've identified the filter type, we can create a filter rule and set the filter values: When creating a simple filter in PhpSpreadsheet, you only need to specify the values for "checked" columns: you do this by creating a filter rule for each value. ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'France' ); $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'Germany' ); ``` This creates two filter rules: the column will be filtered by values that match "France" OR "Germany". For Simple Filters, you can create as many rules as you want Simple filters are always a comparison match of EQUALS, and multiple standard filters are always treated as being joined by an OR condition. #### Matching Blanks If you want to create a filter to select blank cells, you would use: ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, '' ); ``` ### DateGroup Filters In MS Excel, DateGroup filters provide a series of dropdown filter selectors for date values, so you can specify entire years, or months within a year, or individual days within each month. Note that cells covered by such a filter are expected to be in [Excel DateTime Format](./calculation-engine.md#excel-timestamps). ![04-02-dategroup-autofilter.png](./images/04-02-dategroup-autofilter.png) DateGroup filters are still applied as a Standard Filter type. ```php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER ); ``` Creating a dateGroup filter in PhpSpreadsheet, you specify the values for "checked" columns as an associative array of year. month, day, hour minute and second. To select a year and month, you need to create a DateGroup rule identifying the selected year and month: ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, [ 'year' => 2012, 'month' => 1 ] ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP ); ``` The key values for the associative array are: - year - month - day - hour - minute - second Like Standard filters, DateGroup filters are always a match of EQUALS, and multiple standard filters are always treated as being joined by an OR condition. Note that we alse specify a ruleType: to differentiate this from a standard filter, we explicitly set the Rule's Type to AUTOFILTER\_RULETYPE\_DATEGROUP. As with standard filters, we can create any number of DateGroup Filters. ### Custom filters In MS Excel, Custom filters allow us to select more complex conditions using an operator as well as a value. Typical examples might be values that fall within a range (e.g. between -20 and +20), or text values with wildcards (e.g. beginning with the letter U). To handle this, they ![04-03-custom-autofilter-1.png](./images/04-03-custom-autofilter-1.png) ![04-03-custom-autofilter-2.png](./images/04-03-custom-autofilter-2.png) Custom filters are limited to 2 rules, and these can be joined using either an AND or an OR. We start by specifying a Filter type, this time a CUSTOMFILTER. ```php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER ); ``` And then define our rules. The following shows a simple wildcard filter to show all column entries beginning with the letter `U`. ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'U*' ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER ); ``` MS Excel uses `*` as a wildcard to match any number of characters, and `?` as a wildcard to match a single character. `U*` equates to "begins with a 'U'"; `*U` equates to "ends with a 'U'"; and `*U*` equates to "contains a 'U'". Note that PhpSpreadsheet recognizes wildcards only for equal/not-equal tests. If you want to match explicitly against `*` or `?`, you can escape it with a tilde `~`, so `?~**` would explicitly match for `*` as the second character in the cell value, followed by any number of other characters. The only other character that needs escaping is the `~` itself. To create a "between" condition, we need to define two rules: ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, -20 ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER ); $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, 20 ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER ); ``` We also set the rule type to CUSTOMFILTER. This defined two rules, filtering numbers that are `>= -20` OR `<= 20`, so we also need to modify the join condition to reflect AND rather than OR. ```php $columnFilter->setJoin( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND ); ``` The valid set of operators for Custom Filters are defined in the `\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule` class, and comprise: Operator Constant | Value ------------------------------------------|---------------------- AUTOFILTER_COLUMN_RULE_EQUAL | 'equal' AUTOFILTER_COLUMN_RULE_NOTEQUAL | 'notEqual' AUTOFILTER_COLUMN_RULE_GREATERTHAN | 'greaterThan' AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL | 'greaterThanOrEqual' AUTOFILTER_COLUMN_RULE_LESSTHAN | 'lessThan' AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL | 'lessThanOrEqual' ### Dynamic Filters Dynamic Filters are based on a dynamic comparison condition, where the value we're comparing against the cell values is variable, such as 'today'; or when we're testing against an aggregate of the cell data (e.g. 'aboveAverage'). Only a single dynamic filter can be applied to a column at a time. ![04-04-dynamic-autofilter.png](./images/04-04-dynamic-autofilter.png) Again, we start by specifying a Filter type, this time a DYNAMICFILTER. ```php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER ); ``` When defining the rule for a dynamic filter, we don't define a value (we can simply set that to null string) but we do specify the dynamic filter category. ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, '', \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER ); ``` We also set the rule type to DYNAMICFILTER. The valid set of dynamic filter categories is defined in the `\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule` class, and comprises: Operator Constant | Value -----------------------------------------|---------------- AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY | 'yesterday' AUTOFILTER_RULETYPE_DYNAMIC_TODAY | 'today' AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW | 'tomorrow' AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE | 'yearToDate' AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR | 'thisYear' AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER | 'thisQuarter' AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH | 'thisMonth' AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK | 'thisWeek' AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR | 'lastYear' AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER | 'lastQuarter' AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH | 'lastMonth' AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK | 'lastWeek' AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR | 'nextYear' AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER | 'nextQuarter' AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH | 'nextMonth' AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK | 'nextWeek' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 | 'M1' AUTOFILTER_RULETYPE_DYNAMIC_JANUARY | 'M1' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 | 'M2' AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY | 'M2' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 | 'M3' AUTOFILTER_RULETYPE_DYNAMIC_MARCH | 'M3' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 | 'M4' AUTOFILTER_RULETYPE_DYNAMIC_APRIL | 'M4' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 | 'M5' AUTOFILTER_RULETYPE_DYNAMIC_MAY | 'M5' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 | 'M6' AUTOFILTER_RULETYPE_DYNAMIC_JUNE | 'M6' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 | 'M7' AUTOFILTER_RULETYPE_DYNAMIC_JULY | 'M7' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 | 'M8' AUTOFILTER_RULETYPE_DYNAMIC_AUGUST | 'M8' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 | 'M9' AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER | 'M9' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 | 'M10' AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER | 'M10' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 | 'M11' AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER | 'M11' AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 | 'M12' AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER | 'M12' AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 | 'Q1' AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 | 'Q2' AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 | 'Q3' AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 | 'Q4' AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE | 'aboveAverage' AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE | 'belowAverage' We can only apply a single Dynamic Filter rule to a column at a time. ### Top Ten Filters Top Ten Filters are similar to Dynamic Filters in that they are based on a summarisation of the actual data values in the cells. However, unlike Dynamic Filters where you can only select a single option, Top Ten Filters allow you to select based on a number of criteria: ![04-05-custom-topten-1.png](./images/04-05-topten-autofilter-1.png) ![04-05-custom-topten-2.png](./images/04-05-topten-autofilter-2.png) You can identify whether you want the top (highest) or bottom (lowest) values.You can identify how many values you wish to select in the filterYou can identify whether this should be a percentage or a number of items. Like Dynamic Filters, only a single Top Ten filter can be applied to a column at a time. We start by specifying a Filter type, this time a DYNAMICFILTER. ```php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER ); ``` Then we create the rule: ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, 5, \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER ); ``` This will filter the Top 5 percent of values in the column. To specify the lowest (bottom 2 values), we would specify a rule of: ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, 5, \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) ->setRuleType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER ); ``` The option values for TopTen Filters top/bottom value/percent are all defined in the `\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule` class, and comprise: Operator Constant | Value ---------------------------------------|------------- AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE | 'byValue' AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT | 'byPercent' and Operator Constant | Value -------------------------------------|---------- AUTOFILTER_COLUMN_RULE_TOPTEN_TOP | 'top' AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM | 'bottom' ## Executing an AutoFilter When an autofilter is applied in MS Excel, it sets the row hidden/visible flags for each row of the autofilter area based on the selected criteria, so that only those rows that match the filter criteria are displayed. PhpSpreadsheet will not execute the equivalent function automatically when you set or change a filter expression, but only when the file is saved. ### Applying the Filter If you wish to execute your filter from within a script, you need to do this manually. You can do this using the autofilters `showHideRows()` method. ```php $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $autoFilter->showHideRows(); ``` This will set all rows that match the filter criteria to visible, while hiding all other rows within the autofilter area. Excel allows you to explicitly hide a row after applying a filter even if the row wasn't hidden by the filter. However, if a row is hidden *before* applying the filter, and the filter is applied, the row will no longer be hidden. This can make a difference during PhpSpreadsheet save, since PhpSpreadsheet will apply the filter during save if it hasn't been previously applied, or if the filter criteria have changed since it was last applied. Note that an autofilter read in from an existing spreadsheet is assumed to have been applied. Also note that changing the data in the columns being filtered does not result in reevaluation in either Excel or PhpSpreadsheet. If you wish to re-apply all filters in the spreadsheet (possibly just before save): ```php $spreadsheet->reevaluateAutoFilters(false); ``` You can specify `true` rather than `false` to adjust the filter ranges on each sheet so that they end at the last row used on the sheet. ### Displaying Filtered Rows Simply looping through the rows in an autofilter area will still access every row, whether it matches the filter criteria or not. To selectively access only the filtered rows, you need to test each row’s visibility settings. ```php foreach ($spreadsheet->getActiveSheet()->getRowIterator() as $row) { if ($spreadsheet->getActiveSheet() ->getRowDimension($row->getRowIndex())->getVisible()) { echo ' Row number - ' , $row->getRowIndex() , ' '; echo $spreadsheet->getActiveSheet() ->getCell( 'C'.$row->getRowIndex() ) ->getValue(), ' '; echo $spreadsheet->getActiveSheet() ->getCell( 'D'.$row->getRowIndex() )->getFormattedValue(), ' '; echo PHP_EOL; } } ``` ## AutoFilter Sorting In MS Excel, Autofiltering also allows the rows to be sorted. This feature is ***not*** supported by PhpSpreadsheet. ================================================ FILE: docs/topics/calculation-engine.md ================================================ # Calculation Engine ## Using the PhpSpreadsheet calculation engine ### Performing formula calculations As PhpSpreadsheet represents an in-memory spreadsheet, it also offers formula calculation capabilities. A cell can be of a value type (containing a number or text), or a formula type (containing a formula which can be evaluated). For example, the formula `=SUM(A1:A10)` evaluates to the sum of values in A1, A2, ..., A10. Calling `getValue()` on a cell that contains a formula will return the formula itself. To calculate a formula, you can call the cell containing the formula’s method `getCalculatedValue()`, for example: ```php $spreadsheet->getActiveSheet()->getCell('E11')->getCalculatedValue(); ``` If you write the following line of code in the invoice demo included with PhpSpreadsheet, it evaluates to the value "64": ![09-command-line-calculation.png](./images/09-command-line-calculation.png) Calling `getCalculatedValue()` on a cell that doesn't contain a formula will simply return the value of that cell; but if the cell does contain a formula, then PhpSpreadsheet will evaluate that formula to calculate the result. There are a few useful mehods to help identify whether a cell contains a formula or a simple value; and if a formula, to provide further information about it: ```php $spreadsheet->getActiveSheet()->getCell('E11')->isFormula(); ``` will return a boolean true/false, telling you whether that cell contains a formula or not, so you can determine if a call to `getCalculatedVaue()` will need to perform an evaluation. For more details on working with array formulas, see the [the recipes documentationn](./recipes.md/#array-formulas). When writing a formula to a cell, formulas should always be set as they would appear in an English version of Microsoft Office Excel, and PhpSpreadsheet handles all formulas internally in this format. This means that the following rules hold: - Decimal separator is `.` (period) - Function argument separator is `,` (comma) - Matrix row separator is `;` (semicolon) - English function names must be used Another nice feature of PhpSpreadsheet's formula parser, is that it can automatically adjust a formula when inserting/removing rows/columns. Here's an example: ![09-formula-in-cell-1.png](./images/09-formula-in-cell-1.png) You see that the formula contained in cell E11 is "SUM(E4:E9)". Now, when I write the following line of code, two new product lines are added: ```php $spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2); ``` ![09-formula-in-cell-2.png](./images/09-formula-in-cell-2.png) Did you notice? The formula in the former cell E11 (now E13, as I inserted 2 new rows), changed to "SUM(E4:E11)". Also, the inserted cells duplicate style information of the previous cell, just like Excel's behaviour. Note that you can both insert rows and columns. If you want to "anchor" a specific cell for a formula, then you prefix the column and/or the row with a `$` symbol, exactly as you would in MS Excel itself. So if a formula contains "SUM(E$4:E9)", and you insert 2 new rows after row 1, the formula will be adjusted to read "SUM(E$4:E11)", with the `$` fixing row 4 as the start of the range. ## Calculation Cache Once the Calculation engine has evaluated the formula in a cell, the result will be cached, so if you call `getCalculatedValue()` a second time for the same cell, the result will be returned from the cache rather than evaluating the formula a second time. This helps boost performance, because evaluating a formula is an expensive operation in terms of performance and speed. However, there may be times when you don't want this, perhaps you've changed the underlying data and need to re-evaluate the same formula with that new data. ```php Calculation::getInstance($spreadsheet)->disableCalculationCache(); ``` Will disable calculation caching, and flush the current calculation cache. If you want only to flush the cache, then you can call ```php Calculation::getInstance($spreadsheet)->clearCalculationCache(); ``` ## Known limitations There are some known limitations to the PhpSpreadsheet calculation engine. Most of them are due to the fact that an Excel formula is converted into PHP code before being executed. This means that Excel formula calculation is subject to PHP's language characteristics. ### Function that are not Supported in Xls Not all functions are supported, for a comprehensive list, read the [function list by name](../references/function-list-by-name.md). #### Array arguments for Function Calls in Formulas While most of the Excel function implementations now support array arguments, there are a few that should accept arrays as arguments but don't do so. In these cases, the result may be a single value rather than an array; or it may be a `#VALUE!` error. #### Operator precedence In Excel `+` wins over `&`, just like `*` wins over `+` in ordinary algebra. The former rule is not what one finds using the calculation engine shipped with PhpSpreadsheet. - [Reference for Excel](https://support.office.com/en-us/article/Calculation-operators-and-precedence-in-Excel-48be406d-4975-4d31-b2b8-7af9e0e2878a) - [Reference for PHP](https://php.net/manual/en/language.operators.php) #### Formulas involving numbers and text Formulas involving numbers and text may produce unexpected results or even unreadable file contents. For example, the formula `=3+"Hello "` is expected to produce an error in Excel (\#VALUE!). Due to the fact that PHP converts `"Hello "` to a numeric value (zero), the result of this formula is evaluated as 3 instead of evaluating as an error. This also causes the Excel document being generated as containing unreadable content. - [Reference for this behaviour in PHP](https://php.net/manual/en/language.types.string.php#language.types.string.conversion) #### Formulas don’t seem to be calculated in Excel2003 using compatibility pack? This is normal behaviour of the compatibility pack, Xlsx displays this correctly. Use `\PhpOffice\PhpSpreadsheet\Writer\Xls` if you really need calculated values, or force recalculation in Excel2003. #### PAD (Precision As Displayed) Not Supported There are no plans to support Precision As Displayed. ## Handling Date and Time Values ### Excel functions that return a Date and Time value Any of the Date and Time functions that return a date value in Excel can return either an Excel timestamp or a PHP timestamp or `DateTime` object. It is possible for scripts to change the data type used for returning date values by calling the `\PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType()` method: ```php \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType($returnDateType); ``` where the following constants can be used for `$returnDateType`: - `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_NUMERIC` - `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_OBJECT` - `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL` The method will return a Boolean True on success, False on failure (e.g. if an invalid value is passed in for the return date type). The `\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType()` method can be used to determine the current value of this setting: ```php $returnDateType = \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(); ``` The default is `RETURNDATE_PHP_NUMERIC`. #### PHP Timestamps If `RETURNDATE_PHP_NUMERIC` is set for the Return Date Type, then any date value returned to the calling script by any access to the Date and Time functions in Excel will be an integer value that represents the number of seconds from the PHP/Unix base date. The PHP/Unix base date (0) is 00:00 UST on 1st January 1970. This value can be positive or negative: so a value of -3600 would be 23:00 hrs on 31st December 1969; while a value of +3600 would be 01:00 hrs on 1st January 1970. This gives 32-bit PHP a date range of between 14th December 1901 and 19th January 2038. #### PHP `DateTime` Objects If the Return Date Type is set for `RETURNDATE_PHP_OBJECT`, then any date value returned to the calling script by any access to the Date and Time functions in Excel will be a PHP `DateTime` object. #### Excel Timestamps Excel timestamps are stored as integer or floating point, where the integer portion represents the number of days since a base date, and the fraction portion represents the time of day (0 is midnight, 0.5 is noon, 0.999... is just before midnight the next day). The Excel base date is determined by which calendar Excel uses: the Windows 1900 or the Mac 1904 calendar. 1st January 1900 is the base date for the Windows 1900 calendar while 1st January 1904 is the base date for the Mac 1904 calendar. If `RETURNDATE_EXCEL` is set for the Return Date Type, then the returned date value by any access to the Date and Time functions in Excel will be a floating point value in Excel timestamp format (previous paragraph). It is possible for scripts to change the calendar used for calculating Excel date values by calling: ```php \PhpOffice\PhpSpreadsheet\Shared\Date::setExcelCalendar($baseDate); // static property, less preferred $spreadsheet->setExcelCalendar($baseDate); // instance property, preferred ``` where the following constants can be used for `$baseDate`: - `\PhpOffice\PhpSpreadsheet\Shared\Date::CALENDAR_WINDOWS_1900` - `\PhpOffice\PhpSpreadsheet\Shared\Date::CALENDAR_MAC_1904` The method will return a Boolean True on success, False on failure (e.g. if an invalid value is passed in). The current value of this setting can be determined via: ```php $baseDate = \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar(); // static $baseDate = $spreadsheet->getExcelCalendar(); // instance ``` The default is `CALENDAR_WINDOWS_1900`. #### Functions that return a Date/Time Value - DATE - DATEVALUE - EDATE - EOMONTH - NOW - TIME - TIMEVALUE - TODAY ### Excel functions that accept Date and Time values as parameters Date values passed in as parameters to a function can be an Excel timestamp or a PHP timestamp; or `DateTime` object; or a string containing a date value (e.g. '1-Jan-2009'). PhpSpreadsheet will attempt to identify their type based on the PHP datatype: An integer numeric value will be treated as a PHP/Unix timestamp. A real (floating point) numeric value will be treated as an Excel date/timestamp. Any PHP `DateTime` object will be treated as a `DateTime` object. Any string value (even one containing straight numeric data) will be converted to a `DateTime` object for validation as a date value based on the server locale settings, so passing through an ambiguous value of '07/08/2008' will be treated as 7th August 2008 if your server settings are UK, but as 8th July 2008 if your server settings are US. However, if you pass through a value such as '31/12/2008' that would be considered an error by a US-based server, but which is not ambiguous, then PhpSpreadsheet will attempt to correct this to 31st December 2008. If the content of the string doesn’t match any of the formats recognised by the php `DateTime` object implementation of `strtotime()` (which can handle a wider range of formats than the normal `strtotime()` function), then the function will return a `#VALUE` error. However, Excel recommends that you should always use date/timestamps for your date functions, and the recommendation for PhpSpreadsheet is the same: avoid strings because the result is not predictable. The same principle applies when data is being written to Excel. Cells containing date actual values (rather than Excel functions that return a date value) are always written as Excel dates, converting where necessary. If a cell formatted as a date contains an integer or `DateTime` object value, then it is converted to an Excel value for writing: if a cell formatted as a date contains a real value, then no conversion is required. Note that string values are written as strings rather than converted to Excel date timestamp values. #### Functions that expect a Date/Time Value - DATEDIF - DAY - DAYS360 - EDATE - EOMONTH - HOUR - MINUTE - MONTH - NETWORKDAYS - SECOND - WEEKDAY - WEEKNUM - WORKDAY - YEAR - YEARFRAC ### Helper Methods In addition to the `setExcelCalendar()` and `getExcelCalendar()` methods, a number of other methods are available in the `\PhpOffice\PhpSpreadsheet\Shared\Date` class that can help when working with dates: #### \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDate) Converts a date/time from an Excel date timestamp to return a PHP serialized date/timestamp. Note that this method does not trap for Excel dates that fall outside of the valid range for a PHP date timestamp. #### \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($excelDate) Converts a date from an Excel date/timestamp to return a PHP `DateTime` object. #### \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($PHPDate) Converts a PHP serialized date/timestamp or a PHP `DateTime` object to return an Excel date timestamp. #### \PhpOffice\PhpSpreadsheet\Shared\Date::formattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) Takes year, month and day values (and optional hour, minute and second values) and returns an Excel date timestamp value. ### Timezone support for Excel date timestamp conversions The default timezone for the date functions in PhpSpreadsheet is UST (Universal Standard Time). If a different timezone needs to be used, these methods are available: #### \PhpOffice\PhpSpreadsheet\Shared\Date::getDefaultTimezone() Returns the current timezone value PhpSpeadsheet is using to handle dates and times. #### \PhpOffice\PhpSpreadsheet\Shared\Date::setDefaultTimezone($timeZone) Sets the timezone for Excel date timestamp conversions to $timeZone, which must be a valid PHP DateTimeZone value. The return value is a Boolean, where true is success, and false is failure (e.g. an invalid DateTimeZone value was passed.) #### \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($excelDate, $timeZone) #### \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimeStamp($excelDate, $timeZone) These functions support a timezone as an optional second parameter. This applies a specific timezone to that function call without affecting the default PhpSpreadsheet Timezone. ### Calculating Value of Date/Time Read From Spreadsheet Nothing special needs to be done to interpret Date/Time values entered directly into a spreadsheet. They will have been stored as numbers with an appropriate number format set for the cell. However, depending on their value, they may have been stored as either integer or float values. If that is a problem, you can force `getCalculatedValue` to return float rather than int depending on the number format used for the cell. ```php // All fields with Date, Time, or DateTime styles returned as float. \PhpOffice\PhpSpreadsheet\Cell\Cell::setCalculateDateTimeType(\PhpOffice\PhpSpreadsheet\Cell\Cell::CALCULATE_DATE_TIME_FLOAT); // All fields with Time or DateTime styles returned as float. \PhpOffice\PhpSpreadsheet\Cell\Cell::setCalculateDateTimeType(\PhpOffice\PhpSpreadsheet\Cell\Cell::CALCULATE_TIME_FLOAT); // Default - fields with Date, Time, or DateTime styles returned as they had been stored. \PhpOffice\PhpSpreadsheet\Cell\Cell::setCalculateDateTimeType(\PhpOffice\PhpSpreadsheet\Cell\Cell::CALCULATE_DATE_TIME_ASIS); ``` ## Function Reference ### Database Functions #### DAVERAGE The DAVERAGE function returns the average value of the cells in a column of a list or database that match conditions you specify. ##### Syntax DAVERAGE (database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The average value of the matching cells. This is the statistical mean. ##### Examples ```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', '=DAVERAGE(A4:E10,"Yield",A1:B2)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 12 ``` ##### Notes There are no additional notes on this function #### DCOUNT The DCOUNT function returns the count of cells that contain a number in a column of a list or database matching conditions that you specify. ##### Syntax DCOUNT(database, [field], criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The count of the matching cells. ##### Examples ```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 ``` ##### Notes In MS Excel, The field argument is optional. If field is omitted, DCOUNT counts all records in the database that match the criteria. This logic has not yet been implemented in PhpSpreadsheet. #### DCOUNTA The DCOUNTA function returns the count of cells that aren’t blank in a column of a list or database and that match conditions that you specify. ##### Syntax DCOUNTA(database, [field], criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The count of the matching cells. ##### Examples ```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 ``` ##### Notes In MS Excel, The field argument is optional. If field is omitted, DCOUNTA counts all records in the database that match the criteria. This logic has not yet been implemented in PhpSpreadsheet. #### DGET The DGET function extracts a single value from a column of a list or database that matches conditions that you specify. ##### Syntax DGET(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **mixed** The value from the selected column of the matching row. #### Examples ```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', '=GET(A4:E10,"Age",A1:F2)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 14 ``` ##### Notes There are no additional notes on this function #### DMAX The DMAX function returns the largest number in a column of a list or database that matches conditions you specify. ##### Syntax DMAX(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The maximum value of the matching cells. ##### Examples ```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', '=DMAX(A4:E10,"Profit",A1:B2)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 105 ``` ##### Notes There are no additional notes on this function #### DMIN The DMIN function returns the smallest number in a column of a list or database that matches conditions you specify. ##### Syntax DMIN(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The minimum value of the matching cells. ##### Examples ```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 ``` ##### Notes There are no additional notes on this function #### DPRODUCT The DPRODUCT function multiplies the values in a column of a list or database that match conditions that you specify. ##### Syntax DPRODUCT(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The product of the matching cells. ##### Examples ```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 ``` ##### Notes There are no additional notes on this function #### DSTDEV The DSTDEV function estimates the standard deviation of a population based on a sample by using the numbers in a column of a list or database that match conditions that you specify. ##### Syntax DSTDEV(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The estimated standard deviation of the matching cells. ##### Examples ```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 ``` ##### Notes There are no additional notes on this function #### DSTDEVP The DSTDEVP function calculates the standard deviation of a population based on the entire population by using the numbers in a column of a list or database that match conditions that you specify. ##### Syntax DSTDEVP(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The estimated standard deviation of the matching cells. ##### Examples ```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', '=DSTDEVP(A4:E10,"Yield",A1:A3)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 2.65 ``` ##### Notes There are no additional notes on this function #### DSUM The DSUM function adds the numbers in a column of a list or database that matches conditions you specify. ##### Syntax DSUM(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. **field** Indicates which column of the database is used in the function. Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. **criteria** The range of cells that contains the conditions you specify. You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. ##### Return Value **float** The total value of the matching cells. ##### Examples ```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 ``` ##### Notes There are no additional notes on this function #### DVAR Not yet documented. #### DVARP Not yet documented. ### Date and Time Functions Excel provides a number of functions for the manipulation of dates and times, and calculations based on date/time values. it is worth spending some time reading the section titled "Date and Time Values" on passing date parameters and returning date values to understand how PhpSpreadsheet reconciles the differences between dates and times in Excel and in PHP. #### DATE The DATE function returns an Excel timestamp or a PHP timestamp or `DateTime` object representing the date that is referenced by the parameters. ##### Syntax DATE(year, month, day) ##### Parameters **year** The year number. If this value is between 0 (zero) and 1899 inclusive (for the Windows 1900 calendar), or between 4 and 1903 inclusive (for the Mac 1904), then PhpSpreadsheet adds it to the Calendar base year, so a value of 108 will interpret the year as 2008 when using the Windows 1900 calendar, or 2012 when using the Mac 1904 calendar. **month** The month number. If this value is greater than 12, the DATE function adds that number of months to the first month in the year specified. For example, DATE(2008,14,2) returns a value representing February 2, 2009. If the value of **month** is less than 1, then that value will be adjusted by -1, and that will then be subtracted from the first month of the year specified. For example, DATE(2008,0,2) returns a value representing December 2, 2007; while DATE(2008,-1,2) returns a value representing November 2, 2007. **day** The day number. If this value is greater than the number of days in the month (and year) specified, the DATE function adds that number of days to the first day in the month. For example, DATE(2008,1,35) returns a value representing February 4, 2008. If the value of **day** is less than 1, then that value will be adjusted by -1, and that will then be subtracted from the first month of the year specified. For example, DATE(2008,3,0) returns a value representing February 29, 2008; while DATE(2008,3,-2) returns a value representing February 27, 2008. ##### Return Value **mixed** A date/time stamp that corresponds to the given date. This could be a PHP timestamp value (integer), a PHP `DateTime` object, or an Excel timestamp value (real), depending on the value of `\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType()`. ##### Examples ```php $worksheet->setCellValue('A1', 'Year') ->setCellValue('A2', 'Month') ->setCellValue('A3', 'Day'); $worksheet->setCellValue('B1', 2008) ->setCellValue('B2', 12) ->setCellValue('B3', 31); $worksheet->setCellValue('D1', '=DATE(B1,B2,B3)'); $retVal = $worksheet->getCell('D1')->getCalculatedValue(); // $retVal = 1230681600 ``` ```php // We're going to be calling the same cell calculation multiple times, // and expecting different return values, so disable calculation cacheing \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->setCalculationCacheEnabled(FALSE); $saveFormat = \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(); \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATE'], [2008, 12, 31] ); // $retVal = 39813.0 \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_NUMERIC ); $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATE'], [2008, 12, 31] ); // $retVal = 1230681600 \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType($saveFormat); ``` ##### Notes There are no additional notes on this function #### DATEDIF The DATEDIF function computes the difference between two dates in a variety of different intervals, such number of years, months, or days. ##### Syntax DATEDIF(date1, date2 [, unit]) ##### Parameters **date1** First Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **date2** Second Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **unit** The interval type to use for the calculation This is a string, comprising one of the values listed below: Unit | Meaning | Description -----|---------------------------------|-------------------------------- m | Months | Complete calendar months between the dates. d | Days | Number of days between the dates. y | Years | Complete calendar years between the dates. ym | Months Excluding Years | Complete calendar months between the dates as if they were of the same year. yd | Days Excluding Years | Complete calendar days between the dates as if they were of the same year. md | Days Excluding Years And Months | Complete calendar days between the dates as if they were of the same month and same year. The unit value is not case sensitive, and defaults to `d`. ##### Return Value **integer** An integer value that reflects the difference between the two dates. This could be the number of full days, months or years between the two dates, depending on the interval unit value passed into the function as the third parameter. ##### Examples ```php $worksheet->setCellValue('A1', 'Year') ->setCellValue('A2', 'Month') ->setCellValue('A3', 'Day'); $worksheet->setCellValue('B1', 2001) ->setCellValue('C1', 2009) ->setCellValue('B2', 7) ->setCellValue('C2', 12) ->setCellValue('B3', 1) ->setCellValue('C3', 31); $worksheet->setCellValue('D1', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"d")') ->setCellValue('D2', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"m")') ->setCellValue('D3', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"y")') ->setCellValue('D4', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"ym")') ->setCellValue('D5', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"yd")') ->setCellValue('D6', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"md")'); $retVal = $worksheet->getCell('D1')->getCalculatedValue(); // $retVal = 3105 $retVal = $worksheet->getCell('D2')->getCalculatedValue(); // $retVal = 101 $retVal = $worksheet->getCell('D3')->getCalculatedValue(); // $retVal = 8 $retVal = $worksheet->getCell('D4')->getCalculatedValue(); // $retVal = 5 $retVal = $worksheet->getCell('D5')->getCalculatedValue(); // $retVal = 183 $retVal = $worksheet->getCell('D6')->getCalculatedValue(); // $retVal = 30 ``` ```php $date1 = 1193317015; // PHP timestamp for 25-Oct-2007 $date2 = 1449579415; // PHP timestamp for 8-Dec-2015 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEDIF'], [$date1, $date2, 'd'] ); // $retVal = 2966 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEDIF'], [$date1, $date2, 'm'] ); // $retVal = 97 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEDIF'], [$date1, $date2, 'y'] ); // $retVal = 8 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEDIF'], [$date1, $date2, 'ym'] ); // $retVal = 1 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEDIF'], [$date1, $date2, 'yd'] ); // $retVal = 44 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEDIF'], [$date1, $date2, 'md'] ); // $retVal = 13 ``` ##### Notes If Date1 is later than Date2, DATEDIF will return a \#NUM! error. #### DATEVALUE The DATEVALUE function returns the date represented by a date formatted as a text string. Use DATEVALUE to convert a date represented by text to a serial number. ##### Syntax DATEVALUE(dateString) ##### Parameters **date** Date String. A string, representing a date value. ##### Return Value **mixed** A date/time stamp that corresponds to the given date. This could be a PHP timestamp value (integer), a PHP `DateTime` object, or an Excel timestamp value (real), depending on the value of `\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType()`. ##### Examples ```php $worksheet->setCellValue('A1', 'Date String'); ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '31/12/2008') ->setCellValue('A4', '12-31-2008'); $worksheet->setCellValue('B2', '=DATEVALUE(A2)') ->setCellValue('B3', '=DATEVALUE(A3)') ->setCellValue('B4', '=DATEVALUE(A4)'); \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); $retVal = $worksheet->getCell('B3')->getCalculatedValue(); $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 39813.0 for all cases ``` ```php // We're going to be calling the same cell calculation multiple times, // and expecting different return values, so disable calculation cacheing \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->setCalculationCacheEnabled(FALSE); $saveFormat = \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(); \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEVALUE'], ['31-Dec-2008'] ); // $retVal = 39813.0 \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_NUMERIC ); $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DATEVALUE'], ['31-Dec-2008'] ); // $retVal = 1230681600 \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType($saveFormat); ``` ##### Notes DATEVALUE uses the php `DateTime` object implementation of `strtotime()` (which can handle a wider range of formats than the normal `strtotime()` function), and it is also called for any date parameter passed to other date functions (such as DATEDIF) when the parameter value is a string. **WARNING:-** PhpSpreadsheet accepts a wider range of date formats than MS Excel, so it is entirely possible that Excel will return a \#VALUE! error when passed a date string that it can’t interpret, while PhpSpreadsheet is able to translate that same string into a correct date value. Care should be taken in workbooks that use string formatted dates in calculations when writing to Xls or Xlsx. #### DAY The DAY function returns the day of a date. The day is given as an integer ranging from 1 to 31. ##### Syntax DAY(datetime) ##### Parameters **datetime** Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. ##### Return Value **integer** An integer value that reflects the day of the month. This is an integer ranging from 1 to 31. ##### Examples ```php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '14-Feb-2008'); $worksheet->setCellValue('B2', '=DAY(A2)') ->setCellValue('B3', '=DAY(A3)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 31 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 14 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DAYOFMONTH'], ['25-Dec-2008'] ); // $retVal = 25 ``` ##### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::DAYOFMONTH()` when the method is called statically. #### DAYS360 The DAYS360 function computes the difference between two dates based on a 360 day year (12 equal periods of 30 days each) used by some accounting systems. ##### Syntax DAYS360(date1, date2 [, method]) #### Parameters **date1** First Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **date2** Second Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **method** A boolean flag (TRUE or FALSE) This is a flag that determines which method to use in the calculation, based on the values listed below: method | Description -------|------------ FALSE | U.S. (NASD) method. If the starting date is the last day of a month, it becomes equal to the 30th of the same month. If the ending date is the last day of a month and the starting date is earlier than the 30th of a month, the ending date becomes equal to the 1st of the next month; otherwise the ending date becomes equal to the 30th of the same month. TRUE | European method. Starting dates and ending dates that occur on the 31st of a month become equal to the 30th of the same month. The method value defaults to FALSE. ##### Return Value **integer** An integer value that reflects the difference between the two dates. This is the number of full days between the two dates, based on a 360 day year. ##### Examples ```php $worksheet->setCellValue('B1', 'Start Date') ->setCellValue('C1', 'End Date') ->setCellValue('A2', 'Year') ->setCellValue('A3', 'Month') ->setCellValue('A4', 'Day'); $worksheet->setCellValue('B2', 2003) ->setCellValue('B3', 2) ->setCellValue('B4', 3); $worksheet->setCellValue('C2', 2007) ->setCellValue('C3', 5) ->setCellValue('C4', 31); $worksheet->setCellValue('E2', '=DAYS360(DATE(B2,B3,B4),DATE(C2,C3,C4))') ->setCellValue('E4', '=DAYS360(DATE(B2,B3,B4),DATE(C2,C3,C4),FALSE)'); $retVal = $worksheet->getCell('E2')->getCalculatedValue(); // $retVal = 1558 $retVal = $worksheet->getCell('E4')->getCalculatedValue(); // $retVal = 1557 ``` ```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 ``` ##### Notes **WARNING:-** This function does not currently work with the Xls Writer when a PHP Boolean is used for the third (optional) parameter (as shown in the example above), and the writer will generate and error. It will work if a numeric 0 or 1 is used for the method parameter; or if the Excel `TRUE()` and `FALSE()` functions are used instead. #### EDATE The EDATE function returns an Excel timestamp or a PHP timestamp or `DateTime` object representing the date that is the indicated number of months before or after a specified date (the start\_date). Use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue. ##### Syntax EDATE(baseDate, months) ##### Parameters **baseDate** Start Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **months** Number of months to add. An integer value indicating the number of months before or after baseDate. A positive value for months yields a future date; a negative value yields a past date. ##### Return Value **mixed** A date/time stamp that corresponds to the basedate + months. This could be a PHP timestamp value (integer), a PHP `DateTime` object, or an Excel timestamp value (real), depending on the value of `\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType()`. ##### Examples ```php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '1-Jan-2008') ->setCellValue('A3', '29-Feb-2008'); $worksheet->setCellValue('B2', '=EDATE(A2,5)') ->setCellValue('B3', '=EDATE(A3,-12)'); \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 39600.0 (1-Jun-2008) $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 39141.0 (28-Feb-2007) ``` ```php \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'EDATE'], ['31-Oct-2008', 25] ); // $retVal = 40512.0 (30-Nov-2010) ``` ###### Notes **WARNING:-** This function is currently not supported by the Xls Writer because it is not a standard function within Excel 5, but an add-in from the Analysis ToolPak. #### EOMONTH The EOMONTH function returns an Excel timestamp or a PHP timestamp or `DateTime` object representing the date of the last day of the month that is the indicated number of months before or after a specified date (the start\_date). Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. ##### Syntax EOMONTH(baseDate, months) ##### Parameters **baseDate** Start Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **months** Number of months to add. An integer value indicating the number of months before or after baseDate. A positive value for months yields a future date; a negative value yields a past date. ##### Return Value **mixed** A date/time stamp that corresponds to the last day of basedate + months. This could be a PHP timestamp value (integer), a PHP `DateTime` object, or an Excel timestamp value (real), depending on the value of `\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType()`. ##### Examples ```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) ``` ##### Notes **WARNING:-** This function is currently not supported by the Xls Writer because it is not a standard function within Excel 5, but an add-in from the Analysis ToolPak. #### HOUR 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. ##### Examples ```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:20 PM'); $worksheet->setCellValue('B2', '=HOUR(A2)') ->setCellValue('B3', '=HOUR(A3)') ->setCellValue('B4', '=HOUR(A4)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 17 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 4 $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 16 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'HOUROFDAY'], ['09:30'] ); // $retVal = 9 ``` ##### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::HOUROFDAY()` when the method is called statically. #### MINUTE The MINUTE function returns the minutes of a time value. The minute is given as an integer, ranging from 0 to 59. ##### Syntax MINUTE(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 minutes within the hour. This is an integer ranging from 0 to 59. ##### Examples ```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 ``` ##### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::MINUTE()` when the method is called statically. #### MONTH The MONTH function returns the month of a date. The month is given as an integer ranging from 1 to 12. ##### Syntax MONTH(datetime) ##### Parameters **datetime** Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. ##### Return Value **integer** An integer value that reflects the month of the year. This is an integer ranging from 1 to 12. ##### Examples ```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 ``` #### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::MONTHOFYEAR()` when the method is called statically. #### NETWORKDAYS The NETWORKDAYS function returns the number of whole working days between a *start date* and an *end date*. Working days exclude weekends and any dates identified in *holidays*. Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days worked during a specific term. ##### Syntax NETWORKDAYS(startDate, endDate [, holidays]) ##### Parameters **startDate** Start Date of the period. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **endDate** End Date of the period. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **holidays** Optional array of Holiday dates. An optional range of one or more dates to exclude from the working calendar, such as state and federal holidays and floating holidays. The list can be either a range of cells that contains the dates or an array constant of Excel date values, PHP date timestamps, PHP date objects, or dates represented as strings. ##### Return Value **integer** Number of working days. The number of working days between startDate and endDate. ##### Examples ```php ``` ```php ``` ##### Notes There are no additional notes on this function #### NOW The NOW function returns the current date and time. ##### Syntax NOW() ##### Parameters There are no parameters for the `NOW()` function. ##### Return Value **mixed** A date/time stamp that corresponds to the current date and time. This could be a PHP timestamp value (integer), a PHP `DateTime` object, or an Excel timestamp value (real), depending on the value of `\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType()`. ##### Examples ```php ``` ```php ``` ##### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::DATETIMENOW()` when the method is called statically. #### SECOND The SECOND function returns the seconds of a time value. The second is given as an integer, ranging from 0 to 59. ##### Syntax SECOND(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 seconds within the minute. This is an integer ranging from 0 to 59. ##### Examples ```php $worksheet->setCellValue('A1', 'Time String') ->setCellValue('A2', '31-Dec-2008 17:30:20') ->setCellValue('A3', '14-Feb-2008 4:20 AM') ->setCellValue('A4', '14-Feb-2008 4:45:59 PM'); $worksheet->setCellValue('B2', '=SECOND(A2)') ->setCellValue('B3', '=SECOND(A3)'); ->setCellValue('B4', '=SECOND(A4)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 20 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 0 $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 59 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'SECOND'], ['09:30:17'] ); // $retVal = 17 ``` ##### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::SECOND()` when the method is called statically. #### TIME Not yet documented. #### TIMEVALUE Not yet documented. #### TODAY Not yet documented. #### WEEKDAY The WEEKDAY function returns the day of the week for a given date. The day is given as an integer ranging from 1 to 7, although this can be modified to return a value between 0 and 6. ##### Syntax WEEKDAY(datetime [, method]) ##### Parameters **datetime** Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. **method** An integer flag (values 0, 1 or 2) This is a flag that determines which method to use in the calculation, based on the values listed below: method | Description :-----:|------------------------------------------ 0 | Returns 1 (Sunday) through 7 (Saturday). 1 | Returns 1 (Monday) through 7 (Sunday). 2 | Returns 0 (Monday) through 6 (Sunday). The method value defaults to 1. ##### Return Value **integer** An integer value that reflects the day of the week. This is an integer ranging from 1 to 7, or 0 to 6, depending on the value of method. ##### Examples ```php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '14-Feb-2008'); $worksheet->setCellValue('B2', '=WEEKDAY(A2)') ->setCellValue('B3', '=WEEKDAY(A3,0)') ->setCellValue('B4', '=WEEKDAY(A3,2)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 12 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 2 $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 2 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'WEEKDAY'], ['14-July-2008'] ); // $retVal = 7 ``` ##### Notes Note that the PhpSpreadsheet function is `\PhpOffice\PhpSpreadsheet\Calculation\Functions::WEEKDAY()` when the method is called statically. #### WEEKNUM Not yet documented. #### WORKDAY Not yet documented. #### YEAR The YEAR function returns the year of a date. ##### Syntax YEAR(datetime) ##### Parameters **datetime** Date. An Excel date value, PHP date timestamp, PHP `DateTime` object, or a date represented as a string. ##### Return Value **integer** An integer value that reflects the month of the year. This is an integer year value. ##### Examples ```php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '17-Jul-1982') ->setCellValue('A3', '16-Apr-2009'); $worksheet->setCellValue('B2', '=YEAR(A2)') ->setCellValue('B3', '=YEAR(A3)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 1982 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 2009 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'YEAR'], ['14-July-2001'] ); // $retVal = 2001 ``` ##### Notes There are no additional notes on this function ### YEARFRAC Not yet documented. ================================================ FILE: docs/topics/conditional-formatting.md ================================================ # Conditional Formatting ## Introduction In addition to standard cell formatting options, most spreadsheet software provides an option known as Conditional Formatting, which allows formatting options to be set based on the value of a cell. The cell's standard formatting defines most style elements that will always be applied, such as the font face and size; but Conditional Formatting allows you to override some elements of that cell style such as number format mask; font colour, bold, italic and underlining; borders; and fill colour and pattern. Conditional Formatting can be applied to individual cells, or to a range of cells. ### Example As a simple example in MS Excel itself, if we wanted to highlight all cells in the range A1:A10 that contain values greater than 80, start by selecting the range of cells. ![11-01-CF-Simple-Select-Range.png](./images/11-01-CF-Simple-Select-Range.png) On the Home tab, in the "Styles" group, click "Conditional Formatting". This allows us to select an Excel Wizard to guide us through the process of creating a Conditional Rule and defining a Style for that rule. ![11-02-CF-Simple-Tab.png](./images/11-02-CF-Simple-Tab.png) Click "Highlight Cells Rules", then "Greater Than". ![11-03-CF-Simple-CellIs-GreaterThan.png](./images/11-03-CF-Simple-CellIs-GreaterThan.png) Enter the value "80" in the prompt box; and either select one of the pre-defined formatting style (or create a custom style from there). ![11-04-CF-Simple-CellIs-Value-and-Style.png](./images/11-04-CF-Simple-CellIs-Value-and-Style.png) Then click "OK". The rule is immediately applied to the selected range of cells, highlighting all those with a value greater than 80 in the chosen style. ![11-05-CF-Simple-CellIs-Highlighted.png](./images/11-05-CF-Simple-CellIs-Highlighted.png) Any change to the value of a cell within that range will immediately check the rule, and automatically apply the new styling if it applies. ![11-06-CF-Simple-Cell-Value-Change.png](./images/11-06-CF-Simple-Cell-Value-Change.png) If we wanted to set up the same Conditional Formatting rule in PHPSpreadsheet, we would do so using the following code: ```php $conditional = new \PhpOffice\PhpSpreadsheet\Style\Conditional(); $conditional->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS); $conditional->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_GREATERTHAN); $conditional->addCondition(80); $conditional->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN); $conditional->getStyle()->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID); $conditional->getStyle()->getFill()->getStartColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_GREEN); $conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('A1:A10')->getConditionalStyles(); $conditionalStyles[] = $conditional; $spreadsheet->getActiveSheet()->getStyle('A1:A10')->setConditionalStyles($conditionalStyles); ``` Depending on the Rules that we might want to apply for a Condition, sometimes an "operator Type" is required, sometimes not (and not all Operator Types are appropriate for all Condition Types); sometimes a "Condition" is required (or even several conditions), sometimes not, and sometimes it must be a specific Excel formula expression. Creating conditions manually requires a good knowledge of when these different properties need to be set, and with what type of values. This isn't something that an end-user developer should be expected to know. So - to eliminate this need for complex and arcane knowledge - since PHPSpreadsheet verson 1.22.0 there is also a series of Wizards that can assist with creating Conditional Formatting rules, and which are capable of setting the appropriate operators and conditions (including the sometimes complex Excel formula expressions) for a Conditional Rule: ```php $wizardFactory = new \PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard('A1:A10'); $wizard = $wizardFactory->newRule(\PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard::CELL_VALUE); $wizard->greaterThan(80); $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(); ``` The Wizards know which operator types match up with condition types, and provide more meaningful method names for operators, and they build expressions and formulae when required; and also work well with an IDE such as PHPStorm. --- Note that `$conditionalStyles` is an array: it is possible to apply several conditions to the same range of cells. If we also wanted to highlight values that were less than 10 in the A1:A10 range, we can add a second style rule. In Excel, we would do this by selecting the range again, and going through the same process, this time selecting the "Highlight Cells Rules", then "Less Than" from the "Conditional Styles" menu, entering the value "10" in the prompt box, and selecting the appropriate style. In PHPSpreadsheet, we would do: ```php $conditional2 = new \PhpOffice\PhpSpreadsheet\Style\Conditional(); $conditional2->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS); $conditional2->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN); $conditional2->addCondition(10); $conditional2->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKRED); $conditional2->getStyle()->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID); $conditional2->getStyle()->getFill()->getStartColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED); $conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('A1:A10')->getConditionalStyles(); $conditionalStyles[] = $conditional2; $spreadsheet->getActiveSheet()->getStyle('A1:A10')->setConditionalStyles($conditionalStyles); ``` or again, using the Wizard: ```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(); ``` ### Order of Evaluating Multiple Rules/Conditions `$conditionalStyles` is an array, which not only represents multiple conditions that can be applied to a cell (or range of cells), but also the order in which they are checked. Some spreadsheet programs stop processing conditions once they find a match. On the other hand, MS Excel will check each of those conditions in turn in the order they are defined. It will stop checking only if it finds a matching rule that specifies 'stop if true'; however, if it finds conflicting matches with conflicting formatting (e.g. both set a background fill color but use different choices), the first match wins. In either case, this means that the order of checking conditions can be important. Consider the following. We have one condition that checks if a cell value is between -2 and 2, styling the fill color of the cell in yellow if that condition matches; and a second condition that checks if the cell value is equal to 0, styling the fill color of the cell in red if that matches. - Yellow if value is between -2 and 2 - Red if value equals 0 If they are evaluated in the order I've described above, and the cell has a value of 0, then the first rule will match (because 0 is between -2 and 2), and the cell will be styled in yellow, and no further conditions will be checked. So the rule that styles the cell in red if the value is 0 will never be assessed, even though that would also match (and is probably what we actually wanted, otherwise why have an explicit rule defined for that condition). ![11-20-CF-Rule-Order-1.png](./images/11-20-CF-Rule-Order-1.png) If the rule order is reversed - Red if value equals 0 - Yellow if value is between -2 and 2 then the cell containing the value 0 will be rendered in red, because that is the first matching condition; and the formatting in the other condition conflicts with this, so is discarded. ![11-21-CF-Rule-Order-2.png](./images/11-21-CF-Rule-Order-2.png) So when you have multiple conditions where the rules might "overlap", the order of these is important. If the cell matches multiple conditions, Excel (but not most other spreadsheet programs) will apply non-conflicting styles from each match. So, for the example above, if we wanted a match of 0 to have a different *font* color rather than a different *fill* color, Excel can honor both. ![11-21-CF-Rule-Order-2.pic2.png](./images/11-21-CF-Rule-Order-2.pic2.png) Here is the same spreadsheet opened in LibreOffice - cell A4 has only the first conditional style applied to it. (You would see the same if you checked 'Stop if True' in Excel.) If you want the spreadsheet to appear the same in both Excel and LibreOffice, you would need to use more complicated conditions. ![11-21-CF-Rule-Order-2.pic2.png](./images/11-21-CF-Rule-Order-2.pic3.png) PhpSpreadsheet supports the setting of [Stop If True](#stop-if-true-and-no-format-set). ### Reader/Writer Support Currently, the following Conditional Types are supported for the following Readers and Writers: MS Excel | Conditional Type | Readers | Writers ---|---|---|--- | Cell Value | Conditional::CONDITION_CELLIS | Xlsx | Xlsx, Xls, Html Specific Text | Conditional::CONDITION_CONTAINSTEXT | Xlsx | Xlsx, Html | Conditional::CONDITION_NOTCONTAINSTEXT | Xlsx | Xlsx, Html | Conditional::CONDITION_BEGINSWITH | Xlsx | Xlsx, Html | Conditional::CONDITION_ENDSWITH | Xlsx | Xlsx, Html Dates Occurring | Conditional::CONDITION_TIMEPERIOD | Xlsx | Xlsx, Html Blanks | Conditional::CONDITION_CONTAINSBLANKS | Xlsx | Xlsx, Html No Blanks | Conditional::CONDITION_NOTCONTAINSBLANKS | Xlsx | Xlsx, Html Errors | Conditional::CONDITION_CONTAINSERRORS | Xlsx | Xlsx, Html No Errors | Conditional::CONDITION_NOTCONTAINSERRORS | Xlsx | Xlsx, Html Duplicates/Unique | Conditional::CONDITION_DUPLICATES | Xlsx | Xlsx, Html | Conditional::CONDITION_UNIQUE | Xlsx | Xlsx, Html Use a formula | Conditional::CONDITION_EXPRESSION | Xlsx | Xlsx, Xls, Html Data Bars | Conditional::CONDITION_DATABAR | Xlsx | Xlsx, Html Colour Scales | Conditional::COLORSCALE | Xlsx | Html To enable conditional formatting for Html writer, use: ```php $writer = new HtmlWriter($spreadsheet); $writer->setConditionalFormatting(true); ``` The following Conditional Types are currently not supported by any Readers or Writers: MS Excel | Conditional Type ---|--- Above/Below Average | ? Top/Bottom Items | ? Top/Bottom %age | ? Icon Sets | ? Unsupported types will by ignored by the Readers, and cannot be created through PHPSpreadsheet. ## Wizards While the Wizards don't simplify defining the Conditional Style itself; they do make it easier to define the conditions (the rules) where that style will be applied. MS Excel itself has wizards to guide the creation of Conditional Formatting rules and styles. ![11-07-CF-Wizard.png](./images/11-07-CF-Wizard.png) The Wizard Factory allows us to retrieve the appropriate Wizard for the CF Rule that we want to apply. Most of those that have already been defined fall under the "Format only cells that contain" category. MS Excel provides a whole series of different types of rule, each of which has it's own formatting and logic. The Wizards try to replicate this logic and behaviour, similar to Excel's own "Formatting Rule" helper wizard. MS Excel | Wizard Factory newRule() Type Constant | Wizard Class Name ---|---|--- Cell Value | Wizard::CELL_VALUE | CellValue Specific Text | Wizard::TEXT_VALUE | TextValue Dates Occurring | Wizard::DATES_OCCURRING | DateValue Blanks | Wizard::BLANKS | Blanks No Blanks | Wizard::NOT_BLANKS | Blanks Errors | Wizard::ERRORS | Errors No Errors | Wizard::NOT_ERRORS | Errors Additionally, Wizards also exists for "Format only unique or duplicate values", and for "Use a formula to determine which cells to format": MS Excel | Wizard Factory newRule() Type Constant | Wizard Class Name ---|---|--- Duplicates/Unique | Wizard::DUPLICATES or Wizard::UNIQUE | Duplicates Use a formula | Wizard::EXPRESSION or Wizard::FORMULA | Expression There is currently no Wizard for Data Bars, even though this Conditional Type is supported by the Xlsx Reader and Writer. --- We instantiate the Wizard Factory, passing in the cell range where we want to apply Conditional Formatting rules; and can then call the `newRule()` method, passing in the type of Conditional Rule that we want to create in order to return the appropriate Wizard: ```php $wizardFactory = new \PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard('C3:E5'); $wizard = $wizardFactory->newRule(\PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard::CELL_VALUE); ``` You can, of course, instantiate the Wizard that you want directly, rather than using the factory; but still remember to pass in the cell range. ```php $wizard = new \PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard\CellValue('C3:E5'); ``` That Wizard then provides methods allowing us to define the rule, setting the operator and the values that we want to compare for that rule. Note that not all rules require values, or even operators, but the individual Wizards provide whatever is necessary; and this document lists all options available for every Wizard. Once we have used the Wizard to define the conditions and values that we want; and have defined a style using the `setStyle()` method, then we call the Wizard's `getConditional()` method to return a Conditional object that can be added to the array of Conditional Styles that we pass to `setConditionalStyles()`. ### CellValue Wizard For the `CellValue` Wizard, we always need to provide an operator and a value; and for the "between" and "notBetween" operators, we need to provide two values to specify a range. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_CELLIS | Wizard::CELL_VALUE | Conditional::OPERATOR_EQUAL | equals() | | Conditional::OPERATOR_NOTEQUAL | notEquals() | | Conditional::OPERATOR_GREATERTHAN | greaterThan() | | Conditional::OPERATOR_GREATERTHANOREQUAL | greaterThanOrEqual() | | Conditional::OPERATOR_LESSTHAN | lessThan() | | Conditional::OPERATOR_LESSTHANOREQUAL | lessThanOrEqual() | | Conditional::OPERATOR_BETWEEN | between() | | Conditional::OPERATOR_NOTBETWEEN | notBetween() | | | and() | Used to provide the second operand for `between()` and `notBetween() A single operator call is required for every rule (except `between()` and `notBetween`, where the Wizard also provides `and()`); and providing a value is mandatory for all operators. The values that we need to provide for each operator can be numeric, boolean or string literals (even NULL); cell references; or formulae. So to set the rule using an operator, we would make a call like: ```php $wizard->lessThan(10); ``` or when setting a `between()` or `notBetween()` rule, we can make use of the fluent interface with the `and()` method to set the range of values: ```php $wizard->between(-10)->and(10); ``` Providing a second value using `and()` is mandatory for a `between()` or `notBetween()` range. To retrieve the Conditional, to add it to our `$conditionalStyles` array, we call the Wizard's `getConditional()` method. ```php $conditional = $wizard->getConditional(); $conditionalStyles = [$conditional]; ``` or simply ```php $conditionalStyles[] = $wizard->getConditional(); ``` Putting it all together, we can use a block of code like (using pre-defined Style objects): ```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); ``` You can find an example that demonstrates this in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/01_Basic_Comparisons.php#L81 "Conditional Formatting - Simple Example") for the repo. ![11-12-CF-Simple-Example.png](./images/11-12-CF-Simple-Example.png) #### Value Types When we need to provide a value for an operator, that value can be numeric, boolean or string literals (even NULL); cell references; or even an Excel formulae. ##### Literals If the value is a literal (even a string literal), we simply need to pass the value; the Wizard will ensure that strings are correctly quoted when we get the Conditional from the Wizard. ```php $wizard->equals('Hello World'); ``` If you weren't using the Wizard, but were creating the Conditional directly, you would need to remember to wrap this value in quotes yourself (`'"Hello World"'`) However, a cell reference or a formula are also string data, so we need to tell the Wizard if the value that we are passing in isn't just a string literal value, but should be treated as a cell reference or as a formula. ##### Cell References If we want to use the value from cell `H9` in our rule; then we need to pass a value type of `VALUE_TYPE_CELL` to the operator, in addition to the cell reference itself. ```php $wizard->equals('$H$9', Wizard::VALUE_TYPE_CELL); ``` ![11-08-CF-Absolute-Cell-Reference.png](./images/11-08-CF-Absolute-Cell-Reference.png) You can find an example that demonstrates this in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/01_Basic_Comparisons.php#L103 "Conditional Formatting - Basic Comparisons") for the repo. Note that we are passing the cell as an absolute cell reference, "pinned" (with the `$` symbol) for both the row and the column. In this next example, we need to use relative cell references, so that the comparison will match the value in column `A` against the values in columns `B` and `C` for each row in our range (`A18:A20`); ie, test if the value in `A18` is between the values in `B18` and `C18`, test if the value in `A19` is between the values in `B19` and `C19`, etc. ![11-09-CF-Relative-Cell-Reference.png](./images/11-09-CF-Relative-Cell-Reference.png) ```php $wizard->between('$B1', Wizard::VALUE_TYPE_CELL) ->and('$C1', Wizard::VALUE_TYPE_CELL) ->setStyle($greenStyle); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/01_Basic_Comparisons.php#L126 "Conditional Formatting - Basic Comparisons") for the repo. In this case, we "pin" the column for the address; but leave the row "unpinned". Notice also that we treat the first cell in our range as cell `A1`: the relative row number will be adjusted automatically to match our defined range; that is, the range that we specified when we instantiated the Wizard (passed in through the Wizard Factory) when we make the call to `getConditional()`. ##### Formulae It is also possible to set the value/operand as an Excel formula expression, not simply a literal value or a cell reference. Again, we do need to specify that the value is a Formula. ```php $cellRange = 'C26:C28'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->equals('CONCATENATE($A1," ",$B1)', Wizard::VALUE_TYPE_FORMULA) ->setStyle($yellowStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` You can find an example that demonstrates this in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/02_Text_Comparisons.php#L209 "Conditional Formatting - Text Comparisons") for the repo. When the formula contains cell references, we again need to be careful with pinning to absolute columns/rows; and when unpinned, we reference based on the top-left cell of the range being cell `A1` when we define the formula. Here we're defining the formula as `CONCATENATE($A1," ",$B1)`, so we're "pinning" the column references for columns `A` and `B`; but leaving the row unpinned (explicitly set to start from row 1), which is then adjusted to the conditional range when we get the Conditional from the Wizard, and adjusted to the individual rows within that range when MS Excel displays the results. ![11-13-CF-Formula-with-Relative-Cell-Reference.png](./images/11-13-CF-Formula-with-Relative-Cell-Reference.png) ### TextValue Wizard While we can use the `CellValue` Wizard to do basic string comparison rules, the `TextValue` Wizard provides rules for comparing parts of a string value. For the `TextValue` Wizard, we always need to provide an operator and a value. As with the `CellValue` Wizard, values can be literals (but should always be string literals), cell references, or formula. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_CONTAINSTEXT | Wizard::TEXT_VALUE | Conditional::OPERATOR_CONTAINSTEXT | contains() Conditional::CONDITION_NOTCONTAINSTEXT | Wizard::TEXT_VALUE | Conditional::OPERATOR_NOTCONTAINS | doesNotContain() | | | doesntContain() | synonym for `doesNotContain()` Conditional::CONDITION_BEGINSWITH | Wizard::TEXT_VALUE | Conditional::OPERATOR_BEGINSWITH | beginsWith() | | | startsWith() | synonym for `beginsWith()` Conditional::CONDITION_ENDSWITH | Wizard::TEXT_VALUE | Conditional::OPERATOR_ENDSWITH | endsWith() The Conditional actually uses a separate "Condition Type" for each option, each with its own "Operator Type", and the condition should be an Excel formula (not simply the string value to check), and with a custom `text` attribute. The Wizard should make it a lot easier to create these conditional rules. To create a Conditional rule manually, you would need to do something like: ```php $cellRange = 'A14:B16'; $conditionalStyles = []; $conditional = new Conditional(); // Remember to use the correct Condition Type $conditional->setConditionType(Conditional::CONDITION_CONTAINSTEXT); // Remember to use the correct Operator Type $conditional->setOperatorType(Conditional::OPERATOR_CONTAINSTEXT); // Remember to set the text attribute // Remember to wrap the string literal $conditional->setText('"LL"'); // Remember that the condition should be the first element in an array // Remember that we need a specific formula for this Conditional // Remember to wrap the string literal // Remember to use the top-left cell of the range that we want to apply this rule to $conditional->setConditions(['NOT(ISERROR(SEARCH("LL",A14)))']); $conditional->setStyle($greenStyle); $conditionalStyles[] $spreadsheet->getActiveSheet() ->getStyle($cellRange) ->setConditionalStyles($conditionalStyles); ``` But using the Wizard, the same Conditional rule can be created by: ```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); ``` You can find an example that demonstrates this in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/02_Text_Comparisons.php#L149 "Conditional Formatting - Text Comparisons") for the repo. ![11-17-CF-Text-Contains.png](./images/11-17-CF-Text-Contains.png) There are also examples in that file for `notContains()`, `beginsWith()` and `endsWith()` comparisons; using literal text, and with cell references. The actual Excel Expressions used (and that you would need to set manually if you were defining the Conditional yourself rather than using the Wizard) are listed below: Conditional Type | Condition Expression ---|--- Conditional::CONDITION_CONTAINSTEXT | NOT(ISERROR(SEARCH(``,``))) Conditional::CONDITION_NOTCONTAINSTEXT | ISERROR(SEARCH(``,``))`,LEN(``))=`` Conditional::CONDITION_ENDSWITH | RIGHT(``,LEN(``))=`` The `` always references the top-left cell in the range of cells for this Conditional Formatting Rule. The `` should be wrapped in double quotes (`"`) for string literals; but unquoted if it is a value stored in a cell reference, or a formula. The `TextValue` Wizard handles defining these expressions for you. As with the operand for the `CellValue` Wizard, you can specify the value passed to `contains()`, `doesNotContain()`, `beginsWith()` and `endsWith()` as a cell reference, or as a formula; and if you do so, then you need to pass a second argument to those methods specifying `Wizard::VALUE_TYPE_CELL` or `Wizard::VALUE_TYPE_FORMULA`. The same rules also apply to "pinning" cell references as described above for the `CellValue` Wizard. ```php $textWizard->beginsWith('$D$1', Wizard::VALUE_TYPE_CELL) ->setStyle($yellowStyle); ``` ### DateValue Wizard For the `DateValue` Wizard, we always need to provide an operator; but no value is required. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_TIMEPERIOD | Wizard::DATES_OCCURRING | Conditional::TIMEPERIOD_TODAY | today() | | Conditional::TIMEPERIOD_YESTERDAY | yesterday() | | Conditional::TIMEPERIOD_TOMORROW | tomorrow() | | Conditional::TIMEPERIOD_LAST_7_DAYS | last7Days() | | | lastSevenDays() | synonym for `last7Days()` | | Conditional::TIMEPERIOD_LAST_WEEK | lastWeek() | | Conditional::TIMEPERIOD_THIS_WEEK | thisWeek() | | Conditional::TIMEPERIOD_NEXT_WEEK | nextWeek() | | Conditional::TIMEPERIOD_LAST_MONTH | lastMonth() | | Conditional::TIMEPERIOD_THIS_MONTH | thisMonth() | | Conditional::TIMEPERIOD_NEXT_MONTH | nextMonth() The Conditional has no actual "Operator Type", and the condition/value should be an Excel formula, and with a custom `timePeriod` attribute. The Wizard should make it a lot easier to create these condition rules. ![11-18-CF-Date-Occurring-Examples.png](./images/11-18-CF-Date-Occurring-Examples.png) The above image shows a grid that demonstrate each of the possible Date Occurring rules, and was generated using [the code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/05_Date_Comparisons.php#L118 "Conditional Formatting - Dates Occurring Comparisons") Typical sample code wod look something like: ```php $wizardFactory = new Wizard("E2:E19"); /** @var Wizard\DateValue $dateWizard */ $dateWizard = $wizardFactory->newRule(Wizard::DATES_OCCURRING); $conditionalStyles = []; $dateWizard->last7Days() ->setStyle($yellowStyle); $conditionalStyles[] = $dateWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($dateWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` The actual Excel Expressions used (and that you would need to set manually if you were defining the Conditional yourself rather than using the Wizard) are listed below: timePeriod Attribute | Condition Expression ---|--- today | FLOOR(``,1)=TODAY()-1 yesterday | FLOOR(``,1)=TODAY() tomorrow | FLOOR(``,1)=TODAY()+1 last7Days | AND(TODAY()-FLOOR(``,1)<=6,FLOOR(``,1)<=TODAY()) lastWeek | AND(TODAY()-ROUNDDOWN(``,0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(``,0)<(WEEKDAY(TODAY())+7)) thisWeek | AND(TODAY()-ROUNDDOWN(``,0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(``,0)-TODAY()<=7-WEEKDAY(TODAY())) nextWeek | AND(ROUNDDOWN(``,0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(``,0)-TODAY()<(15-WEEKDAY(TODAY()))) lastMonth | AND(MONTH(``)=MONTH(EDATE(TODAY(),0-1)),YEAR(``)=YEAR(EDATE(TODAY(),0-1))) thisMonth | AND(MONTH(``)=MONTH(TODAY()),YEAR(``)=YEAR(TODAY())) nextMonth | AND(MONTH(``)=MONTH(EDATE(TODAY(),0+1)),YEAR(``)=YEAR(EDATE(TODAY(),0+1))) The `` always references the top-left cell in the range of cells for this Conditional Formatting Rule. ### Blanks Wizard This Wizard is used to define a simple boolean state rule, to determine whether a cell is blank or not blank. Whether created using the Wizard Factory with a rule type of `Wizard::BLANKS` or `Wizard::NOT_BLANKS`, the same `Blanks` Wizard is returned. The only difference is that in the one case the rule state is pre-set for `CONDITION_CONTAINSBLANKS`, in the other it is pre-set for `CONDITION_NOTCONTAINSBLANKS`. However, you can switch between the two rules using the `isBlank()` and `notBlank()` methods; and it is only at the point when you call `getConditional()` that a Conditional will be returned based on the current state of the Wizard. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_CONTAINSBLANKS | Wizard::BLANKS | - | isBlank() | Default state | | | notBlank() | | | isEmpty() | Synonym for `isBlank()` | | | notEmpty() | Synonym for `notBlank()` Conditional::CONDITION_NOTCONTAINSBLANKS | Wizard::NOT_BLANKS | - | notBlank()| Default state | | | isBlank() | | | isEmpty() | Synonym for `isBlank()` | | | notEmpty() | Synonym for `notBlank()` The following code shows the same Blanks Wizard being used to create both Blank and Non-Blank Conditionals, using a pre-defined `$redStyle` Style object for Blanks, and a pre-defined `$greenStyle` Style object for Non-Blanks. ```php $cellRange = 'A2:B3'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Blanks $blanksWizard */ $blanksWizard = $wizardFactory->newRule(Wizard::BLANKS); $blanksWizard->setStyle($redStyle); $conditionalStyles[] = $blanksWizard->getConditional(); $blanksWizard->notBlank() ->setStyle($greenStyle); $conditionalStyles[] = $blanksWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($blanksWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/03_Blank_Comparisons.php#L58 "Conditional Formatting - Blank Comparisons") for the repo. ![11-10-CF-Blanks-Example.png](./images/11-10-CF-Blanks-Example.png) No operand/value is required for the Blanks Wizard methods; but the Conditional that is returned contains a defined expression with an Excel formula: Blanks Type | Condition Expression ---|--- isBlank() | LEN(TRIM(``))=0 notBlank() | LEN(TRIM(``))>0 The `` always references the top-left cell in the range of cells for this Conditional Formatting Rule. ### Errors Wizard Like the `Blanks` Wizard, this Wizard is used to define a simple boolean state rule, to determine whether a cell with a formula value results in an error or not. Whether created using the Wizard Factory with a rule type of `Wizard::ERRORS` or `Wizard::NOT_ERRORS`, the same `Errors` Wizard is returned. The only difference is that in the one case the rule state is pre-set for `CONDITION_CONTAINSERRORS`, in the other it is pre-set for `CONDITION_NOTCONTAINSERRORS`. However, you can switch between the two rules using the `isError()` and `notError()` methods; and it is only at the point when you call `getConditional()` that a Conditional will be returned based on the current state of the Wizard. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_CONTAINSERRORS | Wizard::ERRORS | - | isError() | Default state | | | notError() Conditional::CONDITION_NOTCONTAINSERRORS | Wizard::NOT_ERRORS | - | notError()| Default state | | | isError() The following code shows the same Errors Wizard being used to create both Error and Non-Error Conditionals, using a pre-defined `$redStyle` Style object for Errors, and a pre-defined `$greenStyle` Style object for Non-Errors. ```php $cellRange = 'C2:C6'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Errors $errorsWizard */ $errorsWizard = $wizardFactory->newRule(Wizard::ERRORS); $errorsWizard->setStyle($redStyle); $conditionalStyles[] = $errorsWizard->getConditional(); $errorsWizard->notError() ->setStyle($greenStyle); $conditionalStyles[] = $errorsWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($errorsWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/04_Error_Comparisons.php#L62 "Conditional Formatting - Error Comparisons") for the repo. ![11-11-CF-Errors-Example.png](./images/11-11-CF-Errors-Example.png) No operand/value is required for the Errors Wizard methods; but the Conditional that is returned contains a defined expression with an Excel formula: Blanks Type | Condition Expression ---|--- isError() | ISERROR(``) notError() | NOT(ISERROR(``)) The `` always references the top-left cell in the range of cells for this Conditional Formatting Rule. ### Duplicates/Unique Wizard This Wizard is used to define a simple boolean state rule, to determine whether a cell value matches any other cells with the same value within the conditional cell range, or if the value is unique in that range of cells. It only has any meaning if it is applied to a range of cells, not to an individual cell. Whether created using the Wizard Factory with a rule type of `Wizard::DUPLICATES` or `Wizard::UNIQUE`, the same `Duplicates` Wizard is returned. The only difference is that in the one case the rule state is pre-set for `CONDITION_DUPLICATES`, in the other it is pre-set for `CONDITION_UNIQUE`. However, you can switch between the two rules using the `duplicates()` and `unique()` methods; and it is only at the point when you call `getConditional()` that a Conditional will be returned based on the current state of the Wizard. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_DUPLICATES | Wizard::DUPLICATES | - | duplicates() | Default state | | | unique() Conditional::CONDITION_UNIQUE | Wizard::UNIQUE | - | unique()| Default state | | | duplicates() The following code shows the same Duplicates Wizard being used to create both Blank and Non-Blank Conditionals, using a pre-defined `$redStyle` Style object for Blanks, and a pre-defined `$greenStyle` Style object for Non-Blanks. ```php $cellRange = 'A2:E6'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Duplicats $duplicatesWizard */ $duplicatesWizard = $wizardFactory->newRule(Wizard::DUPLICATES); $duplicatesWizard->setStyle($redStyle); $conditionalStyles[] = $duplicatesWizard->getConditional(); $duplicatesWizard->unique() ->setStyle($greenStyle); $conditionalStyles[] = $duplicatesWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($duplicatesWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/06_Duplicate_Comparisons.php#L66 "Conditional Formatting - Duplicate/Unique Comparisons") for the repo. ![11-19-CF-Duplicates-Uniques-Examples.png](./images/11-19-CF-Duplicates-Uniques-Examples.png) Duplicates/Uniques Conditions are only identified by a Condition Type in Excel, with no operator and no expression. ### Expression Wizard The `Expression` Wizard expects to be provided with an Expression, an MS Excel formula that evaluates to either false or true. Condition Type | Wizard Factory newRule() Type Constant | Conditional Operator Type | Wizard Methods | Notes ---|---|---|---|--- Conditional::CONDITION_EXPRESSION | Wizard::EXPRESSION or Wizard::FORMULA | - | expression() | The argument is an Excel formula that evaluates to true or false | | | | formula() | Synonym for `expression()` Just as a simple example, here's a code snippet demonstrating expressions to determine if a cell contains an odd or an even number value: ```php $cellRange = 'A2:C11'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Expression $expressionWizard */ $expressionWizard = $wizardFactory->newRule(Wizard::EXPRESSION); $expressionWizard->expression('ISODD(A1)') ->setStyle($greenStyle); $conditionalStyles[] = $expressionWizard->getConditional(); $expressionWizard->expression('ISEVEN(A1)') ->setStyle($yellowStyle); $conditionalStyles[] = $expressionWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($expressionWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/07_Expression_Comparisons.php#L87 "Conditional Formatting - Odd/Even Expression Comparisons") for the repo. ![11-14-CF-Expression-Example-Odd-Even.png](./images/11-14-CF-Expression-Example-Odd-Even.png) As a more complicated example, let's look at a Sales Grid, and use conditional formatting to highlight sales in the "USA" region: ```php $greenStyleMoney = clone $greenStyle; $greenStyleMoney->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_ACCOUNTING_USD); $cellRange = 'A17:D22'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Expression $expressionWizard */ $expressionWizard = $wizardFactory->newRule(Wizard::EXPRESSION); $expressionWizard->expression('$C1="USA"') ->setStyle($greenStyleMoney); $conditionalStyles[] = $expressionWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($expressionWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/07_Expression_Comparisons.php#L107 "Conditional Formatting - Sales Grid Expression Comparisons") for the repo. ![11-15-CF-Expression-Sales-Grid-1.png](./images/11-15-CF-Expression-Sales-Grid-1.png) Or we could apply multiple comparisons in the same expression, so to check for all sales for the "USA" region in "Q4", combining them using an Excel `AND()`: ```php $expressionWizard->expression('AND($C1="USA",$D1="Q4")') ->setStyle($greenStyleMoney); ``` This example can also be found in the [code samples](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/ConditionalFormatting/07_Expression_Comparisons.php#L121 "Conditional Formatting - Sales Grid Expression Comparisons") for the repo. ![11-16-CF-Expression-Sales-Grid-2.png](./images/11-16-CF-Expression-Sales-Grid-2.png) ## General Notes ### Stop If True, and No Format Set Normally, Excel continues to check even after it finds a match. To tell it to stop once a match is found, 'stop if true' should be specified: ```php $conditional->setStopIfTrue(true); ``` Sometimes you want a matched cell to just show its unconditional format. This is most useful in conjunction with 'stop if true'. ```php $conditional->setNoFormatSet(true); ``` ### Changing the Cell Range If you want to apply the same Conditional Rule/Style to several different areas on your spreadsheet, then you can do this using the `setCellRange()` method between calls to `getConditional()`. ```php $wizardFactory = new Wizard(); /** @var Wizard\CellValue $wizard */ $wizard = $wizardFactory->newRule(Wizard::CELL_VALUE); // Apply the wizard conditional to cell range A2:A10 $cellRange = 'A2:A10'; $conditionalStyles = []; $wizard->between('$B1', Wizard::VALUE_TYPE_CELL) ->and('$C1', Wizard::VALUE_TYPE_CELL) ->setStyle($greenStyle); $spreadsheet->getActiveSheet() ->getStyle($wizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Apply the same wizard conditional to cell range E2:E10 $cellRange = 'E2:E10'; $wizard->setCellRange($cellRange); $conditionalStyles = []; $wizard->between('$B1', Wizard::VALUE_TYPE_CELL) ->and('$C1', Wizard::VALUE_TYPE_CELL) ->setStyle($greenStyle); $spreadsheet->getActiveSheet() ->getStyle($wizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` Because we use cell `A1` as the baseline cell for relative references, the Wizard is able to handle the necessary adjustments for cell references and formulae to match the range of cells that it is being applied to when `getConditional()` is called, so it returns the correct expression. ### Converting a Conditional to a Wizard If you already have a `Conditional` object; you can create a Wizard from that Conditional to manipulate it using all the benefits of the Wizard before using that to create a new version of the Conditional: ```php $wizard = Wizard\CellValue::fromConditional($conditional, '$A$3:$E$8'); $wizard->greaterThan(12.5); $newConditional = $wizard->getConditional(); ``` This is ok if you know what type of Conditional you want to convert; but it will throw an Exception if the Conditional is not of an appropriate type (ie. not a `cellIs`). If you don't know what type of Conditional it is, then it's better to use the Wizard Factory `fromConditional()` method instead; and then test what type of Wizard object is returned: ```php $wizard = Wizard::fromConditional($conditional, '$A$3:$E$8'); if ($wizard instanceof Wizard\CellValue) { $wizard->greaterThan(12.5); $newConditional = $wizard->getConditional(); } ``` ================================================ FILE: docs/topics/creating-spreadsheet.md ================================================ # Creating a spreadsheet ## The `Spreadsheet` class The `Spreadsheet` class is the core of PhpSpreadsheet. It contains references to the contained worksheets, document security settings and document meta data. To simplify the PhpSpreadsheet concept: the `Spreadsheet` class represents your workbook. Typically, you will create a workbook in one of two ways, either by loading it from a spreadsheet file, or creating it manually. A third option, though less commonly used, is cloning an existing workbook that has been created using one of the previous two methods. ### Loading a Workbook from a file Details of the different spreadsheet formats supported, and the options available to read them into a Spreadsheet object are described fully in the [Reading Files](./reading-files.md) document. ```php $inputFileName = './sampleData/example1.xls'; /** Load $inputFileName to a Spreadsheet object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); ``` ### Creating a new workbook If you want to create a new workbook, rather than load one from file, then you simply need to instantiate it as a new Spreadsheet object. ```php /** Create a new Spreadsheet Object **/ $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); ``` A new workbook will always be created with a single worksheet. ## Clearing a Workbook from memory The PhpSpreadsheet object contains cyclic references (e.g. the workbook is linked to the worksheets, and the worksheets are linked to their parent workbook) which cause problems when PHP tries to clear the objects from memory when they are `unset()`, or at the end of a function when they are in local scope. The result of this is "memory leaks", which can easily use a large amount of PHP's limited memory. This can only be resolved manually: if you need to unset a workbook, then you also need to "break" these cyclic references before doing so. PhpSpreadsheet provides the `disconnectWorksheets()` method for this purpose. ```php $spreadsheet->disconnectWorksheets(); unset($spreadsheet); ``` ================================================ FILE: docs/topics/defined-names.md ================================================ # Defined Names There are two types of Defined Names in MS Excel and other Spreadsheet formats: Named Ranges and Named Formulae. Between them, they can add a lot of power to your Spreadsheets, but they need to be used correctly. Working examples for all the code shown in this document can be found in the `/samples/DefinedNames` folder. ## Named Ranges A Named Range provides a name reference to a cell or a range of cells. You can then reference that cell or cells by that name within a formula. As an example, I'll create a simple Calculator that adds Tax to a Price. ```php // Set up some basic data $worksheet ->setCellValue('A1', 'Tax Rate:') ->setCellValue('B1', '=19%') ->setCellValue('A3', 'Net Price:') ->setCellValue('B3', 12.99) ->setCellValue('A4', 'Tax:') ->setCellValue('A5', 'Price including Tax:'); // Define named ranges $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('TAX_RATE', $worksheet, '=$B$1') ); $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PRICE', $worksheet, '=$B$3') ); // Reference that defined name in a formula $worksheet ->setCellValue('B4', '=PRICE*TAX_RATE') ->setCellValue('B5', '=PRICE*(1+TAX_RATE)'); echo sprintf( 'With a Tax Rate of %.2f and a net price of %.2f, Tax is %.2f and the gross price is %.2f', $worksheet->getCell('B1')->getCalculatedValue(), $worksheet->getCell('B3')->getValue(), $worksheet->getCell('B4')->getCalculatedValue(), $worksheet->getCell('B5')->getCalculatedValue() ), PHP_EOL; ``` `/samples/DefinedNames/SimpleNamedRange.php` This makes formulae in the generated spreadsheet easier to understand when viewing it them MS Excel. Using these Named Ranges (providing meaningful human-readable names for cells) makes the purpose of the formula immediately clear. We don't need to look for cell `B2` to see what it is, the name tells us. And, if the Tax Rate changes to 16%, then we only need to change the value in cell `B1` to the new Tax rate (`=16%`), or if we want to calculate the Tax Charges for a different net price, that will immediately be reflected in all the calculations that reference those Named Ranges. No matter whereabouts in the worksheet I used that Named Range, it always references the value in cell `B1`. In fact, because we were required to specify a worksheet when we defined the name, that name is available from any worksheet within the spreadsheet, and always means cell `B2` in this worksheet (but see the notes on Named Range Scope below). ### Absolute Named Ranges In the above example, when I define the Named Range values (e.g. `'=$B$1'`), I used a `$` before both the row and the column. This made the Named Range an Absolute Reference. Another example: ```php // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named range using an absolute cell reference $spreadsheet->addNamedRange( new NamedRange('CHARGE_RATE', $worksheet, '=$B$1') ); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", "=B{$row}*CHARGE_RATE"); $row++; } $endRow = $row - 1; ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(B{$startRow}:B{$endRow})") ->setCellValue("C{$row}", "=SUM(C{$startRow}:C{$endRow})"); echo sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $worksheet->getCell("B{$row}")->getCalculatedValue(), $worksheet->getCell('B1')->getValue(), $worksheet->getCell("C{$row}")->getCalculatedValue() ), PHP_EOL; ``` `/samples/DefinedNames/AbsoluteNamedRange.php` Because the Named Range `CHARGE_RATE` is defined as an Absolute cell reference, then it always references cell `B2` no matter where it is referenced in a formula in the spreadsheet. ### Relative Named Ranges The previous example showed a simple timesheet using an Absolute Reference for the Charge Rate, used to calculate our billed charges to client. The use of `B{$row}` in our formula (at least it will appear as an actual cell reference in MS Excel if we save the file and open it) requires a bit of mental agility to remember that column `B` is our hours for that day. Why can't we use another Named Range called something like `HOURS_PER_DAY` to make the formula more easily readable and meaningful. But if we used an Absolute Named Range for `HOURS_PER_DAY`, then we'd need a different Named Range for each day (`MONDAY_HOURS_PER_DAY`, `TUESDAY_HOURS_PER_DAY`, etc), and a different formula for each day of the week; if we kept a monthly timesheet, we would have to defined a different Named Range for every day of the month... and that's a lot more trouble than it's worth, and quickly becomes unmanageable. This is where Relative Named Ranges are very useful. ```php // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange( new NamedRange('CHARGE_RATE', $worksheet, '=$B$1') ); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange( new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1') ); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", "=HOURS_PER_DAY*CHARGE_RATE"); $row++; } $endRow = $row - 1; ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(B{$startRow}:B{$endRow})") ->setCellValue("C{$row}", "=SUM(C{$startRow}:C{$endRow})"); echo sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $worksheet->getCell("B{$row}")->getCalculatedValue(), $worksheet->getCell('B1')->getValue(), $worksheet->getCell("C{$row}")->getCalculatedValue() ), PHP_EOL; ``` `/samples/DefinedNames/RelativeNamedRange.php` The difference in the cell definition for `HOURS_PER_DAY` (`'=$B1'`) is that we have a `$` in front of the column `B`, but not in front of the row number. The `$` makes the column absolute: no matter where in the worksheet we use this name, it always references column `B`. Without a `$`in front of the row number, we make the row number relative, relative to the row where the name appears in a formula, so it effectively replaces the `1` with its own row number when it executes the calculation. When it is used in the formula in row 4, then it references cell `B4`, when it appears in row 5, it references cell `B5`, and so on. Using a Relative Named Range, we can use the same Named Range to refer to cells in different rows (and/or different columns), so we can re-use the same Named Range to refer to different cells relative to the row (or column) where we use them. --- Named Ranges aren't limited to a single cell, but can point to a range of cells. A common use case might be to provide a series of column totals at the bottom of a dataset. Let's take our timesheet, and modify it just slightly to use a Relative column range for that purpose. I won't replicate the entire code from the previous example, because I'm only changing a few lines; but we just replace the block: ```php ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(B{$startRow}:B{$endRow})") ->setCellValue("C{$row}", "=SUM(C{$startRow}:C{$endRow})"); ``` with: ```php // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange( new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}") ); ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(COLUMN_DATA_VALUES)") ->setCellValue("C{$row}", "=SUM(COLUMN_DATA_VALUES)"); ``` `/samples/DefinedNames/RelativeNamedRange2.php` Now that I've specified column as relative in the definition of `COLUMN_DATA_VALUES` with an address of column `A`, and the rows are absolute. When the same Relative Named Range is used in column `B`,it references cells in column `B` rather than `A`; and when it is used in column `C`, it references cells in column `C`. While we still have a piece of code (`"=A\${$startRow}:A\${$endRow}"`) that isn't easily human-readable, when we open the generated spreadsheet in MS Excel, the displayed formula in for the cells for the totals is immediately understandable. ### Named Range Scope Whenever we define a Named Range, we are required to specify a worksheet, and that name is then available from any worksheet within the spreadsheet, and always means that cell or cell range in the specified worksheet. ```php // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50'); // Define a global named range on the first worksheet for our Charge Rate // CHARGE_RATE is an absolute cell reference that always points to cell B1 // Because it is defined globally, it will still be usable from any worksheet in the spreadsheet $spreadsheet->addNamedRange( new NamedRange('CHARGE_RATE', $worksheet, '=$B$1') ); // Create a second worksheet as our client timesheet $worksheet = $spreadsheet->addSheet(new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Client Timesheet')); // Define named ranges // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange( new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1') ); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Date') ->setCellValue('B1', 'Hours') ->setCellValue('C1', 'Charge'); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 2; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", "=HOURS_PER_DAY*CHARGE_RATE"); $row++; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange( new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}") ); ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(COLUMN_DATA_VALUES)") ->setCellValue("C{$row}", "=SUM(COLUMN_DATA_VALUES)"); echo sprintf( 'Worked %.2f hours at a rate of %s - Charge to the client is %.2f', $worksheet->getCell("B{$row}")->getCalculatedValue(), $chargeRateCellValue = $spreadsheet ->getSheetByName($spreadsheet->getNamedRange('CHARGE_RATE')->getWorksheet()->getTitle()) ->getCell($spreadsheet->getNamedRange('CHARGE_RATE')->getCellsInRange()[0])->getValue(), $worksheet->getCell("C{$row}")->getCalculatedValue() ), PHP_EOL; ``` `/samples/DefinedNames/ScopedNamedRange.php` Even though `CHARGE_RATE` references a cell on a different worksheet, because is set as global (the default) it is accessible from any worksheet in the spreadsheet. so when we reference it in formulae on the second timesheet worksheet, we are able to access the value from that first worksheet and use it in our calculations. --- However, a Named Range can be locally scoped so that it is only available when referenced from a specific worksheet, or it can be globally scoped. This means that you can use the same Named Range name with different values on different worksheets. Building further on our timesheet, perhaps we use a different worksheet for each client, and we use the same hourly rate when billing most of our clients; but for one particular client (perhaps doing work for a friend) we use a lower rate. ```php $clients = [ 'Client #1 - Full Hourly Rate' => [ '2020-0-06' => 2.5, '2020-0-07' => 2.25, '2020-0-08' => 6.0, '2020-0-09' => 3.0, '2020-0-10' => 2.25, ], 'Client #2 - Full Hourly Rate' => [ '2020-0-06' => 1.5, '2020-0-07' => 2.75, '2020-0-08' => 0.0, '2020-0-09' => 4.5, '2020-0-10' => 3.5, ], 'Client #3 - Reduced Hourly Rate' => [ '2020-0-06' => 3.5, '2020-0-07' => 2.5, '2020-0-08' => 1.5, '2020-0-09' => 0.0, '2020-0-10' => 1.25, ], ]; foreach ($clients as $clientName => $workHours) { $worksheet = $spreadsheet->addSheet(new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, $clientName)); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); ; // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange( new NamedRange('CHARGE_RATE', $worksheet, '=$B$1', true) ); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange( new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1', true) ); // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", "=HOURS_PER_DAY*CHARGE_RATE"); $row++; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange( new NamedRange('COLUMN_TOTAL', $worksheet, "=A\${$startRow}:A\${$endRow}", true) ); ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(COLUMN_TOTAL)") ->setCellValue("C{$row}", "=SUM(COLUMN_TOTAL)"); } $spreadsheet->removeSheetByIndex(0); // Set the reduced charge rate for our special client $worksheet ->setCellValue("B1", 4.5); foreach ($spreadsheet->getAllSheets() as $worksheet) { echo sprintf( 'Worked %.2f hours for "%s" at a rate of %.2f - Charge to the client is %.2f', $worksheet->getCell("B{$row}")->getCalculatedValue(), $worksheet->getTitle(), $worksheet->getCell('B1')->getValue(), $worksheet->getCell("C{$row}")->getCalculatedValue() ), PHP_EOL; } ``` `/samples/DefinedNames/ScopedNamedRange2.php` Now we are creating three worksheets for each of three different clients. Because each Named Range is linked to a worksheet, we need to create three sets of Named Ranges, so that we don't simply reference the cells on only one of the worksheets; but because we are locally scoping them (note the extra boolean argument used when we define the Named Ranges) we can use the same names on each worksheet, and they will reference the correct cells when we use them in our formulae on that worksheet. When Named Ranges are being evaluated, the logic looks first to see if there is a locally scoped Named Range defined for the current worksheet. If there is, then that is the Named Range that will be used in the calculation. If no locally scoped Named Range with that name is found, the logic then looks to see if there is a globally scoped Named Range definition, and will use that if it is found. If no Named Range of the required name is found scoped to the current worksheet, or globally scoped, then a `#NAME` error will be returned. ## Named Formulae A Named Formula is a stored formula, or part of a formula, that can be referenced in cells by name, and re-used in many different places within the spreadsheet. As an example, I'll modify the simple Tax Calculator that I created as my example for Named Ranges. ```php // Add some Named Formulae // The first to store our tax rate $spreadsheet->addNamedFormula(new NamedFormula('TAX_RATE', $worksheet, '=19%')); // The second to calculate the Tax on a Price value (Note that `PRICE` is defined later as a Named Range) $spreadsheet->addNamedFormula(new NamedFormula('TAX', $worksheet, '=PRICE*TAX_RATE')); // Set up some basic data $worksheet ->setCellValue('A1', 'Tax Rate:') ->setCellValue('B1', '=TAX_RATE') ->setCellValue('A3', 'Net Price:') ->setCellValue('B3', 19.99) ->setCellValue('A4', 'Tax:') ->setCellValue('A5', 'Price including Tax:'); // Define a named range that we can use in our formulae $spreadsheet->addNamedRange(new NamedRange('PRICE', $worksheet, '=$B$3')); // Reference the defined formulae in worksheet formulae $worksheet ->setCellValue('B4', '=TAX') ->setCellValue('B5', '=PRICE+TAX'); echo sprintf( 'With a Tax Rate of %.2f and a net price of %.2f, Tax is %.2f and the gross price is %.2f', $worksheet->getCell('B1')->getCalculatedValue(), $worksheet->getCell('B3')->getValue(), $worksheet->getCell('B4')->getCalculatedValue(), $worksheet->getCell('B5')->getCalculatedValue() ), PHP_EOL; ``` `/samples/DefinedNames/SimpleNamedFormula.php` There are a few points to note here: Firstly. we are actually storing the tax rate in a named formula (`TAX_RATE`) rather than as a cell value. When we display the tax rate in cell `B1`, we are really storing an instruction for MS Excel to evaluate the formula and display the result in that cell. Then we are using a Named Formula `TAX` that references both another Named Formula (`TAX_RATE`) and a Named Range (`PRICE`) and executes a calculation using them both (`PRICE * TAX_RATE`). Finally, we are using the formula `TAX` in two different contexts. Once to display the tax value (in cell `B4`); and a second time as part of another formula (`PRICE + TAX`) in cell `B5`. --- Named Formulae aren't just restricted tosimple mathematics, but can include MS EXcel functions as well to provide a lot of flexibility; and they can reference values on other worksheets. ```php $worksheet = $spreadsheet->setActiveSheetIndex(0); setYearlyData($worksheet,'2019', $data2019); $worksheet = $spreadsheet->addSheet(new Worksheet($spreadsheet)); setYearlyData($worksheet,'2020', $data2020); $worksheet = $spreadsheet->addSheet(new Worksheet($spreadsheet)); setYearlyData($worksheet,'2020', [], 'GROWTH'); function setYearlyData(Worksheet $worksheet, string $year, $yearlyData, ?string $title = null) { // Set up some basic data $worksheetTitle = $title ?: $year; $worksheet ->setTitle($worksheetTitle) ->setCellValue('A1', 'Month') ->setCellValue('B1', $worksheetTitle === 'GROWTH' ? 'Growth' : 'Sales') ->setCellValue('C1', $worksheetTitle === 'GROWTH' ? 'Profit Growth' : 'Margin') ->setCellValue('A2', Date::stringToExcel("{$year}-01-01")); for ($row = 3; $row <= 13; ++$row) { $worksheet->setCellValue("A{$row}", "=NEXT_MONTH"); } if (!empty($yearlyData)) { $worksheet->fromArray($yearlyData, null, 'B2'); } else { for ($row = 2; $row <= 13; ++$row) { $worksheet->setCellValue("B{$row}", "=GROWTH"); $worksheet->setCellValue("C{$row}", "=PROFIT_GROWTH"); } } $worksheet->getStyle('A1:C1') ->getFont()->setBold(true); $worksheet->getStyle('A2:A13') ->getNumberFormat() ->setFormatCode('mmmm'); $worksheet->getStyle('B2:C13') ->getNumberFormat() ->setFormatCode($worksheetTitle === 'GROWTH' ? '0.00%' : '_-€* #,##0_-'); } // Add some Named Formulae // The first to store our tax rate $spreadsheet->addNamedFormula(new NamedFormula('NEXT_MONTH', $worksheet, "=EDATE(OFFSET(\$A1,-1,0),1)")); $spreadsheet->addNamedFormula(new NamedFormula('GROWTH', $worksheet, "=IF('2020'!\$B1=\"\",\"-\",(('2020'!\$B1/'2019'!\$B1)-1))")); $spreadsheet->addNamedFormula(new NamedFormula('PROFIT_GROWTH', $worksheet, "=IF('2020'!\$C1=\"\",\"-\",(('2020'!\$C1/'2019'!\$C1)-1))")); for ($row = 2; $row<=7; ++$row) { $month = $worksheet->getCell("A{$row}")->getFormattedValue(); $growth = $worksheet->getCell("B{$row}")->getFormattedValue(); $profitGrowth = $worksheet->getCell("C{$row}")->getFormattedValue(); echo "Growth for {$month} is {$growth}, with a Profit Growth of {$profitGrowth}", PHP_EOL; } ``` `/samples/DefinedNames/CrossWorksheetNamedFormula.php` Here we're creating two Named Formulae that both use the `IF()` function, and that compare values on two different worksheets, and calculate the percentage difference between the two. We're also creating a Named Formula that uses the `OFFSET()` function to reference the cell immediately above the current Relative cell reference. ## Combining Named Ranges and Formulae For a slightly more complex example combining Named Ranges and Named Formulae, we can build on our client timesheet. ```php // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); // Set up the formula for calculating the daily charge $spreadsheet->addNamedFormula(new NamedFormula('DAILY_CHARGE', null, '=HOURS_PER_DAY*CHARGE_RATE')); // Set up the formula for calculating the column totals $spreadsheet->addNamedFormula(new NamedFormula('COLUMN_TOTALS', null, '=SUM(COLUMN_DATA_VALUES)')); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=DAILY_CHARGE'); ++$row; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange(new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}")); ++$row; $worksheet ->setCellValue("B{$row}", '=COLUMN_TOTALS') ->setCellValue("C{$row}", '=COLUMN_TOTALS'); echo sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $worksheet->getCell("B{$row}")->getCalculatedValue(), $worksheet->getCell('B1')->getValue(), $worksheet->getCell("C{$row}")->getCalculatedValue() ), PHP_EOL; ``` `/samples/DefinedNames/NamedFormulaeAndRanges.php` The main point to notice in this example is that you must specify a Worksheet for Named Ranges, but that it isn't required for Named Formulae; in fact, specifying a Worksheet for named Formulae can lead to MS Excel errors when a saved file is opened. Generally, it is far safer to specify a null Worksheet value when creating a Named Formula, unless it references cell values explicitly, or you wish to scope it to that Worksheet. It also doesn't matter what order we define our Named Ranges and Formulae, even when some are dependent on others: this only matters when we try to use them in a cell calculation, or when we save the file; and as long as every Defined Name has been defined at that point, then it isn't important. In this case, we couldn't define `COLUMN_DATA_VALUES` until we new the range of rows that it needed to contain; but we could still define the `COLUMN_TOTALS` formula before that. ## Additional Comments ### Helper In all the examples so far, we have explicitly used the `NamedRange` and `NamedFormula` classes, and the Spreadsheet's `addNamedRange()` and `addNamedFormula()` methods, e.g. ```php $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); ``` However, this can lead to errors if we accidentally set a formula value for a Named Range, or a range value for a Named Formula. As a helper, the DefinedName class provides a static method that can identify whether the value expression is a Range or a Formula, and instantiate the appropriate class. ```php $this->spreadsheet->addDefinedName( DefinedName::createInstance('FOO', $this->spreadsheet->getSheetByName('Sheet #2'), '=16%', true) ); ``` ### Naming Names The names that you assign to Defined Name must follow the following set of rules: - The first character of a name must be one of the following characters: - letter (including UTF-8 letters) - underscore (`_`) - Remaining characters in the name can be - letters (including UTF-8 letters) - numbers (including UTF-8 numbers) - periods (`.`) - underscore characters (`_`) - The following are not allowed: - Space characters are not allowed as part of a name. - Names can't look like cell addresses, such as A35 or R2C2 - Names are not case sensitive. For example, `North` and `NORTH` are treated as the same name. ### Limitations PHPSpreadsheet doesn't yet fully validate the names that you use, so it is possible to create a spreadsheet in PHPSpreadsheet that will break when you save and try to open it in MS Excel; or that will break PHPSpreadsheet when they are referenced in a cell. So please be sensible when creating names, and follow the rules listed above. --- There is nothing to stop you creating a Defined Name that matches an existing Function name ```php $spreadsheet->addNamedFormula(new NamedFormula('SUM', $worksheet, '=SUM(A1:E5)')); ``` And this will work without problems in MS Excel. However, it is not guaranteed to work correctly in PHPSpreadsheet; and will certainly cause confusion for anybody reading it; so it is not recommended. Names exist to give clarity to the person reading the spreadsheet, and a cell containing `=SUM` is even harder to understand (what is it the sum of?) than a cell containing `=SUM(B4:B8)`. Use names that provide meaning, like `SUM_OF_WORKED_HOURS`. --- You cannot have a Named Range and a Named Formula with the same name, unless they are differently scoped. --- MS Excel uses some "special tricks" to simulate Relative Named Ranges where the row or column comes before the current row or column, useful if you want to get column totals that don't include the current cell. These "tricks" aren't supported by PHPSpreadsheet, but can be simulated using the `OFFSET()` function in a Named Formula. In our `RelativeNamedRange2.php` example, we explicitly created the `COLUMN_DATA_VALUES` Named Range using only the rows that we knew should be included, so that we weren't including the current row (where we were displaying the total) and creating a cyclic reference: ```php // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange(new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}")); ``` We could instead have created a Named Function using `OFFSET()` to specify just the start row, and offset the end row by -1 row: ```php // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used // To avoid including the current row,or having to hard-code the range itself (as we did in the previous example) // we wrap it in a named formula using the OFFSET() function $spreadsheet->addNamedFormula(new NamedFormula('COLUMN_DATA_VALUES', $worksheet, "=OFFSET(A\$4:A1, -1, 0)")); ``` as demonstrated in example `RelativeNamedRangeAsFunction.php`. ================================================ FILE: docs/topics/file-formats.md ================================================ # File Formats PhpSpreadsheet can read a number of different spreadsheet and file formats, although not all features are supported by all of the readers. Check the [features cross reference](../references/features-cross-reference.md) for a list that identifies which features are supported by which readers. Currently, PhpSpreadsheet supports the following File Types for Reading: ### Xls The Microsoft Excel™ Binary file format (BIFF5 and BIFF8) is a binary file format that was used by Microsoft Excel™ between versions 95 and 2003. The format is supported (to various extents) by most spreadsheet programs. BIFF files normally have an extension of .xls. Documentation describing the format can be [read online](https://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx) or [downloaded as PDF](https://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/%5BMS-XLS%5D.pdf). ### Xml Microsoft Excel™ 2003 included options for a file format called SpreadsheetML. This file is a zipped XML document. It is not very common, but its core features are supported. Documentation for the format can be [read online](https://msdn.microsoft.com/en-us/library/aa140066(office.10).aspx) though it’s sadly rather sparse in its detail. ### Xlsx Microsoft Excel™ 2007 shipped with a new file format, namely Microsoft Office Open XML SpreadsheetML, and Excel 2010 extended this still further with its new features such as sparklines. These files typically have an extension of .xlsx. This format is based around a zipped collection of eXtensible Markup Language (XML) files. Microsoft Office Open XML SpreadsheetML is mostly standardized in [ECMA 376](https://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm) and ISO 29500. ### Ods aka Open Document Format (ODF) or OASIS, this is the OpenOffice.org XML file format for spreadsheets. It comprises a zip archive including several components all of which are text files, most of these with markup in the eXtensible Markup Language (XML). It is the standard file format for OpenOffice.org Calc and StarCalc, and files typically have an extension of .ods. The published specification for the file format is available from [the OASIS Open Office XML Format Technical Committee web page](https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office). Other information is available from [the OpenOffice.org XML File Format web page](https://www.openoffice.org/xml/), part of the OpenOffice.org project. ### Slk This is the Microsoft Multiplan Symbolic Link Interchange (SYLK) file format. Multiplan was a predecessor to Microsoft Excel™. Files normally have an extension of .slk. While not common, there are still a few applications that generate SYLK files as a cross-platform option, because (despite being limited to a single worksheet) it is a simple format to implement, and supports some basic data and cell formatting options (unlike CSV files). ### Gnumeric The [Gnumeric file format](https://help.gnome.org/users/gnumeric/stable/sect-file-formats.html.en#file-format-gnumeric) is used by the Gnome Gnumeric spreadsheet application, and typically files have an extension of `.gnumeric`. The file contents are stored using eXtensible Markup Language (XML) markup, and the file is then compressed using the GNU project's gzip compression library. ### Csv Comma Separated Value (CSV) file format is a common structuring strategy for text format files. In CSV files, each line in the file represents a row of data and (within each line of the file) the different data fields (or columns) are separated from one another using a comma (`,`). If a data field contains a comma, then it should be enclosed (typically in quotation marks (`"`). Sometimes tabs `\t`, or the pipe symbol (`|`), or a semi-colon (`;`) are used as separators instead of a comma, although other symbols can be used. Because CSV is a text-only format, it doesn't support any data formatting options. "CSV" is not a single, well-defined format (although see [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180.html) for one definition that is commonly used). Rather, in practice the term "CSV" refers to any file that: - is plain text using a character set such as ASCII, Unicode, EBCDIC, or Shift JIS, - consists of records (typically one record per line), - with the records divided into fields separated by delimiters (typically a single reserved character such as comma, semicolon, or tab, - where every record has the same sequence of fields. Within these general constraints, many variations are in use. Therefore "CSV" files are not entirely portable. Nevertheless, the variations are fairly small, and many implementations allow users to glance at the file (which is feasible because it is plain text), and then specify the delimiter character(s), quoting rules, etc. **Warning:** Microsoft Excel™ will open .csv files, but depending on the system's regional settings, it may expect a semicolon as a separator instead of a comma, since in some languages the comma is used as the decimal separator. Also, many regional versions of Excel will not be able to deal with Unicode characters in a CSV file. ### Html HyperText Markup Language (HTML) is the main markup language for creating web pages and other information that can be displayed in a web browser. Files typically have an extension of .html or .htm. HTML markup provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. Since 1996, the HTML specifications have been maintained, with input from commercial software vendors, by the World Wide Web Consortium (W3C). However, in 2000, HTML also became an international standard (ISO/IEC 15445:2000). HTML 4.01 was published in late 1999, with further errata published through 2001. In 2004 development began on HTML5 in the Web Hypertext Application Technology Working Group (WHATWG), which became a joint deliverable with the W3C in 2008. ================================================ FILE: docs/topics/memory_saving.md ================================================ # Memory saving PhpSpreadsheet uses an average of about 1k per cell (1.6k on 64-bit PHP) in your worksheets, so large workbooks can quickly use up available memory. Cell caching provides a mechanism that allows PhpSpreadsheet to maintain the cell objects in a smaller size of memory, or off-memory (eg: on disk, in APCu, memcache or redis). This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data. By default, PhpSpreadsheet holds all cell objects in memory, but you can specify alternatives by providing your own [PSR-16](https://www.php-fig.org/psr/psr-16/) implementation. PhpSpreadsheet keys are automatically namespaced, and cleaned up after use, so a single cache instance may be shared across several usage of PhpSpreadsheet or even with other cache usages. To enable cell caching, you must provide your own implementation of cache like so: ```php $cache = new MyCustomPsr16Implementation(); \PhpOffice\PhpSpreadsheet\Settings::setCache($cache); ``` A separate cache is maintained for each individual worksheet, and is automatically created when the worksheet is instantiated based on the settings that you have configured. You cannot change the configuration settings once you have started to read a workbook, or have created your first worksheet. ## Beware of TTL As opposed to common cache concept, PhpSpreadsheet data cannot be re-generated from scratch. If some data is stored and later is not retrievable, PhpSpreadsheet will throw an exception. That means that the data stored in cache **must not be deleted** by a third-party or via TTL mechanism. So be sure that TTL is either de-activated or long enough to cover the entire usage of PhpSpreadsheet. ## Common use cases PhpSpreadsheet does not ship with alternative cache implementation. It is up to you to select the most appropriate implementation for your environment. You can either implement [PSR-16](https://www.php-fig.org/psr/psr-16/) from scratch, or use [pre-existing libraries](https://packagist.org/search/?q=psr-16). One such library is [PHP Cache](https://www.php-cache.com/) which provides a wide range of alternatives. Refers to their documentation for details, but here are a few suggestions that should get you started. ### APCu Require the packages into your project: ```sh composer require cache/simple-cache-bridge cache/apcu-adapter ``` Configure PhpSpreadsheet with something like: ```php $pool = new \Cache\Adapter\Apcu\ApcuCachePool(); $simpleCache = new \Cache\Bridge\SimpleCache\SimpleCacheBridge($pool); \PhpOffice\PhpSpreadsheet\Settings::setCache($simpleCache); ``` ### Redis Require the packages into your project: ```sh composer require cache/simple-cache-bridge cache/redis-adapter ``` Configure PhpSpreadsheet with something like: ```php $client = new \Redis(); $client->connect('127.0.0.1', 6379); $pool = new \Cache\Adapter\Redis\RedisCachePool($client); $simpleCache = new \Cache\Bridge\SimpleCache\SimpleCacheBridge($pool); \PhpOffice\PhpSpreadsheet\Settings::setCache($simpleCache); ``` ### Memcache Require the packages into your project: ```sh composer require cache/simple-cache-bridge cache/memcache-adapter ``` Configure PhpSpreadsheet with something like: ```php $client = new \Memcache(); $client->connect('localhost', 11211); $pool = new \Cache\Adapter\Memcache\MemcacheCachePool($client); $simpleCache = new \Cache\Bridge\SimpleCache\SimpleCacheBridge($pool); \PhpOffice\PhpSpreadsheet\Settings::setCache($simpleCache); ``` ================================================ FILE: docs/topics/migration-from-PHPExcel.md ================================================ # Migration from PHPExcel PhpSpreadsheet introduced many breaking changes by introducing namespaces and renaming some classes. To help you migrate existing project, a tool was written to replace all references to PHPExcel classes to their new names. But there are also manual changes that need to be done. ## Automated tool [RectorPHP](https://github.com/rectorphp/rector) can be used to automatically migrate your codebase. Note that this support has been dropped from current releases of rector, so you need to require an earlier release to do this. Assuming that your files to be migrated live in `src/`, you can run the migration like so: ```sh composer require rector/rector:0.15.10 rector/rector-phpoffice phpoffice/phpspreadsheet --dev # this creates rector.php config vendor/bin/rector init ``` Add `PHPOfficeSetList` set to `rector.php` ```php declare(strict_types=1); use Rector\Config\RectorConfig; use Rector\PHPOffice\Set\PHPOfficeSetList; return static function (RectorConfig $rectorConfig): void { $rectorConfig->sets([ PHPOfficeSetList::PHPEXCEL_TO_PHPSPREADSHEET ]); }; ``` And run Rector on your code: ```sh vendor/bin/rector process src ``` For more details, see [rector-phpoffice](https://github.com/rectorphp/rector-phpoffice). ## Manual changes RectorPHP should take care of everything, but if somehow it does not work, you can review/apply the following manual changes ### Renamed readers and writers When using `IOFactory::createReader()`, `IOFactory::createWriter()` and `IOFactory::identify()`, the reader/writer short names are used. Those were changed, along as their corresponding class, to remove ambiguity: Before | After -----------------|--------- `'CSV'` | `'Csv'` `'Excel2003XML'` | `'Xml'` `'Excel2007'` | `'Xlsx'` `'Excel5'` | `'Xls'` `'Gnumeric'` | `'Gnumeric'` `'HTML'` | `'Html'` `'OOCalc'` | `'Ods'` `'OpenDocument'` | `'Ods'` `'PDF'` | `'Pdf'` `'SYLK'` | `'Slk'` ### Simplified IOFactory The following methods : - `PHPExcel_IOFactory::getSearchLocations()` - `PHPExcel_IOFactory::setSearchLocations()` - `PHPExcel_IOFactory::addSearchLocation()` were replaced by `IOFactory::registerReader()` and `IOFactory::registerWriter()`. That means IOFactory now relies on classes autoloading. Before: ```php // Before \PHPExcel_IOFactory::addSearchLocation($type, $location, $classname); // After \PhpOffice\PhpSpreadsheet\IOFactory::registerReader($type, $classname); ``` ### Removed deprecated things #### Worksheet::duplicateStyleArray() ``` php // Before $worksheet->duplicateStyleArray($styles, $range, $advanced); // After $worksheet->getStyle($range)->applyFromArray($styles, $advanced); ``` #### DataType::dataTypeForValue() ``` php // Before DataType::dataTypeForValue($value); // After DefaultValueBinder::dataTypeForValue($value); ``` #### Conditional::getCondition() ``` php // Before $conditional->getCondition(); // After $conditional->getConditions()[0]; ``` #### Conditional::setCondition() ``` php // Before $conditional->setCondition($value); // After $conditional->setConditions($value); ``` #### Worksheet::getDefaultStyle() ``` php // Before $worksheet->getDefaultStyle(); // After $worksheet->getParent()->getDefaultStyle(); ``` #### Worksheet::setDefaultStyle() ``` php // Before $worksheet->setDefaultStyle($value); // After $worksheet->getParent()->getDefaultStyle()->applyFromArray([ 'font' => [ 'name' => $pValue->getFont()->getName(), 'size' => $pValue->getFont()->getSize(), ], ]); ``` #### Worksheet::setSharedStyle() ``` php // Before $worksheet->setSharedStyle($sharedStyle, $range); // After $worksheet->duplicateStyle($sharedStyle, $range); ``` #### Worksheet::getSelectedCell() ``` php // Before $worksheet->getSelectedCell(); // After $worksheet->getSelectedCells(); ``` #### Writer\Xls::setTempDir() ``` php // Before $writer->setTempDir(); // After, there is no way to set temporary storage directory anymore ``` ### Autoloader The class `PHPExcel_Autoloader` was removed entirely and is replaced by composer autoloading mechanism. ### Writing PDF PDF libraries must be installed via composer. And the following methods were removed and are replaced by `IOFactory::registerWriter()` instead: - `PHPExcel_Settings::getPdfRenderer()` - `PHPExcel_Settings::setPdfRenderer()` - `PHPExcel_Settings::getPdfRendererName()` - `PHPExcel_Settings::setPdfRendererName()` Before: ```php \PHPExcel_Settings::setPdfRendererName(PHPExcel_Settings::PDF_RENDERER_MPDF); \PHPExcel_Settings::setPdfRenderer($somePath); $writer = \PHPExcel_IOFactory::createWriter($spreadsheet, 'PDF'); ``` After: ```php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf'); // Or alternatively \PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Pdf'); // Or alternatively $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet); ``` ### Rendering charts When rendering charts for HTML or PDF outputs, the process was simplified. And, while JpGraph support is still available, the version distributed via Composer is no longer maintained, so you would need to install the current version manually. If you rely on this package, please consider contributing patches either to JpGraph or another `IRenderer` implementation (a good candidate might be [CpChart](https://github.com/szymach/c-pchart)). The package [mitoteam/jpgraph](https://github.com/mitoteam/jpgraph) is distributed via Composer, and is fully compatible with Jpgraph. We recommend that it be used for rendering. Before: ```php $rendererName = \PHPExcel_Settings::CHART_RENDERER_JPGRAPH; $rendererLibrary = 'jpgraph3.5.0b1/src/'; $rendererLibraryPath = '/php/libraries/Charts/' . $rendererLibrary; \PHPExcel_Settings::setChartRenderer($rendererName, $rendererLibraryPath); ``` After: Require the dependency via composer: ```sh composer require mitoteam/jpgraph ``` And then: ```php Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class); ``` ### PclZip and ZipArchive Support for PclZip were dropped in favor of the more complete and modern [PHP extension ZipArchive](https://php.net/manual/en/book.zip.php). So the following were removed: - `PclZip` - `PHPExcel_Settings::setZipClass()` - `PHPExcel_Settings::getZipClass()` - `PHPExcel_Shared_ZipArchive` - `PHPExcel_Shared_ZipStreamWrapper` ### Cell caching Cell caching was heavily refactored to leverage [PSR-16](https://www.php-fig.org/psr/psr-16/). That means most classes related to that feature were removed: - `PHPExcel_CachedObjectStorage_APC` - `PHPExcel_CachedObjectStorage_DiscISAM` - `PHPExcel_CachedObjectStorage_ICache` - `PHPExcel_CachedObjectStorage_Igbinary` - `PHPExcel_CachedObjectStorage_Memcache` - `PHPExcel_CachedObjectStorage_Memory` - `PHPExcel_CachedObjectStorage_MemoryGZip` - `PHPExcel_CachedObjectStorage_MemorySerialized` - `PHPExcel_CachedObjectStorage_PHPTemp` - `PHPExcel_CachedObjectStorage_SQLite` - `PHPExcel_CachedObjectStorage_SQLite3` - `PHPExcel_CachedObjectStorage_Wincache` In addition to that, `\PhpOffice\PhpSpreadsheet::getCellCollection()` was renamed to `\PhpOffice\PhpSpreadsheet::getCoordinates()` and `\PhpOffice\PhpSpreadsheet::getCellCacheController()` to `\PhpOffice\PhpSpreadsheet::getCellCollection()` for clarity. Refer to [the new documentation](./memory_saving.md) to see how to migrate. ### Dropped conditionally returned cell For all the following methods, it is not possible to change the type of returned value. They will always return the Worksheet and never the Cell or Rule: - Worksheet::setCellValue() - Worksheet::setCellValueByColumnAndRow() (*deprecated*) - Worksheet::setCellValueExplicit() - Worksheet::setCellValueExplicitByColumnAndRow() (*deprecated*) - Worksheet::addRule() Migration would be similar to: ``` php // Before $cell = $worksheet->setCellValue('A1', 'value', true); // After $cell = $worksheet->getCell('A1')->setValue('value'); ``` ### Standardized keys for styling Array keys used for styling have been standardized for a more coherent experience. It now uses the same wording and casing as the getter and setter: ```php // Before $style = [ 'numberformat' => [ 'code' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE, ], 'font' => [ 'strike' => true, 'superScript' => true, 'subScript' => true, ], 'alignment' => [ 'rotation' => 90, 'readorder' => Alignment::READORDER_RTL, 'wrap' => true, ], 'borders' => [ 'diagonaldirection' => Borders::DIAGONAL_BOTH, 'allborders' => [ 'style' => Border::BORDER_THIN, ], ], 'fill' => [ 'type' => Fill::FILL_GRADIENT_LINEAR, 'startcolor' => [ 'argb' => 'FFA0A0A0', ], 'endcolor' => [ 'argb' => 'FFFFFFFF', ], ], ]; // After $style = [ 'numberFormat' => [ 'formatCode' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE, ], 'font' => [ 'strikethrough' => true, 'superscript' => true, 'subscript' => true, ], 'alignment' => [ 'textRotation' => 90, 'readOrder' => Alignment::READORDER_RTL, 'wrapText' => true, ], 'borders' => [ 'diagonalDirection' => Borders::DIAGONAL_BOTH, 'allBorders' => [ 'borderStyle' => Border::BORDER_THIN, ], ], 'fill' => [ 'fillType' => Fill::FILL_GRADIENT_LINEAR, 'startColor' => [ 'argb' => 'FFA0A0A0', ], 'endColor' => [ 'argb' => 'FFFFFFFF', ], ], ]; ``` ### Dedicated class to manipulate coordinates Methods to manipulate coordinates that used to exists in `PHPExcel_Cell` were extracted to a dedicated new class `\PhpOffice\PhpSpreadsheet\Cell\Coordinate`. The methods are: - `absoluteCoordinate()` - `absoluteReference()` - `buildRange()` - `columnIndexFromString()` - `coordinateFromString()` - `extractAllCellReferencesInRange()` - `getRangeBoundaries()` - `mergeRangesInCollection()` - `rangeBoundaries()` - `rangeDimension()` - `splitRange()` - `stringFromColumnIndex()` ### Column index based on 1 Column indexes are now based on 1. So column `A` is the index `1`. This is consistent with rows starting at 1 and Excel function `COLUMN()` that returns `1` for column `A`. So the code must be adapted with something like: ```php // Before $cell = $worksheet->getCellByColumnAndRow($column, $row); // Use StringHelper::stringIncrement($column) rather than ++$column if using Php8.5+. for ($column = 0; $column < $max; ++$column) { $worksheet->setCellValueByColumnAndRow($column, $row, 'value'); } // After $cell = $worksheet->getCell([$column + 1, $row]); // Use StringHelper::stringIncrement($column) rather than ++$column if using Php8.5+. for ($column = 1; $column <= $max; ++$column) { $worksheet->setCellValue([$column, $row], 'value'); } ``` All the following methods are affected, and all are now deprecated (see example above for how to replace them): - `PHPExcel_Worksheet::cellExistsByColumnAndRow()` - `PHPExcel_Worksheet::freezePaneByColumnAndRow()` - `PHPExcel_Worksheet::getCellByColumnAndRow()` - `PHPExcel_Worksheet::getColumnDimensionByColumn()` - `PHPExcel_Worksheet::getCommentByColumnAndRow()` - `PHPExcel_Worksheet::getStyleByColumnAndRow()` - `PHPExcel_Worksheet::insertNewColumnBeforeByIndex()` - `PHPExcel_Worksheet::mergeCellsByColumnAndRow()` - `PHPExcel_Worksheet::protectCellsByColumnAndRow()` - `PHPExcel_Worksheet::removeColumnByIndex()` - `PHPExcel_Worksheet::setAutoFilterByColumnAndRow()` - `PHPExcel_Worksheet::setBreakByColumnAndRow()` - `PHPExcel_Worksheet::setCellValueByColumnAndRow()` - `PHPExcel_Worksheet::setCellValueExplicitByColumnAndRow()` - `PHPExcel_Worksheet::setSelectedCellByColumnAndRow()` - `PHPExcel_Worksheet::stringFromColumnIndex()` - `PHPExcel_Worksheet::unmergeCellsByColumnAndRow()` - `PHPExcel_Worksheet::unprotectCellsByColumnAndRow()` - `PHPExcel_Worksheet_PageSetup::addPrintAreaByColumnAndRow()` - `PHPExcel_Worksheet_PageSetup::setPrintAreaByColumnAndRow()` ### Removed default values Default values for many methods were removed when it did not make sense. Typically, setter methods should not have default values. For a complete list of methods and their original default values, see [that commit](https://github.com/PHPOffice/PhpSpreadsheet/commit/033a4bdad56340795a5bf7ec3c8a2fde005cda24). ================================================ FILE: docs/topics/reading-and-writing-to-file.md ================================================ # Reading and writing to file As you already know from the [architecture](./architecture.md#readers-and-writers), reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of `\PhpOffice\PhpSpreadsheet\Reader\IReader` and `\PhpOffice\PhpSpreadsheet\Writer\IWriter`. ## \PhpOffice\PhpSpreadsheet\IOFactory The PhpSpreadsheet API offers multiple methods to create a `\PhpOffice\PhpSpreadsheet\Reader\IReader` or `\PhpOffice\PhpSpreadsheet\Writer\IWriter` instance: Direct creation via `\PhpOffice\PhpSpreadsheet\IOFactory`. All examples underneath demonstrate the direct creation method. Note that you can also use the `\PhpOffice\PhpSpreadsheet\IOFactory` class to do this. ### Creating `\PhpOffice\PhpSpreadsheet\Reader\IReader` using `\PhpOffice\PhpSpreadsheet\IOFactory` There are 2 methods for reading in a file into PhpSpreadsheet: using automatic file type resolving or explicitly. Automatic file type resolving checks the different `\PhpOffice\PhpSpreadsheet\Reader\IReader` distributed with PhpSpreadsheet. If one of them can load the specified file name, the file is loaded using that `\PhpOffice\PhpSpreadsheet\Reader\IReader`. Explicit mode requires you to specify which `\PhpOffice\PhpSpreadsheet\Reader\IReader` should be used. You can create a `\PhpOffice\PhpSpreadsheet\Reader\IReader` instance using `\PhpOffice\PhpSpreadsheet\IOFactory` in automatic file type resolving mode using the following code sample: ```php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("05featuredemo.xlsx"); ``` A typical use of this feature is when you need to read files uploaded by your users, and you don’t know whether they are uploading xls or xlsx files. If you need to set some properties on the reader, (e.g. to only read data, see more about this later), then you may instead want to use this variant: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx"); $reader->setReadDataOnly(true); $reader->load("05featuredemo.xlsx"); ``` You can create a `\PhpOffice\PhpSpreadsheet\Reader\IReader` instance using `\PhpOffice\PhpSpreadsheet\IOFactory` in explicit mode using the following code sample: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx"); $spreadsheet = $reader->load("05featuredemo.xlsx"); ``` Note that automatic type resolving mode is slightly slower than explicit mode. ### Creating `\PhpOffice\PhpSpreadsheet\Writer\IWriter` using `\PhpOffice\PhpSpreadsheet\IOFactory` You can create a `\PhpOffice\PhpSpreadsheet\Writer\IWriter` instance using `\PhpOffice\PhpSpreadsheet\IOFactory`: ```php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx"); $writer->save("05featuredemo.xlsx"); ``` ## Excel 2007 (SpreadsheetML) file format Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting the in-memory spreadsheet to a .xlsx file. ### \PhpOffice\PhpSpreadsheet\Reader\Xlsx #### Reading a spreadsheet You can read an .xlsx file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load("05featuredemo.xlsx"); ``` #### Read data only You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $reader->setReadDataOnly(true); $spreadsheet = $reader->load("05featuredemo.xlsx"); ``` #### Read specific sheets only You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $reader->setLoadSheetsOnly(["Sheet 1", "My special sheet"]); $spreadsheet = $reader->load("05featuredemo.xlsx"); ``` #### Read specific cells only You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`. The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file: ```php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($columnAddress, $row, $worksheetName = '') { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; } return false; } } $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $reader->setReadFilter( new MyReadFilter() ); $spreadsheet = $reader->load("06largescale.xlsx"); ``` Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call `getCell()` for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value. Methods such as `toArray()` assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use `rangeToArray()` instead. ### \PhpOffice\PhpSpreadsheet\Writer\Xlsx #### Writing a spreadsheet You can write an .xlsx file using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); $writer->save("05featuredemo.xlsx"); ``` #### Formula pre-calculation By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.xlsx"); ``` **Note** Formulas will still be calculated in any column set to be autosized even if pre-calculated is set to false **Note** Prior to release 3.7.0, the use of this feature will cause Excel to be used in a mode where opening a sheet saved in this manner *might* not automatically recalculate a cell's formula when a cell used it the formula changes. Furthermore, that behavior might be applied to all spreadsheets open at the time. To avoid this behavior, add the following statement after `setPreCalculateFormulas` above: ```php $writer->setForceFullCalc(false); ``` Starting with Release 4.0.0, the property's default is changed to `false` and that statement is no longer be required. The property can be set to `null` if the old behavior is needed. #### Office 2003 compatibility pack Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation). You can enable Office2003 compatibility with the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); $writer->setOffice2003Compatibility(true); $writer->save("05featuredemo.xlsx"); ``` **Office2003 compatibility option should only be used when needed** because it disables several Office2007 file format options, resulting in a lower-featured Office2007 spreadsheet. #### Maximum Column Width In the Xlsx User Interface, the user cannot set a column width > 255. Nevertheless, it will honor a higher value if supplied in the Xml. PhpSpreadsheet will, by default, allow values > 255 to be written. However, Excel's behavior, restricting the value to 255, can be emulated: ```php $writer->setRestrictMaxColumnWidth(true); ``` ### Form Control Fields PhpSpreadsheet offers limited support for Forms Controls (buttons, checkboxes, etc.). The support is available only for Excel 2007 format, and is offered solely to allow loading a spreadsheet with such controls and saving it as a new file. Support is not available for adding such elements to the spreadsheet, nor even to locate them to determine their properties (so you can't modify or delete them). Modifications to a worksheet with controls are "caveat emptor"; some modifications will work correctly, but others are very likely to cause problems, e.g. adding a comment to the worksheet, or inserting or deleting rows or columns in a manner that would cause the controls to change location. ## Excel 5 (BIFF) file format Xls file format is the old Excel file format, implemented in PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls files. It is basically a modified version of [PEAR Spreadsheet\_Excel\_Writer](https://pear.php.net/package/Spreadsheet_Excel_Writer), although it has been extended and has fewer limitations and more features than the old PEAR library. This can read all BIFF versions that use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot read earlier versions. Xls file format will not be developed any further, it just provides an additional file format for PhpSpreadsheet. **Excel5 (BIFF) limitations** Please note that BIFF file format has some limits regarding to styling cells and handling large spreadsheets via PHP. ### \PhpOffice\PhpSpreadsheet\Reader\Xls #### Reading a spreadsheet You can read an .xls file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $spreadsheet = $reader->load("05featuredemo.xls"); ``` #### Read data only You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $reader->setReadDataOnly(true); $spreadsheet = $reader->load("05featuredemo.xls"); ``` #### Read specific sheets only You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $reader->setLoadSheetsOnly(["Sheet 1", "My special sheet"]); $spreadsheet = $reader->load("05featuredemo.xls"); ``` #### Read specific cells only You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`. The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file: ```php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($columnAddress, $row, $worksheetName = '') { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; } return false; } } $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $reader->setReadFilter( new MyReadFilter() ); $spreadsheet = $reader->load("06largescale.xls"); ``` ### \PhpOffice\PhpSpreadsheet\Writer\Xls #### Writing a spreadsheet You can write an .xls file using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet); $writer->save("05featuredemo.xls"); ``` ## Excel 2003 XML file format Excel 2003 XML file format is a file format which can be used in older versions of Microsoft Excel. **Excel 2003 XML limitations** Please note that Excel 2003 XML format has some limits regarding to styling cells and handling large spreadsheets via PHP. ### \PhpOffice\PhpSpreadsheet\Reader\Xml #### Reading a spreadsheet You can read an Excel 2003 .xml file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml(); $spreadsheet = $reader->load("05featuredemo.xml"); ``` #### Read specific cells only You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`. The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file: ```php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($columnAddress, $row, $worksheetName = '') { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; } return false; } } $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml(); $reader->setReadFilter( new MyReadFilter() ); $spreadsheet = $reader->load("06largescale.xml"); ``` ## Symbolic LinK (SYLK) Symbolic Link (SYLK) is a Microsoft file format typically used to exchange data between applications, specifically spreadsheets. SYLK files conventionally have a .slk suffix. Composed of only displayable ANSI characters, it can be easily created and processed by other applications, such as databases. **SYLK limitations** Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets via PHP. ### \PhpOffice\PhpSpreadsheet\Reader\Slk #### Reading a spreadsheet You can read an .slk file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk(); $spreadsheet = $reader->load("05featuredemo.slk"); ``` #### Read specific cells only You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`. The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file: ```php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($columnAddress, $row, $worksheetName = '') { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; } return false; } } $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk(); $reader->setReadFilter( new MyReadFilter() ); $spreadsheet = $reader->load("06largescale.slk"); ``` ## Open/Libre Office (.ods) Open Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files. ### \PhpOffice\PhpSpreadsheet\Reader\Ods #### Reading a spreadsheet You can read an .ods file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods(); $spreadsheet = $reader->load("05featuredemo.ods"); ``` #### Read specific cells only You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`. The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file: ```php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($columnAddress, $row, $worksheetName = '') { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; } return false; } } $reader = new PhpOffice\PhpSpreadsheet\Reader\Ods(); $reader->setReadFilter( new MyReadFilter() ); $spreadsheet = $reader->load("06largescale.ods"); ``` ## CSV (Comma Separated Values) CSV (Comma Separated Values) are often used as an import/export file format with other systems. PhpSpreadsheet allows reading and writing to CSV files. **CSV limitations** Please note that CSV file format has some limits regarding to styling cells, number formatting, ... ### \PhpOffice\PhpSpreadsheet\Reader\Csv #### Reading a CSV file You can read a .csv file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $spreadsheet = $reader->load('sample.csv'); ``` You can also treat a string as if it were the contents of a CSV file as follows: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $spreadsheet = $reader->loadSpreadsheetFromString($data); ``` #### Setting CSV options Often, CSV files are not really "comma separated", or use semicolon (`;`) as a separator. You can set some options before reading a CSV file. The separator will be auto-detected, so in most cases it should not be necessary to specify it. But in cases where auto-detection does not fit the use-case, then it can be set manually. Note that `\PhpOffice\PhpSpreadsheet\Reader\Csv` by default assumes that the loaded CSV file is UTF-8 encoded. If you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately. ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $reader->setInputEncoding('CP1252'); $reader->setDelimiter(';'); $reader->setEnclosure(''); $reader->setSheetIndex(0); $spreadsheet = $reader->load("sample.csv"); ``` You may also let PhpSpreadsheet attempt to guess the input encoding. It will do so based on a test for BOM (UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, or UTF-32LE), or by doing heuristic tests for those encodings, falling back to a specifiable encoding (default is CP1252) if all of those tests fail. ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $encoding = \PhpOffice\PhpSpreadsheet\Reader\Csv::guessEncoding('sample.csv'); // or, e.g. $encoding = \PhpOffice\PhpSpreadsheet\Reader\Csv::guessEncoding( // 'sample.csv', 'ISO-8859-2'); $reader->setInputEncoding($encoding); $reader->setDelimiter(';'); $reader->setEnclosure(''); $reader->setSheetIndex(0); $spreadsheet = $reader->load('sample.csv'); ``` You can also set the reader to guess the encoding rather than calling guessEncoding directly. In this case, the user-settable fallback encoding is used if nothing else works. ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $reader->setInputEncoding(\PhpOffice\PhpSpreadsheet\Reader\Csv::GUESS_ENCODING); $reader->setFallbackEncoding('ISO-8859-2'); // default CP1252 without this statement $reader->setDelimiter(';'); $reader->setEnclosure(''); $reader->setSheetIndex(0); $spreadsheet = $reader->load('sample.csv'); ``` The CSV reader will normally not load null strings into the spreadsheet. To load them: ```php $reader->setPreserveNullString(true); ``` Finally, you can set a callback to be invoked when the constructor is executed, either through `new Csv()` or `IOFactory::load`, and have that callback set the customizable attributes to whatever defaults are appropriate for your environment. ```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'); ``` #### Read a specific worksheet CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV: ```php $reader->setSheetIndex(0); ``` #### Read into existing spreadsheet When working with CSV files, it might occur that you want to import CSV data into an existing `Spreadsheet` object. The following code loads a CSV file into an existing `$spreadsheet` containing some sheets, and imports onto the 6th sheet: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $reader->setDelimiter(';'); $reader->setEnclosure('"'); $reader->setSheetIndex(5); $reader->loadIntoExisting("05featuredemo.csv", $spreadsheet); ``` #### Line endings Line endings for Unix (`\n`) and Windows (`\r\n`) are supported. Support for Mac line endings (`\r`) is deprecated since PHP 8.1, and is scheduled to remain deprecated for all later PHP8 releases; PhpSpreadsheet will continue to support them for PHP 8.*. Support is scheduled to be dropped with PHP 9; PhpSpreadsheet will then no longer handle CSV files with Mac line endings correctly. You can suppress testing for Mac line endings as follows: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); $reader->setTestAutoDetect(false); ``` Starting with Release 4.0.0, the property defaults to `false`, so the statement above is no longer needed. The old behavior can be enabled by setting the property to `true`. ### \PhpOffice\PhpSpreadsheet\Writer\Csv #### Writing a CSV file You can write a .csv file using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->save("05featuredemo.csv"); ``` #### Setting CSV options Often, CSV files are not really "comma separated", or use semicolon (`;`) as a separator. You can set some options before writing a CSV file: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->setDelimiter(';'); $writer->setEnclosure('"'); $writer->setLineEnding("\r\n"); $writer->setSheetIndex(0); $writer->save("05featuredemo.csv"); ``` #### CSV enclosures By default, all CSV fields are wrapped in the enclosure character, which defaults to double-quote. You can change to use the enclosure character only when required: ``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->setEnclosureRequired(false); $writer->save("05featuredemo.csv"); ``` #### Write a specific worksheet CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV: ```php $writer->setSheetIndex(0); ``` #### Formula pre-calculation By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.csv"); ``` #### Writing UTF-8 CSV files CSV files are written in UTF-8. If they do not contain characters outside the ASCII range, nothing else need be done. However, if such characters are in the file, or if the file starts with the 2 characters 'ID', it should explicitly include a BOM file header; if it doesn't, Excel will not interpret those characters correctly. This can be enabled by using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->setUseBOM(true); $writer->save("05featuredemo.csv"); ``` #### Writing CSV files with desired encoding It can be set to output with the encoding that can be specified by PHP's mb_convert_encoding. This looks like the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->setUseBOM(false); $writer->setOutputEncoding('SJIS-WIN'); $writer->save("05featuredemo.csv"); ``` #### Writing CSV files with varying numbers of columns A CSV file can have a different number of columns in each row. This differs from the default behavior when saving as a .csv in Excel, but can be enabled in PhpSpreadsheet by using the following code: ``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); $writer->setVariableColumns(true); $writer->save("05featuredemo.csv"); ``` #### Decimal and thousands separators If the worksheet you are exporting contains numbers with decimal or thousands separators then you should think about what characters you want to use for those before doing the export. By default PhpSpreadsheet looks up in the server's locale settings to decide what characters to use. But to avoid problems it is recommended to set the characters explicitly as shown below. English users will want to use this before doing the export: ```php \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator('.'); \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator(','); ``` German users will want to use the opposite values. ```php \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator(','); \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator('.'); ``` Note that the above code sets decimal and thousand separators as global options. This also affects how HTML and PDF is exported. ## HTML PhpSpreadsheet allows you to read or write a spreadsheet as HTML format, for quick representation of the data in it to anyone who does not have a spreadsheet application on their PC, or loading files saved by other scripts that simply create HTML markup and give it a .xls file extension. **HTML limitations** Please note that HTML file format has some limits regarding to styling cells, number formatting, ... Declared charsets compatible with ASCII in range 00-7F, and UTF-8/16 with BOM are supported. ### \PhpOffice\PhpSpreadsheet\Reader\Html #### Reading a spreadsheet You can read an .html or .htm file using the following code: ```php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html(); $spreadsheet = $reader->load("05featuredemo.html"); ``` **HTML limitations** Please note that HTML reader is still experimental and does not yet support merged cells or nested tables cleanly ### \PhpOffice\PhpSpreadsheet\Writer\Html Please note that `\PhpOffice\PhpSpreadsheet\Writer\Html` only outputs the first worksheet by default. #### Writing a spreadsheet You can write a .htm file using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet); $writer->save("05featuredemo.htm"); ``` #### Write all worksheets HTML files can contain one or more worksheets. If you want to write all sheets into a single HTML file, use the following code: ```php $writer->writeAllSheets(); ``` #### Write a specific worksheet HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML: ```php $writer->setSheetIndex(0); ``` #### Setting the images root of the HTML file There might be situations where you want to explicitly set the included images root. For example, instead of: ```html ``` You might want to see: ```html ``` You can use the following code to achieve this result: ```php $writer->setImagesRoot('http://www.example.com'); ``` #### Formula pre-calculation By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet); $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.htm"); ``` #### Embedding generated HTML in a web page There might be a situation where you want to embed the generated HTML in an existing website. \PhpOffice\PhpSpreadsheet\Writer\Html provides support to generate only specific parts of the HTML code, which allows you to use these parts in your website. Supported methods: - `generateHTMLHeader()` - `generateStyles()` - `generateSheetData()` - `generateHTMLFooter()` - `generateHTMLAll()` Here's an example which retrieves all parts independently and merges them into a resulting HTML page: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet); $hdr = $writer->generateHTMLHeader(); $sty = $writer->generateStyles(false); // do not write $newstyle = << $sty body { background-color: yellow; } EOF; echo preg_replace('@@', "$newstyle\n", $hdr); echo $writer->generateSheetData(); echo $writer->generateHTMLFooter(); ``` #### Editing HTML during save via a callback You can also add a callback function to edit the generated html before saving. For example, you could change the gridlines from a thin solid black line: ``` 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); ``` #### Decimal and thousands separators See section `\PhpOffice\PhpSpreadsheet\Writer\Csv` how to control the appearance of these. ## PDF PhpSpreadsheet allows you to write a spreadsheet into PDF format, for fast distribution of represented data. **PDF limitations** Please note that PDF file format has some limits regarding to styling cells, number formatting, ... ### \PhpOffice\PhpSpreadsheet\Writer\Pdf PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as TCPDF, mPDF or Dompdf. You must now install a PDF rendering library yourself; but PhpSpreadsheet will work with a number of different libraries. Currently, the following libraries are supported: | Library | Downloadable from | PhpSpreadsheet writer | |---------|-------------------------------------|-----------------------| | TCPDF | https://github.com/tecnickcom/tcpdf | Tcpdf | | mPDF | https://github.com/mpdf/mpdf | Mpdf | | Dompdf | https://github.com/dompdf/dompdf | Dompdf | The different libraries have different strengths and weaknesses. Some generate better formatted output than others, some are faster or use less memory than others, while some generate smaller .pdf files. It is the developers choice which one they wish to use, appropriate to their own circumstances. You can instantiate a writer with its specific name, like so: ```php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf'); ``` Or you can register which writer you are using with a more generic name, so you don't need to remember which library you chose, only that you want to write PDF files: ```php $class = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class; \PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', $class); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Pdf'); ``` Or you can instantiate directly the writer of your choice like so: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet); ``` #### Custom implementation or configuration If you need a custom implementation, or custom configuration, of a supported PDF library. You can extends the PDF library, and the PDF writer like so: ```php class My_Custom_TCPDF extends TCPDF { // ... } class My_Custom_TCPDF_Writer extends \PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf { protected function createExternalWriterInstance($orientation, $unit, $paperSize) { $instance = new My_Custom_TCPDF($orientation, $unit, $paperSize); // more configuration of $instance return $instance; } } \PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', MY_TCPDF_WRITER::class); ``` #### Writing a spreadsheet Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet); $writer->save("05featuredemo.pdf"); ``` Please note that `\PhpOffice\PhpSpreadsheet\Writer\Pdf` only outputs the first worksheet by default. #### Write all worksheets PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code: ```php $writer->writeAllSheets(); ``` #### Write a specific worksheet PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF: ```php $writer->setSheetIndex(0); ``` #### Setting Orientation and PaperSize PhpSpreadsheet will attempt to honor the orientation and paper size specified in the worksheet for each page it prints, if the renderer supports that. However, you can set all pages to have the same orientation and paper size, e.g. ```php $writer->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE); ``` #### Formula pre-calculation By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet); $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.pdf"); ``` #### Editing Pdf during save via a callback You can also add a callback function to edit the html used to generate the Pdf before saving. [See under Html](#editing-html-during-save-via-a-callback). #### Decimal and thousands separators See section `\PhpOffice\PhpSpreadsheet\Writer\Csv` how to control the appearance of these. ## Generating Excel files from templates (read, modify, write) Readers and writers are the tools that allow you to generate Excel files from templates. This requires less coding effort than generating the Excel file from scratch, especially if your template has many styles, page setup properties, headers etc. Here is an example how to open a template file, fill in a couple of fields and save it again: ```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'); ``` Notice that it is ok to load an xlsx file and generate an xls file. ## Generating Excel files from HTML content If you are generating an Excel file from pre-rendered HTML content you can do so automatically using the HTML Reader. This is most useful when you are generating Excel files from web application content that would be downloaded/sent to a user. For example: ```php $htmlString = '
Hello World
Hello
World
Hello
World
'; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html(); $spreadsheet = $reader->loadFromString($htmlString); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('write.xls'); ``` Suppose you have multiple worksheets you'd like created from html. This can be accomplished as follows. ```php $firstHtmlString = '
Hello World
'; $secondHtmlString = '
Hello World
'; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html(); $spreadsheet = $reader->loadFromString($firstHtmlString); $reader->setSheetIndex(1); $spreadsheet = $reader->loadFromString($secondHtmlString, $spreadsheet); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('write.xls'); ``` ## Reader/Writer Flags Some Readers and Writers support special "Feature Flags" that need to be explicitly enabled. An example of this is Charts in a spreadsheet. By default, when you load a spreadsheet that contains Charts, the charts will not be loaded. If all you want to do is read the data in the spreadsheet, then loading charts is an overhead for both speed of loading and memory usage. However, there are times when you may want to load any charts in the spreadsheet as well as the data. To do so, you need to tell the Reader explicitly to include Charts. ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx"); $reader->setIncludeCharts(true); $reader->load("spreadsheetWithCharts.xlsx"); ``` Alternatively, you can specify this in the call to load the spreadsheet: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("spreadsheetWithCharts.xlsx"); $reader->load("spreadsheetWithCharts.xlsx", $reader::LOAD_WITH_CHARTS); ``` If you wish to use the IOFactory `load()` method rather than instantiating a specific Reader, then you can still pass these flags. ```php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load( "spreadsheetWithCharts.xlsx", \PhpOffice\PhpSpreadsheet\Reader\IReader::LOAD_WITH_CHARTS ); ``` Flags that are available that can be passed to the Reader in this way include: - $reader::LOAD_WITH_CHARTS - $reader::READ_DATA_ONLY - $reader::IGNORE_EMPTY_CELLS - $reader::IGNORE_ROWS_WITH_NO_CELLS - $reader::ALLOW_EXTERNAL_IMAGES (starting with release 4.5) - $reader::DONT_ALLOW_EXTERNAL_IMAGES (starting with release 4.5) | Readers | LOAD
CHARTS | DATA
ONLY | IGNORE
EMPTY | IGNORE
ROWS | EXTERNAL
IMAGES | |----------|--------|------|--------|--------|--------| | Xlsx | YES | YES | YES | YES | YES | | Xls | NO | YES | YES | NO | NO | | Xml | NO | NO | NO | NO | NO | | Ods | NO | YES | NO | NO | NO | | Gnumeric | NO | YES | NO | NO | NO | | Html | N/A | N/A | N/A | N/A | YES | | Slk | N/A | NO | NO | NO | N/A | | Csv | N/A | NO | NO | NO | N/A | Likewise, when saving a file using a Writer, loaded charts will not be saved unless you explicitly tell the Writer to include them: ```php $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->setIncludeCharts(true); $writer->save('mySavedFileWithCharts.xlsx'); ``` As with the `load()` method, you can also pass flags in the `save()` method: ```php $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('mySavedFileWithCharts.xlsx', \PhpOffice\PhpSpreadsheet\Writer\IWriter::SAVE_WITH_CHARTS); ``` Flags that are available that can be passed to the Reader in this way include: - $reader::SAVE_WITH_CHARTS - $reader::DISABLE_PRECALCULATE_FORMULAE | Writers | SAVE_WITH_CHARTS | DISABLE_PRECALCULATE_FORMULAE | |---------|------------------|-------------------------------| | Xlsx | YES | YES | | Xls | NO | NO | | Ods | NO | YES | | Html | YES | YES | | Pdf | YES | YES | | Csv | N/A | YES | ### Combining Flags One benefit of flags is that you can pass several flags in a single method call. Two or more flags can be passed together using PHP's `|` operator. ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile('myExampleFile.xlsx'); $reader->load( 'spreadsheetWithCharts.xlsx', $reader::READ_DATA_ONLY | $reader::IGNORE_EMPTY_CELLS ); ``` ## Writing Data as a Plaintext Grid Although not really a spreadsheet format, it can be useful to write data in grid format to a plaintext file. Code like the following can be used: ```php $array = $sheet->toArray(null, true, true, true); $textGrid = new \PhpOffice\PhpSpreadsheet\Shared\TextGrid( $array, true, // true for cli, false for html // Starting with release 4.2, // the output format can be tweaked by uncommenting // any of the following 3 optional parameters. // rowDividers: true, // rowHeaders: false, // columnHeaders: false, // Starting with release 5.4: // numbersRight: TextGridRightAlign::numeric, ); $result = $textGrid->render(); ``` You can then echo `$result` to a terminal, or write it to a file with `file_put_contents`. The result will resemble: ``` +-----+------------------+---+----------+ | A | B | C | D | +---+-----+------------------+---+----------+ | 1 | 6 | 1900-01-06 00:00 | | 0.572917 | | 2 | 6 | TRUE | | 1<>2 | | 3 | xyz | xyz | | | +---+-----+------------------+---+----------+ ``` Please note that this may produce sub-optimal results for situations such as: - use of accents as combining characters rather than using pre-composed characters (may be handled by extending the class to override the `getString` or `strlen` methods) - Fullwidth characters - right-to-left characters (better display in a browser than a terminal on a non-RTL system) - multi-line strings ================================================ FILE: docs/topics/reading-files.md ================================================ # Reading Files ## Security XML-based formats such as OfficeOpen XML, Excel2003 XML, OASIS and Gnumeric are susceptible to XML External Entity Processing (XXE) injection attacks when reading spreadsheet files. This can lead to: - Disclosure whether a file is existent - Server Side Request Forgery - Command Execution (depending on the installed PHP wrappers) To prevent this, by default every XML-based Reader looks for XML entities declared inside the DOCTYPE and if any is found an exception is raised. Read more [about of XXE injection](https://websec.io/2012/08/27/Preventing-XXE-in-PHP.html). ## Loading a Spreadsheet File The simplest way to load a workbook file is to let PhpSpreadsheet's IO Factory identify the file type and load it, calling the static `load()` method of the `\PhpOffice\PhpSpreadsheet\IOFactory` class. ```php $inputFileName = './sampleData/example1.xls'; /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); ``` See `samples/Reader/01_Simple_file_reader_using_IOFactory.php` for a working example of this code. The `load()` method will attempt to identify the file type, and instantiate a loader for that file type; using it to load the file and store the data and any formatting in a `Spreadsheet` object. The method makes an initial guess at the loader to instantiate based on the file extension; but will test the file before actually executing the load: so if (for example) the file is actually a CSV file or contains HTML markup, but that has been given a .xls extension (quite a common practise), it will reject the Xls loader that it would normally use for a .xls file; and test the file using the other loaders until it finds the appropriate loader, and then use that to read the file. If you know that this is an `xls` file, but don't know whether it is a genuine BIFF-format Excel or Html markup with an xls extension, you can limit the loader to check only those two possibilities by passing in an array of Readers to test against. ```php $inputFileName = './sampleData/example1.xls'; $testAgainstFormats = [ \PhpOffice\PhpSpreadsheet\IOFactory::READER_XLS, \PhpOffice\PhpSpreadsheet\IOFactory::READER_HTML, ]; /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName, 0, $testAgainstFormats); ``` While easy to implement in your code, and you don't need to worry about the file type; this isn't the most efficient method to load a file; and it lacks the flexibility to configure the loader in any way before actually reading the file into a `Spreadsheet` object. ## Creating a Reader and Loading a Spreadsheet File If you know the file type of the spreadsheet file that you need to load, you can instantiate a new reader object for that file type, then use the reader's `load()` method to read the file to a `Spreadsheet` object. It is possible to instantiate the reader objects for each of the different supported filetype by name. However, you may get unpredictable results if the file isn't of the right type (e.g. it is a CSV with an extension of .xls), although this type of exception should normally be trapped. ```php $inputFileName = './sampleData/example1.xls'; /** Create a new Xls Reader **/ $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml(); // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods(); // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk(); // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Gnumeric(); // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/02_Simple_file_reader_using_a_specified_reader.php` for a working example of this code. Alternatively, you can use the IO Factory's `createReader()` method to instantiate the reader object for you, simply telling it the file type of the reader that you want instantiating. ```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); ``` See `samples/Reader/03_Simple_file_reader_using_the_IOFactory_to_return_a_reader.php` for a working example of this code. If you're uncertain of the filetype, you can use the `IOFactory::identify()` method to identify the reader that you need, before using the `createReader()` method to instantiate the reader object. ```php $inputFileName = './sampleData/example1.xls'; /** * Identify the type of $inputFileName. * See below for a possible improvement for release 4.1.0+. */ $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName); /** Create a new Reader of the type that has been identified **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/04_Simple_file_reader_using_the_IOFactory_to_identify_a_reader_to_use.php` for a working example of this code. Prior to release 4.1.0, `identify` returns a file type. It may be more useful to return a fully-qualified class name, which can be accomplished using a parameter introduced in 4.1.0: ```php $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName, null, true); ``` As with the IOFactory `load()` method, you can also pass an array of formats for the `identify()` method to check against if you know that it will only be in a subset of the possible formats that PhpSpreadsheet supports. ```php $inputFileName = './sampleData/example1.xls'; $testAgainstFormats = [ \PhpOffice\PhpSpreadsheet\IOFactory::READER_XLS, \PhpOffice\PhpSpreadsheet\IOFactory::READER_HTML, ]; /** Identify the type of $inputFileName **/ $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName, $testAgainstFormats); ``` You can also use this to confirm that a file is what it claims to be: ```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 } ``` ## Spreadsheet Reader Options Once you have created a reader object for the workbook that you want to load, you have the opportunity to set additional options before executing the `load()` method. All of these options can be set by calling the appropriate methods against the Reader (as described below), but some options (those with only two possible values) can also be set through flags, either by calling the Reader's `setFlags()` method, or passing the flags as an argument in the call to `load()`. Those options that can be set through flags are: Option | Flag | Default -------------------|-------------------------------------|------------------------ Empty Cells | IReader::IGNORE_EMPTY_CELLS | Load empty cells Rows with no Cells | IReader::IGNORE_ROWS_WITH_NO_CELLS | Load rows with no cells Data Only | IReader::READ_DATA_ONLY | Read data, structure and style Charts | IReader::LOAD_WITH_CHARTS | Don't read charts Several flags can be combined in a single call: ```php $inputFileType = 'Xlsx'; $inputFileName = './sampleData/example1.xlsx'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Set additional flags before the call to load() */ $reader->setFlags(IReader::IGNORE_EMPTY_CELLS | IReader::LOAD_WITH_CHARTS); $reader->load($inputFileName); ``` or ```php $inputFileType = 'Xlsx'; $inputFileName = './sampleData/example1.xlsx'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Set additional flags in the call to load() */ $reader->load($inputFileName, IReader::IGNORE_EMPTY_CELLS | IReader::LOAD_WITH_CHARTS); ``` ### Ignoring Empty Cells Many Excel files have empty rows or columns at the end of a worksheet, which can't easily be seen when looking at the file in Excel (Try using Ctrl-End to see the last cell in a worksheet). By default, PhpSpreadsheet will load these cells, because they are valid Excel values; but you may find that an apparently small spreadsheet requires a lot of memory for all those empty cells. If you are running into memory issues with seemingly small files, you can tell PhpSpreadsheet not to load those empty cells using the `setReadEmptyCells()` method. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader that we only want to load cell's that contain actual content **/ $reader->setReadEmptyCells(false); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` Note that cells containing formulae will still be loaded, even if that formula evaluates to a NULL or an empty string. Similarly, Conditional Styling might also hide the value of a cell; but cells that contain Conditional Styling or Data Validation will always be loaded regardless of their value. This option is available for the following formats: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | YES | Xls | YES | Xml | NO | Ods | NO | SYLK | NO | Gnumeric | NO | CSV | NO | HTML | NO This option is also available through flags. ### Ignoring Rows With No Cells Similar to the previous item, you can choose to ignore rows which contain no cells. This can also help with memory issues. ```php $inputFileType = 'Xlsx'; $inputFileName = './sampleData/example1.xlsx'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader that we do not want rows with no cells **/ $reader->setIgnoreRowsWithNoCells(true); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` This option is available only for Xlsx. It is also available through flags. ### Reading Only Data from a Spreadsheet File If you're only interested in the cell values in a workbook, but don't need any of the cell formatting information, then you can set the reader to read only the data values and any formulae from each cell using the `setReadDataOnly()` method. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader that we only want to load cell data **/ $reader->setReadDataOnly(true); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/05_Simple_file_reader_using_the_read_data_only_option.php` for a working example of this code. It is important to note that most Workbooks (and PhpSpreadsheet) store dates and times as simple numeric values: they can only be distinguished from other numeric values by the format mask that is applied to that cell. When setting read data only to true, PhpSpreadsheet doesn't read the cell format masks, so it is not possible to differentiate between dates/times and numbers. The Gnumeric loader has been written to read the format masks for date values even when read data only has been set to true, so it can differentiate between dates/times and numbers; but this change hasn't yet been implemented for the other readers. Reading Only Data from a Spreadsheet File applies to Readers: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | YES | Xls | YES | Xml | YES | Ods | YES | SYLK | NO | Gnumeric | YES | CSV | NO | HTML | NO This option is also available through flags. ### Reading Only Named WorkSheets from a File If your workbook contains a number of worksheets, but you are only interested in reading some of those, then you can use the `setLoadSheetsOnly()` method to identify those sheets you are interested in reading. To read a single sheet, you can pass that sheet name as a parameter to the `setLoadSheetsOnly()` method. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetname = 'Data Sheet #2'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader of which WorkSheets we want to load **/ $reader->setLoadSheetsOnly($sheetname); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/07_Simple_file_reader_loading_a_single_named_worksheet.php` for a working example of this code. If you want to read more than just a single sheet, you can pass a list of sheet names as an array parameter to the `setLoadSheetsOnly()` method. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetnames = ['Data Sheet #1','Data Sheet #3']; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader of which WorkSheets we want to load **/ $reader->setLoadSheetsOnly($sheetnames); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/08_Simple_file_reader_loading_several_named_worksheets.php` for a working example of this code. To reset this option to the default, you can call the `setLoadAllSheets()` method. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader to load all Worksheets **/ $reader->setLoadAllSheets(); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/06_Simple_file_reader_loading_all_worksheets.php` for a working example of this code. Reading Only Named WorkSheets from a File applies to Readers: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | YES | Xls | YES | Xml | YES | Ods | YES | SYLK | NO | Gnumeric | YES | CSV | NO | HTML | NO ### Reading Only Specific Columns and Rows from a File (Read Filters) If you are only interested in reading part of a worksheet, then you can write a filter class that identifies whether or not individual cells should be read by the loader. A read filter must implement the `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter` interface, and contain a `readCell()` method that accepts arguments of `$column`, `$row` and `$worksheetName`, and return a boolean true or false that indicates whether a workbook cell identified by those arguments should be read or not. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetname = 'Data Sheet #3'; /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($columnAddress, $row, $worksheetName = '') { // Read rows 1 to 7 and columns A to E only if ($row >= 1 && $row <= 7) { if (in_array($columnAddress,range('A','E'))) { return true; } } return false; } } /** Create an Instance of our Read Filter **/ $filterSubset = new MyReadFilter(); /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Tell the Reader that we want to use the Read Filter **/ $reader->setReadFilter($filterSubset); /** Load only the rows and columns that match our filter to Spreadsheet **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/09_Simple_file_reader_using_a_read_filter.php` for a working example of this code. This example is not particularly useful, because it can only be used in a very specific circumstance (when you only want cells in the range A1:E7 from your worksheet. A generic Read Filter would probably be more useful: ```php /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { private $startRow = 0; private $endRow = 0; private $columns = []; /** Get the list of rows and columns to read */ public function __construct($startRow, $endRow, $columns) { $this->startRow = $startRow; $this->endRow = $endRow; $this->columns = $columns; } public function readCell($columnAddress, $row, $worksheetName = '') { // Only read the rows and columns that were configured if ($row >= $this->startRow && $row <= $this->endRow) { if (in_array($columnAddress,$this->columns)) { return true; } } return false; } } /** Create an Instance of our Read Filter, passing in the cell range **/ $filterSubset = new MyReadFilter(9,15,range('G','K')); ``` See `samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php` for a working example of this code. This can be particularly useful for conserving memory, by allowing you to read and process a large workbook in "chunks": an example of this usage might be when transferring data from an Excel worksheet to a database. Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call `getCell()` for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value. Methods such as `toArray()` assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use `rangeToArray()` instead. ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example2.xls'; /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ class ChunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { private $startRow = 0; private $endRow = 0; /** Set the list of rows that we want to read */ public function setRows($startRow, $chunkSize) { $this->startRow = $startRow; $this->endRow = $startRow + $chunkSize; } public function readCell($columnAddress, $row, $worksheetName = '') { // Only read the heading row, and the configured rows if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { return true; } return false; } } /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Define how many rows we want to read for each "chunk" **/ $chunkSize = 2048; /** Create a new Instance of our Read Filter **/ $chunkFilter = new ChunkReadFilter(); /** Tell the Reader that we want to use the Read Filter **/ $reader->setReadFilter($chunkFilter); /** Loop to read our worksheet in "chunk size" blocks **/ for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) { /** Tell the Read Filter which rows we want this iteration **/ $chunkFilter->setRows($startRow,$chunkSize); /** Load only the rows that match our filter **/ $spreadsheet = $reader->load($inputFileName); // Do some processing here } ``` See `samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_` for a working example of this code. Using Read Filters applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | YES | Xls | YES | Xml | YES | Ods | YES | SYLK | NO | Gnumeric | YES | CSV | YES | HTML | NO | | | ### Combining Multiple Files into a Single Spreadsheet Object While you can limit the number of worksheets that are read from a workbook file using the `setLoadSheetsOnly()` method, certain readers also allow you to combine several individual "sheets" from different files into a single `Spreadsheet` object, where each individual file is a single worksheet within that workbook. For each file that you read, you need to indicate which worksheet index it should be loaded into using the `setSheetIndex()` method of the `$reader`, then use the `loadIntoExisting()` method rather than the `load()` method to actually read the file into that worksheet. ```php $inputFileType = 'Csv'; $inputFileNames = [ './sampleData/example1.csv', './sampleData/example2.csv' './sampleData/example3.csv' ]; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Extract the first named file from the array list **/ $inputFileName = array_shift($inputFileNames); /** Load the initial file to the first worksheet in a `Spreadsheet` Object **/ $spreadsheet = $reader->load($inputFileName); /** Set the worksheet title (to the filename that we've loaded) **/ $spreadsheet->getActiveSheet() ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); /** Loop through all the remaining files in the list **/ foreach($inputFileNames as $sheet => $inputFileName) { /** Increment the worksheet index pointer for the Reader **/ $reader->setSheetIndex($sheet+1); /** Load the current file into a new worksheet in Spreadsheet **/ $reader->loadIntoExisting($inputFileName,$spreadsheet); /** Set the worksheet title (to the filename that we've loaded) **/ $spreadsheet->getActiveSheet() ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); } ``` See `samples/Reader/13_Simple_file_reader_for_multiple_CSV_files.php` for a working example of this code. Note that using the same sheet index for multiple sheets won't append files into the same sheet, but overwrite the results of the previous load. You cannot load multiple CSV files into the same worksheet. Combining Multiple Files into a Single Spreadsheet Object applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | NO | Xls | NO | Xml | NO | Ods | NO | SYLK | YES | Gnumeric | NO | CSV | YES | HTML | NO ### Combining Read Filters with the `setSheetIndex()` method to split a large CSV file across multiple Worksheets An Xls BIFF .xls file is limited to 65536 rows in a worksheet, while the Xlsx Microsoft Office Open XML SpreadsheetML .xlsx file is limited to 1,048,576 rows in a worksheet; but a CSV file is not limited other than by available disk space. This means that we wouldn’t ordinarily be able to read all the rows from a very large CSV file that exceeded those limits, and save it as an Xls or Xlsx file. However, by using Read Filters to read the CSV file in "chunks" (using the ChunkReadFilter Class that we defined in [the above section](#reading-only-specific-columns-and-rows-from-a-file-read-filters), and the `setSheetIndex()` method of the `$reader`, we can split the CSV file across several individual worksheets. ```php $inputFileType = 'Csv'; $inputFileName = './sampleData/example2.csv'; echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'
'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Define how many rows we want to read for each "chunk" **/ $chunkSize = 65530; /** Create a new Instance of our Read Filter **/ $chunkFilter = new ChunkReadFilter(); /** Tell the Reader that we want to use the Read Filter **/ /** and that we want to store it in contiguous rows/columns **/ $reader->setReadFilter($chunkFilter) ->setContiguous(true); /** Instantiate a new Spreadsheet object manually **/ $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); /** Set a sheet index **/ $sheet = 0; /** Loop to read our worksheet in "chunk size" blocks **/ /** $startRow is set to 2 initially because we always read the headings in row #1 **/ for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) { /** Tell the Read Filter which rows we want to read this loop **/ $chunkFilter->setRows($startRow,$chunkSize); /** Increment the worksheet index pointer for the Reader **/ $reader->setSheetIndex($sheet); /** Load only the rows that match our filter into a new worksheet **/ $reader->loadIntoExisting($inputFileName,$spreadsheet); /** Set the worksheet title for the sheet that we've justloaded) **/ /** and increment the sheet index as well **/ $spreadsheet->getActiveSheet()->setTitle('Country Data #'.(++$sheet)); } ``` See `samples/Reader/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php` for a working example of this code. This code will read 65,530 rows at a time from the CSV file that we’re loading, and store each "chunk" in a new worksheet. The `setContiguous()` method for the Reader is important here. It is applicable only when working with a Read Filter, and identifies whether or not the cells should be stored by their position within the CSV file, or their position relative to the filter. For example, if the filter returned true for cells in the range B2:C3, then with setContiguous set to false (the default) these would be loaded as B2:C3 in the `Spreadsheet` object; but with setContiguous set to true, they would be loaded as A1:B2. Splitting a single loaded file across multiple worksheets applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | NO | Xls | NO | Xml | NO | Ods | NO | SYLK | NO | Gnumeric | NO | CSV | YES | HTML | NO ### Pipe or Tab Separated Value Files The CSV loader will attempt to auto-detect the separator used in the file. If it cannot auto-detect, it will default to the comma. If this does not fit your use-case, you can manually specify a separator by using the `setDelimiter()` method. ```php $inputFileType = 'Csv'; $inputFileName = './sampleData/example1.tsv'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Set the delimiter to a TAB character **/ $reader->setDelimiter("\t"); // $reader->setDelimiter('|'); /** Load the file to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/15_Simple_file_reader_for_tab_separated_value_file_using_the_Advanced_Value_Binder.php` for a working example of this code. In addition to the delimiter, you can also use the following methods to set other attributes for the data load: Method | Default -------------------|---------- setEnclosure() | `"` setInputEncoding() | `UTF-8` Setting CSV delimiter applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | NO | Xls | NO | Xml | NO | Ods | NO | SYLK | NO | Gnumeric | NO | CSV | YES | HTML | NO ### Reading formatted Numbers from a CSV File Unfortunately, numbers in a CSV file may be formatted as strings. If that number is a simple integer or float (with a decimal `.` separator) without any thousands separator, then it will be treated as a number. However, if the value has a thousands separator (e.g. `12,345`), or a decimal separator that isn't a `.` (e.g. `123,45` for a European locale), then it will be loaded as a string with that formatting. If you want the Csv Reader to convert that value to a numeric when it loads the file, the you need to tell it to do so. The `castFormattedNumberToNumeric()` lets you do this. (Assuming that our server is configured with German locale settings: otherwise it may be necessary to call `setlocale()` before loading the file.) ```php $inputFileType = 'Csv'; $inputFileName = './sampleData/example1.de.csv'; /** It may be necessary to call setlocale() first if this is not your default locale */ // setlocale(LC_ALL, 'de_DE.UTF-8', 'deu_deu'); /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Enable loading numeric values formatted with German , decimal separator and . thousands separator **/ $reader->castFormattedNumberToNumeric(true); /** Load the file to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` This will attempt to load those formatted numeric values as numbers, based on the server's locale settings. If you want to load those values as numbers, but also to retain the formatting as a number format mask, then you can pass a boolean `true` as a second argument to the `castFormattedNumberToNumeric()` method to tell the Reader to identify the format masking to use for that value. This option does have an arbitrary limit of 6 decimal places. If your Csv file includes other formats for numbers (currencies, scientific format, etc); then you should probably also use the Advanced Value Binder to handle these cases. Applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| Xlsx | NO | Xls | NO | Xml | NO | Ods | NO | SYLK | NO | Gnumeric | NO | CSV | YES | HTML | NO ## A Brief Word about the Advanced Value Binder When loading data from a file that contains no formatting information, such as a CSV file, then data is read either as strings or numbers (float or integer). This means that PhpSpreadsheet does not automatically recognise dates/times (such as `16-Apr-2009` or `13:30`), booleans (`true` or `false`), percentages (`75%`), hyperlinks (`https://www.example.com`), etc as anything other than simple strings. However, you can apply additional processing that is executed against these values during the load process within a Value Binder. A Value Binder is a class that implement the `\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` interface. It must contain a `bindValue()` method that accepts a `\PhpOffice\PhpSpreadsheet\Cell\Cell` and a value as arguments, and return a boolean `true` or `false` that indicates whether the workbook cell has been populated with the value or not. The Advanced Value Binder implements such a class: amongst other tests, it identifies a string comprising "TRUE" or "FALSE" (based on locale settings) and sets it to a boolean; or a number in scientific format (e.g. "1.234e-5") and converts it to a float; or dates and times, converting them to their Excel timestamp value – before storing the value in the cell object. It also sets formatting for strings that are identified as dates, times or percentages. It could easily be extended to provide additional handling (including text or cell formatting) when it encountered a hyperlink, or HTML markup within a CSV file. So using a Value Binder allows a great deal more flexibility in the loader logic when reading unformatted text files. ```php $inputFileType = 'Csv'; $inputFileName = './sampleData/example1.tsv'; $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $reader->setDelimiter("\t"); /** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/ // Old method using static property \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); // Preferred method using dynamic property since 3.4.0 $reader::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); $spreadsheet = $reader->load($inputFileName); ``` See `samples/Reader/15_Simple_file_reader_for_tab_separated_value_file_using_the_Advanced_Value_Binder.php` for a working example of this code. Loading using a Value Binder applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N ----------|:---:|--------|:---:|--------------|:---: Xlsx | NO | Xls | NO | Xml | NO Ods | NO | SYLK | YES | Gnumeric | NO CSV | YES | HTML | YES Note that you can also use the Binder to determine how PhpSpreadsheet identified datatypes for values when you set a cell value without explicitly setting a datatype. Value Binders can also be used to set formatting for a cell appropriate to the value. ## Error Handling Of course, you should always apply some error handling to your scripts as well. PhpSpreadsheet throws exceptions, so you can wrap all your code that accesses the library methods within Try/Catch blocks to trap for any problems that are encountered, and deal with them in an appropriate manner. The PhpSpreadsheet Readers throw a `\PhpOffice\PhpSpreadsheet\Reader\Exception`. ```php $inputFileName = './sampleData/example-1.xls'; try { /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); } catch(\PhpOffice\PhpSpreadsheet\Reader\Exception $e) { die('Error loading file: '.$e->getMessage()); } ``` See `samples/Reader/16_Handling_loader_exceptions_using_TryCatch.php` for a working example of this code. ## Helper Methods You can retrieve a list of worksheet names contained in a file without loading the whole file by using the Reader’s `listWorksheetNames()` method; similarly, a `listWorksheetInfo()` method will retrieve the dimensions of worksheet in a file without needing to load and parse the whole file. ### listWorksheetNames The `listWorksheetNames()` method returns a simple array listing each worksheet name within the workbook: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $worksheetNames = $reader->listWorksheetNames($inputFileName); echo '

Worksheet Names

'; echo '
    '; foreach ($worksheetNames as $worksheetName) { echo '
  1. ', $worksheetName, '
  2. '; } echo '
'; ``` See `samples/Reader/18_Reading_list_of_worksheets_without_loading_entire_file.php` for a working example of this code. ### listWorksheetInfo The `listWorksheetInfo()` method returns a nested array, with each entry listing the name, dimensions and state for a worksheet: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $worksheetData = $reader->listWorksheetInfo($inputFileName); echo '

Worksheet Information

'; echo '
    '; foreach ($worksheetData as $worksheet) { echo '
  1. ', $worksheet['worksheetName'], '
    '; echo 'Rows: ', $worksheet['totalRows'], ' Columns: ', $worksheet['totalColumns'], '
    '; echo 'Cell Range: A1:', $worksheet['lastColumnLetter'], $worksheet['totalRows'], '
    '; echo 'Sheet state: ', $worksheet['sheetState']; echo '
  2. '; } echo '
'; ``` See `samples/Reader/19_Reading_worksheet_information_without_loading_entire_file.php` for a working example of this code. ================================================ FILE: docs/topics/recipes.md ================================================ # Recipes The following pages offer you some widely-used PhpSpreadsheet recipes. Please note that these do NOT offer complete documentation on specific PhpSpreadsheet API functions, but just a bump to get you started. If you need specific API functions, please refer to the [API documentation](https://phpoffice.github.io/PhpSpreadsheet). For example, [setting a worksheet's page orientation and size ](#setting-a-worksheets-page-orientation-and-size) covers setting a page orientation to A4. Other paper formats, like US Letter, are not covered in this document, but in the PhpSpreadsheet [API documentation](https://phpoffice.github.io/PhpSpreadsheet). My apologies if this documentation seems very basic to some of you; but I spend so much time having to provide help lessons in PHP 101 and Excel 101 that I feel I need to provide this level of very simple detail. ## Setting a spreadsheet's metadata PhpSpreadsheet allows an easy way to set a spreadsheet's metadata, using document property accessors. Spreadsheet metadata can be useful for finding a specific document in a file repository or a document management system. For example Microsoft Sharepoint uses document metadata to search for a specific document in its document lists.
Click here for details of Spreadsheet Document Properties These are accessed in MS Excel from the "Info" option on the "File" menu: ![99-Properties_File-Menu.png](images%2F99-Properties_File-Menu.png) Some of these properties can be edited "in situ" in the Properties Block: ![99-Properties_Block.png](images%2F99-Properties_Block.png) For more advanced properties, click on the "Properties" dropdown: ![99-Properties_Advanced.png](images%2F99-Properties_Advanced.png) And you will be able to add/edit/delete a lot of different property values. ![99-Properties_Advanced-Form.png](images%2F99-Properties_Advanced-Form.png) Properties on the "General", "Statistics" and "Contents" tabs are informational, and cannot be user-defined in Excel itself. Properties on the "Summary" tab are all string values. The "Custom" tab allows you to define your own properties. More information from the Microsoft Documentation can be found [here](https://support.microsoft.com/en-us/office/view-or-change-the-properties-for-an-office-file-21d604c2-481e-4379-8e54-1dd4622c6b75). ![99-Properties_Advanced-Form-2.png](images%2F99-Properties_Advanced-Form-2.png) You can select a property name from the dropdown, or type a new name of your choice; select a Type; enter a value; and then click on "Add". The new property will then be created and displayed in the list at the bottom of the form. While "Text", "Number" (can be an integer or a floating point value) and "Yes or No" types are straightforward to add a value, "Date" types are more difficult, and Microsoft provide very little help. However, you need to enter the date in the format that matches your locale, so an American would enter "7/4/2023 for the 4th of July; but in the UK I would enter "4/7/2023" for the same date. Although typically recognised as a date elsewhere in MS Excel, the almost universally recognised `2022-12-31` date format is not recognised as valid here.
Setting spreadsheet metadata in PhpSpreadsheet is done as follows: ```php $spreadsheet->getProperties() ->setCreator("Maarten Balliauw") ->setLastModifiedBy("Mark Baker") ->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"); ``` You can choose which properties to set or ignore.
Click here for details of Property Getters/Setters PhpSpreadsheet provides specific getters/setters for a number of pre-defined properties. | Property Name | DataType | Getter/Setter | Notes | |------------------|-------------------------|----------------------------------------------|-----------------------------------------------------------| | Creator | string | getCreator()
setCreator() | | | Last Modified By | string | getLastModifiedBy()
setLastModifiedBy() | | | Created | float/int
timestamp | getCreated()
setCreated() | Cannot be modified in MS Excel; but is automatically set. | | Modified | float/int
timestamp | getModified()
setModified() | Cannot be modified in MS Excel; but is automatically set. | | Title | string | getTitle()
setTitle() | | | Description | string | getDescription()
setDescription() | | | Subject | string | getSubject()
setSubject() | | | Keywords | string | getKeywords()
setKeywords() | | | Category | string | getCategory()
setCategory() | Not supported in xls files. | | Company | string | getCompany()
setCompany() | Not supported in xls files. | | Manager | string | getManager()
setManager() | Not supported in xls files. | > **Note:** Not all Spreadsheet File Formats support all of these properties. > For example: "Category", "Company" and "Manager" are not supported in `xls` files.
Click here for details of Custom Properties Additionally, PhpSpreadsheet supports the creation and reading of custom properties for those file formats that accept custom properties. The following methods of the Properties class can be used when working with custom properties. - `getCustomProperties()`
Will return an array listing the names of all custom properties that are defined. - `isCustomPropertySet(string $propertyName)`
Will return a boolean indicating if the named custom property is defined. - `getCustomPropertyValue(string $propertyName)`
Will return the "raw" value of the named custom property; or null if the property doesn't exist. - `getCustomPropertyType(string $propertyName)`
Will return the datatype of the named custom property; or null if the property doesn't exist. - `setCustomProperty(string $propertyName, $propertyValue = '', $propertyType = null)`
Will let you set (or modify) a custom property. If you don't provide a datatype, then PhpSpreadsheet will attempt to identify the datatype from the value that you set. The recognised Property Types are: | Constant | Datatype | Value | |-----------------------------------|----------|-------| | Properties::PROPERTY_TYPE_BOOLEAN | boolean | b | | Properties::PROPERTY_TYPE_INTEGER | integer | i | | Properties::PROPERTY_TYPE_FLOAT | float | f | | Properties::PROPERTY_TYPE_DATE | date | d | | Properties::PROPERTY_TYPE_STRING | string | s | When reading property types, you might also encounter: | Datatype | Value | |----------|--------------| | null | null value | | empty | empty string | | u | unknown | Other more complex types, such as pointers and filetime, are not supported by PhpSpreadsheet; and are discarded when reading a file.
```php $spreadsheet->getProperties() ->setCustomProperty('Editor', 'Mark Baker') ->setCustomProperty('Version', 1.17) ->setCustomProperty('Tested', true) ->setCustomProperty('Test Date', '2021-03-17', Properties::PROPERTY_TYPE_DATE); ``` > **Warning:** If the datatype for a date is not explicitly used, then it will be treated as a string. > **Note:** Although MS Excel doesn't recognise `2022-12-31` as valid date format when entering Custom Date Properties, PhpSpreadsheet will accept it. ## Setting a spreadsheet's active sheet A Spreadsheet consists of (very rarely) none, one or more Worksheets. If you have 1 or more Worksheets, then one (and only one) of those Worksheets can be "Active" (viewed or updated) at a time, but there will always be an "Active" Worksheet (unless you explicitly delete all of the Worksheets in the Spreadsheet).
Click here for details about Worksheets When you create a new Spreadsheet in MS Excel, it creates the Spreadsheet with a single Worksheet ("Sheet1") ![101-Basic-Spreadsheet-with-Worksheet.png](images%2F101-Basic-Spreadsheet-with-Worksheet.png) and that is the "Active" Worksheet. ![101-Active-Worksheet-1.png](images%2F101-Active-Worksheet-1.png) This is the same as ```php $spreadsheet = new Spreadsheet(); $activeWorksheet = $spreadsheet->getActiveSheet(); ``` in PhpSpreadsheet. And you can then write values to Cells in `$activeWorksheet` (`Sheet1`). To create a new Worksheet in MS Excel, you click on the "+" button in the Worksheet Tab Bar. MS Excel will then create a new Worksheet ("Sheet2") in the Spreadsheet, and make that the current "Active" Worksheet. ![101-Active-Worksheet-2.png](images%2F101-Active-Worksheet-2.png) Excel always shows the "Active" Worksheet in the Grid, and you can see which Worksheet is "Active" because it is highlighted in the Worksheet Tab Bar at the bottom of the Worksheet Grid. This is the same as ```php $activeWorksheet = $spreadsheet->createSheet(); ``` in PhpSpreadsheet. And you can then write values to Cells in `$activeWorksheet` (`Sheet2`).
To switch between Worksheets in MS Excel, you click on the Tab for the Worksheet that you want to be "Active" in the Worksheet Tab Bar. Excel will then set that as the "Active" Worksheet. ![101-Active-Worksheet-Change.png](images%2F101-Active-Worksheet-Change.png) In PhpSpreadsheet, you do this by calling the Spreadsheet's `setActiveSheetIndex()` methods. Either: ```php $activeWorksheet = $spreadsheet->setActiveSheetIndexByName('Sheet1') ``` using the name/title of the Worksheet that you want as the "Active" Worksheet. Or: ```php $activeWorksheet = $spreadsheet->setActiveSheetIndex(0); ``` Where you set the "Active" Worksheet by its position in the Worksheet Tab Bar, with 0 as the first Worksheet, 1 as the second, etc. And you can then write values to Cells in `$activeWorksheet` (`Sheet1`) again. You don't have to assign the return value from calls to `createSheet()` and `setActiveSheetIndex()` to a variable, but it means that you can call Worksheet methods directly against `$activeWorksheet`, rather than having to call `$spreadsheet->getActiveSheet()` all the time. And, unlike MS Excel where you can only update Cells in the "Active" Worksheet; PhpSpreadsheet allows you to update Cells in any Worksheet: ```php // Create a Spreadsheet, with Worksheet Sheet1, which is the Active Worksheet $spreadsheet = new Spreadsheet(); // Assign the Active Worksheet (Sheet1) to $worksheet1 $worksheet1 = $spreadsheet->getActiveSheet(); // Create a new Worksheet (Sheet2) and make that the Active Worksheet $worksheet2 = $spreadsheet->createSheet(); $worksheet1->setCellValue('A1', 'I am a cell on Sheet1'); $worksheet2->setCellValue('A1', 'I am a cell on Sheet2'); ``` ## Write a date or time into a cell In Excel, dates and Times are stored as numeric values counting the number of days elapsed since 1900-01-01. For example, the date '2008-12-31' is represented as 39813. You can verify this in Microsoft Office Excel by entering that date in a cell and afterwards changing the number format to 'General' so the true numeric value is revealed. Likewise, '3:15 AM' is represented as 0.135417. PhpSpreadsheet works with UST (Universal Standard Time) date and Time values, but does no internal conversions; so it is up to the developer to ensure that values passed to the date/time conversion functions are UST. Writing a date value in a cell consists of 2 lines of code. Select the method that suits you the best. Here are some examples: ```php // MySQL-like timestamp '2008-12-31' or date string // Old method using static property \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); // Preferred method using dynamic property since 3.4.0 $spreadsheet->setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); $spreadsheet->getActiveSheet() ->setCellValue('D1', '2008-12-31'); $spreadsheet->getActiveSheet()->getStyle('D1') ->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH); // PHP-time (Unix time) $time = gmmktime(0,0,0,12,31,2008); // int(1230681600) $spreadsheet->getActiveSheet() ->setCellValue('D1', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($time)); $spreadsheet->getActiveSheet()->getStyle('D1') ->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH); // Excel-date/time $spreadsheet->getActiveSheet()->setCellValue('D1', 39813) $spreadsheet->getActiveSheet()->getStyle('D1') ->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH); ``` The above methods for entering a date all yield the same result. The `\PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel()` method will also work with a PHP DateTime object; or with strings containing different well-recognised date formats (although this is limited in the same ways as using the Advanced Value Binder). Similarly, times (or date and time values) can be entered in the same fashion: just remember to use an appropriate format code. > **Note:** See section "Using value binders to facilitate data entry" to learn more about the AdvancedValueBinder used in the first example. Excel can also operate in a 1904-based calendar (default for workbooks saved on Mac). Normally, you do not have to worry about this when using PhpSpreadsheet. `\PhpOffice\PhpSpreadsheet\Style\NumberFormat` provides a number of pre-defined date formats; but this is just a string value, and you can define your own values as long as they are a valid MS Excel format. PhpSpreadsheet also provides a number of Wizards to help you create Date, Time and DateTime format masks.
Click here for an example of the Date/Time Wizards ```php use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Date as DateWizard; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Time as TimeWizard; use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\DateTime as DateTimeWizard; $spreadsheet->getActiveSheet()->setCellValue('A1', '=NOW()') $spreadsheet->getActiveSheet()->setCellValue('A2', '=NOW()') $spreadsheet->getActiveSheet()->setCellValue('A3', '=NOW()') // yyyy-mm-dd $dateFormat = new DateWizard( DateWizard::SEPARATOR_DASH, DateWizard::YEAR_FULL, DateWizard::MONTH_NUMBER_LONG, DateWizard::DAY_NUMBER_LONG ); $spreadsheet->getActiveSheet()->getStyle('A1') ->getNumberFormat() ->setFormatCode($dateFormat); // hh:mm $timeFormat = new TimeWizard( TimeWizard::SEPARATOR_COLON, TimeWizard::HOURS_LONG, TimeWizard::MINUTES_LONG, ); $spreadsheet->getActiveSheet()->getStyle('A2') ->getNumberFormat() ->setFormatCode($timeFormat); // yyyy-mm-dd hh:mm $dateTimeFormat = new DateTimeWizard(' ', $dateFormat, $timeFormat); $spreadsheet->getActiveSheet()->getStyle('A3') ->getNumberFormat() ->setFormatCode($dateTimeFormat); ```
## Write a formula into a cell Inside the Excel file, formulas are always stored as they would appear in an English version of Microsoft Office Excel, and PhpSpreadsheet handles all formulas internally in this format. This means that the following rules hold: - Decimal separator is `.` (period) - Function argument separator is `,` (comma) - Matrix row separator is `;` (semicolon) - English function names must be used This is regardless of which language version of Microsoft Office Excel may have been used to create the Excel file. When the final workbook is opened by the user, Microsoft Office Excel will take care of displaying the formula according the applications language. Translation is taken care of by the application! The following line of code writes the formula `=IF(C4>500,"profit","loss")` into the cell B8. Note that the formula must start with `=` to make PhpSpreadsheet recognise this as a formula. ```php $spreadsheet->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")'); ``` If you want to write a string beginning with an `=` character to a cell, then you should use the `setCellValueExplicit()` method. ```php $spreadsheet->getActiveSheet() ->setCellValueExplicit( 'B8', '=IF(C4>500,"profit","loss")', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING ); ``` A cell's formula can be read again using the following line of code: ```php $formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue(); ``` If you need the calculated value of a cell, use the following code. This is further explained in [the calculation engine](./calculation-engine.md). ```php $value = $spreadsheet->getActiveSheet()->getCell('B8')->getCalculatedValue(); ``` ### Array Formulas With version 3.0.0 of PhpSpreadsheet, we've introduced support for Excel "array formulas". **It is an opt-in feature.** You need to enable it with the following code: ```php // preferred method \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance($spreadsheet) ->setInstanceArrayReturnType( \PhpOffice\PhpSpreadsheet\Calculation\Calculation::RETURN_ARRAY_AS_ARRAY); // or less preferred \PhpOffice\PhpSpreadsheet\Calculation\Calculation::setArrayReturnType( \PhpOffice\PhpSpreadsheet\Calculation\Calculation::RETURN_ARRAY_AS_ARRAY); ``` This is not a new constant, and setArrayReturnType is also not new, but it has till now not had much effect. The instance variable set by the new setInstanceArrayReturnType will always be checked first, and the static variable used only if the instance variable is uninitialized. As a basic example, let's look at a receipt for buying some fruit: ![12-CalculationEngine-Basic-Formula.png](./images/12-CalculationEngine-Basic-Formula.png) We can provide a "Cost" formula for each row of the receipt by multiplying the "Quantity" (column `B`) by the "Price" (column `C`); so for the "Apples" in row `2` we enter the formula `=$B2*$C2`. In PhpSpreadsheet, we would set this formula in cell `D2` using: ```php $spreadsheet->getActiveSheet()->setCellValue('D2','=$B2*$C2'); ``` and then do the equivalent for rows `3` to `6`. To calculate the "Total", we would use a different formula, telling it to calculate the sum value of rows 2 to 6 in the "Cost" column: ![12-CalculationEngine-Basic-Formula-2.png](./images/12-CalculationEngine-Basic-Formula-2.png) I'd imagine that most developers are familiar with this: we're setting a formula that uses an Excel function (the `SUM()` function) and specifying a range of cells to include in the sum (`$D$2:$D6`) ```php $spreadsheet->getActiveSheet()->setCellValue('D7','=SUM($D$2:$D6'); ``` However, we could have specified an alternative formula to calculate that result, using the arrays of the "Quantity" and "Cost" columns multiplied directly, and then summed together: ![12-CalculationEngine-Array-Formula.png](./images/12-CalculationEngine-Array-Formula.png) Entering the formula `=SUM(B2:B6*C2:C6)` will calculate the same result; but because it's using arrays, we need to enter it as an "array formula". In MS Excel itself, we'd do this by using `Ctrl-Shift-Enter` rather than simply `Enter` when we define the formula in the formula edit box. MS Excel then shows that this is an array formula in the formula edit box by wrapping it in the `{}` braces (you don't enter these in the formula yourself; MS Excel does it). **In recent releases of Excel, Ctrl-Shift-Enter is not required, and Excel does not add the braces. PhpSpreadsheet will attempt to behave like the recent releases.** Or to identify the biggest increase in like-for-like sales from one month to the next: ![12-CalculationEngine-Array-Formula-3.png](./images/12-CalculationEngine-Array-Formula-3.png) ```php $spreadsheet->getActiveSheet()->setCellValue('F1','=MAX(B2:B6-C2:C6)'); ``` Which tells us that the biggest increase in sales between December and January was 30 more (in this case, 30 more Lemons). --- These are examples of array formula where the results are displayed in a single cell; but other array formulas might be displayed across several cells. As an example, consider transposing a grid of data: MS Excel provides the `TRANSPOSE()` function for that purpose. Let's transpose our shopping list for the fruit: ![12-CalculationEngine-Array-Formula-2.png](./images/12-CalculationEngine-Array-Formula-2.png) When we do this in MS Excel, we used to need to indicate ___all___ the cells that will contain the transposed data from cells `A1` to `D7`. We do this by selecting the cells where we want to display our transposed data either by holding the left mouse button down while we move with the mouse, or pressing `Shift` and using the arrow keys. Once we've selected all the cells to hold our data, then we enter the formula `TRANSPOSE(A1:D7)` in the formula edit box, remembering to use `Ctrl-Shift-Enter` to tell MS Excel that this is an array formula. In recent Excel, you can just enter `=TRANSPOSE(A1:D7)` into cell A10. Note also that we still set this as the formula for the top-left cell of that range, cell `A10`. Simply setting an array formula in a cell and specifying the range won't populate the spillage area for that formula. ```php $spreadsheet->getActiveSheet() ->setCellValue( 'A10', '=SEQUENCE(3,3)' ); // Will return a null, because the formula for A1 hasn't been calculated to populate the spillage area $result = $spreadsheet->getActiveSheet()->getCell('C3')->getValue(); ``` To do that, we need to retrieve the calculated value for the cell. ```php $spreadsheet->getActiveSheet()->getCell('A1')->getCalculatedValue(); // Will return 9, because the formula for A1 has now been calculated, and the spillage area is populated $result = $spreadsheet->getActiveSheet()->getCell('C3')->getValue(); ``` If returning arrays has been enabled, `getCalculatedValue` will return an array when appropriate, and will populate the spill range. If returning arrays has not been enabled, when we call `getCalculatedValue()` for a cell that contains an array formula, PhpSpreadsheet will return the single value from the topmost leftmost cell, and will leave other cells unchanged. ```php // Will return integer 1, the value for that cell within the array $a1result = $spreadsheet->getActiveSheet()->getCell('A1')->getCalculatedValue(); ``` --- Excel365 introduced a number of new functions that return arrays of results. These include the `UNIQUE()`, `SORT()`, `SORTBY()`, `FILTER()`, `SEQUENCE()` and `RANDARRAY()` functions. While not all of these have been implemented by the Calculation Engine in PhpSpreadsheet, so they cannot all be calculated within your PHP applications, they can still be read from and written to Xlsx files. The `SEQUENCE()` function generates a series of values (in this case, starting with `-10` and increasing in steps of `2.5`); and here we're telling the formula to populate a 3x3 grid with these values. ![12-CalculationEngine-Spillage-Formula.png](./images/12-CalculationEngine-Spillage-Formula.png) Note that this is visually different from using `Ctrl-Shift-Enter` for the formula. When we are positioned in the "spill" range for the grid, MS Excel highlights the area with a blue border; and the formula displayed in the formula editing field isn't wrapped in braces (`{}`). And if we select any other cell inside the "spill" area other than the top-left cell, the formula in the formula edit field is greyed rather than displayed in black. ![12-CalculationEngine-Spillage-Formula-2.png](./images/12-CalculationEngine-Spillage-Formula-2.png) When we enter this formula in MS Excel, we don't need to select the range of cells that it should occupy; nor do we need to enter it using `Ctrl-Shift-Enter`. ### The Spill Operator If you want to reference the entire spillage range of an array formula within another formula, you could do so using the standard Excel range operator (`:`, e.g. `A1:C3`); but you may not always know the range, especially for array functions that spill across as many cells as they need, like `UNIQUE()` and `FILTER()`. To simplify this, MS Excel has introduced the "Spill" Operator (`#`). ![12-CalculationEngine-Spillage-Operator.png](./images/12-CalculationEngine-Spillage-Operator.png) Using our `SEQUENCE()`example, where the formula cell is `A1` and the result spills across the range `A1:C3`, we can use the Spill operator `A1#` to reference all the cells in that spillage range. In this case, we're taking the absolute value of each cell in that range, and adding them together using the `SUM()` function to give us a result of 50. PhpSpreadsheet supports entry of a formula like this using the Spill operator. Alternatively, MS Excel internally implements the Spill Operator as a function (`ANCHORARRAY()`). MS Excel itself doesn't allow you to use this function in a formula, you have to use the "Spill" operator; but PhpSpreadsheet does allow you to use this internal Excel function. PhpSpreadsheet will convert the spill operator to ANCHORARRAY on write (so it may appear that your formula has changed, but it hasn't really); it is not necessary to convert it back on read. To create this same function in PhpSpreadsheet, use: ```php $spreadsheet->getActiveSheet()->setCellValue('D1','=SUM(ABS(ANCHORARRAY(A1)))'); ``` When the file is saved, and opened in MS Excel, it will be rendered correctly. ### The At-sign Operator If you want to reference just the first cell of an array formula within another formula, you could do so by prefixing it with an at-sign. You can also select the entry in a range which matches the current row in this way; so, if you enter `=@A1:A5` in cell G3, the result will be the value from A3. MS Excel again implements this under the covers by converting to a function SINGLE. PhpSpreadsheet allows the use of the SINGLE function. It does not yet support the at-sign operator, which can have a different meaning in other contexts. ### Updating Cell in Spill Area Excel prevents you from updating a cell in the spill area. PhpSpreadsheet does not - it seems like it might be quite expensive, needing to reevaluate the entire worksheet with each `setValue`. PhpSpreadsheet does provide a method to be used prior to calling `setValue` if desired. ```php $sheet->setCellValue('A1', '=SORT{7;5;1}'); $sheet->getCell('A1')->getCalculatedValue(); // populates A1-A3 $sheet->isCellInSpillRange('A2'); // true $sheet->isCellInSpillRange('A3'); // true $sheet->isCellInSpillRange('A4'); // false $sheet->isCellInSpillRange('A1'); // false ``` The last result might be surprising. Excel allows you to alter the formula cell itself, so `isCellInSpillRange` treats the formula cell as not in range. It should also be noted that, if array returns are not enabled, `isCellInSpillRange` will always return `false`. ## Locale Settings for Formulas Some localisation elements have been included in PhpSpreadsheet. You can set a locale by changing the settings. To set the locale to Russian you would use: ```php $locale = 'ru'; $validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale); if (!$validLocale) { echo 'Unable to set locale to '.$locale." - reverting to en_us
\n"; } ``` If Russian language files aren't available, the `setLocale()` method will return an error, and English settings will be used throughout. Once you have set a locale, you can translate a formula from its internal English coding. ```php $formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue(); $translatedFormula = \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->translateFormulaToLocale($formula); ``` You can also create a formula using the function names and argument separators appropriate to the defined locale; then translate it to English before setting the cell value: ```php $formula = '=ДНЕЙ360(ДАТА(2010;2;5);ДАТА(2010;12;31);ИСТИНА)'; $internalFormula = \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->translateFormulaToEnglish($formula); $spreadsheet->getActiveSheet()->setCellValue('B8',$internalFormula); ``` Currently, formula translation only translates the function names, the constants TRUE and FALSE (and NULL), Excel error messages, and the function argument separators. Cell addressing using R1C1 formatting is not supported. At present, the following locale settings are supported: Language | | Locale Code ---------------------|----------------------|------------- Bulgarian | български | bg Czech | Ceština | cs Danish | Dansk | da German | Deutsch | de Spanish | Español | es Finnish | Suomi | fi French | Français | fr Hungarian | Magyar | hu Italian | Italiano | it Dutch | Nederlands | nl Norwegian | Norsk Bokmål | nb Polish | Jezyk polski | pl Portuguese | Português | pt Brazilian Portuguese | Português Brasileiro | pt_br Russian | русский язык | ru Swedish | Svenska | sv Turkish | Türkçe | tr If anybody can provide translations for additional languages, particularly Basque (Euskara), Catalan (Català), Croatian (Hrvatski jezik), Galician (Galego), Greek (Ελληνικά), Slovak (Slovenčina) or Slovenian (Slovenščina); please feel free to volunteer your services, and we'll happily show you what is needed to contribute a new language. ## Write a newline character "\n" in a cell (ALT+"Enter") In Microsoft Office Excel you get a line break in a cell by hitting ALT+"Enter". When you do that, it automatically turns on "wrap text" for the cell. Here is how to achieve this in PhpSpreadsheet: ```php $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld"); $spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true); ``` **Tip** Read more about formatting cells using `getStyle()` elsewhere. **Tip** AdvancedValuebinder.php automatically turns on "wrap text" for the cell when it sees a newline character in a string that you are inserting in a cell. Just like Microsoft Office Excel. Try this: ```php // Old method using static property \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); // Preferred method using dynamic property since 3.4.0 $spreadsheet->setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld"); ``` Read more about AdvancedValueBinder.php elsewhere. ## Explicitly set a cell's datatype You can set a cell's datatype explicitly by using the cell's setValueExplicit method, or the setCellValueExplicit method of a worksheet. Here's an example: ```php $spreadsheet->getActiveSheet()->getCell('A1') ->setValueExplicit( '25', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC ); ``` ## Change a cell into a clickable URL You can make a cell (or, for Xlsx only, a drawing) a clickable URL by setting its hyperlink property: ```php $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.example.com'); $spreadsheet->getActiveSheet()->getCell('E26') ->getHyperlink() ->setUrl('https://www.example.com'); ``` If you want to make a hyperlink to another worksheet/cell, use the following code: ```php $spreadsheet->getActiveSheet() ->setCellValue('E27', 'go to another sheet'); $spreadsheet->getActiveSheet()->getCell('E27') ->getHyperlink() ->setUrl("sheet://'Sheetname'!A1"); ``` Xlsx format uses `#` in place of `sheet://`. PhpSpreadsheet will automatically convert to that form when writing a spreadsheet, so you should continue to use `sheet://` for greater interoperability. Excel automatically supplies a special style when a hyperlink is entered into a cell. PhpSpreadsheet cannot do so. However, starting with release 4.3, you can mimic Excel's behavior with: ```php $spreadsheet->getActiveSheet() ->getStyle('E26') ->getFont() ->setHyperlinkTheme(); ``` This will set underline (all formats) and text color (always for Xlsx, and usually for other formats). ## Setting Printer Options for Excel files ### Setting a worksheet's page orientation and size Setting a worksheet's page orientation and size can be done using the following lines of code: ```php $spreadsheet->getActiveSheet()->getPageSetup() ->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE); $spreadsheet->getActiveSheet()->getPageSetup() ->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4); ``` Note that there are additional page settings available. Please refer to the [API documentation](https://phpoffice.github.io/PhpSpreadsheet) for all possible options. The default papersize is initially PAPERSIZE_LETTER. However, this default can be changed for new sheets with the following call: ```php \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::setPaperSizeDefault( \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4 ); ``` The default orientation is ORIENTATION_DEFAULT, which will be treated as Portrait in Excel. However, this default can be changed for new sheets with the following call: ```php \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::setOrientationDefault( \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE ); ``` ### Page Setup: Scaling options The page setup scaling options in PhpSpreadsheet relate directly to the scaling options in the "Page Setup" dialog as shown in the illustration. Default values in PhpSpreadsheet correspond to default values in MS Office Excel as shown in illustration ![08-page-setup-scaling-options.png](./images/08-page-setup-scaling-options.png) method | initial value | calling method will trigger | Note --------------------|:-------------:|-----------------------------|------ setFitToPage(...) | FALSE | - | setScale(...) | 100 | setFitToPage(FALSE) | setFitToWidth(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-width setFitToHeight(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-height #### Example Here is how to fit to 1 page wide by infinite pages tall: ```php $spreadsheet->getActiveSheet()->getPageSetup()->setFitToWidth(1); $spreadsheet->getActiveSheet()->getPageSetup()->setFitToHeight(0); ``` As you can see, it is not necessary to call setFitToPage(TRUE) since setFitToWidth(...) and setFitToHeight(...) triggers this. If you use `setFitToWidth()` you should in general also specify `setFitToHeight()` explicitly like in the example. Be careful relying on the initial values. ### Page margins To set page margins for a worksheet, use this code: ```php $spreadsheet->getActiveSheet()->getPageMargins()->setTop(1); $spreadsheet->getActiveSheet()->getPageMargins()->setRight(0.75); $spreadsheet->getActiveSheet()->getPageMargins()->setLeft(0.75); $spreadsheet->getActiveSheet()->getPageMargins()->setBottom(1); ``` Note that the margin values are specified in inches. ![08-page-setup-margins.png](./images/08-page-setup-margins.png) ### Center a page horizontally/vertically To center a page horizontally/vertically, you can use the following code: ```php $spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true); $spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(false); ``` ### Setting the print header and footer of a worksheet Setting a worksheet's print header and footer can be done using the following lines of code: ```php $spreadsheet->getActiveSheet()->getHeaderFooter() ->setOddHeader('&C&HPlease treat this document as confidential!'); $spreadsheet->getActiveSheet()->getHeaderFooter() ->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N'); ``` Notice the use of `oddHeader/Footer` above. This is, by default, the header used on all pages, not just the odd-numbered pages. You can specify a different header/footer for the first page and/or for even-numbered pages. ```php $spreadsheet->getActiveSheet()->getHeaderFooter() ->setDifferentFirst(true); // then as above except setFirstHeader/Footer rather than Odd $spreadsheet->getActiveSheet()->getHeaderFooter() ->setDifferentOddEven(true); // then as above except setEvenHeader/Footer rather than Odd ``` Substitution and formatting codes (starting with &) can be used inside headers and footers. There is no required order in which these codes must appear. The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: - Strikethrough - Superscript - Subscript Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, while the first is ON. The following codes are supported by Xlsx: Code | Meaning -------------------------|----------- `&L` | Code for "left section" (there are three header / footer locations, "left", "center", and "right"). When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the left section. `&P` | Code for "current page #" `&N` | Code for "total pages" `&font size` | Code for "text font size", where font size is a font size in points. `&K` | Code for "text font color" - RGB Color is specified as RRGGBB Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade value, NN is the tint/shade value. `&S` | Code for "text strikethrough" on / off `&X` | Code for "text super script" on / off `&Y` | Code for "text subscript" on / off `&C` | Code for "center section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the center section. `&D` | Code for "date" `&T` | Code for "time" `&G` | Code for "picture as background" - Please make sure to add the image to the header/footer (see [Tip for picture](#Tip-for-picture)) `&U` | Code for "text single underline" `&E` | Code for "double underline" `&R` | Code for "right section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the right section. `&Z` | Code for "this workbook's file path" `&F` | Code for "this workbook's file name" `&A` | Code for "sheet tab name" `&+` | Code for add to page # `&-` | Code for subtract from page # `&"font name,font type"` | Code for "text font name" and "text font type", where font name and font type are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font name, it means "none specified". Both of font name and font type can be localized values. `&"-,Bold"` | Code for "bold font style" `&B` | Code for "bold font style" `&"-,Regular"` | Code for "regular font style" `&"-,Italic"` | Code for "italic font style" `&I` | Code for "italic font style" `&"-,Bold Italic"` | Code for "bold italic font style" `&O` | Code for "outline style" `&H` | Code for "shadow style" **Tip** The above table of codes may seem overwhelming first time you are trying to figure out how to write some header or footer. Luckily, there is an easier way. Let Microsoft Office Excel do the work for you.For example, create in Microsoft Office Excel an xlsx file where you insert the header and footer as desired using the programs own interface. Save file as test.xlsx. Now, take that file and read off the values using PhpSpreadsheet as follows: ```php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('test.xlsx'); $worksheet = $spreadsheet->getActiveSheet(); var_dump($worksheet->getHeaderFooter()->getOddFooter()); var_dump($worksheet->getHeaderFooter()->getEvenFooter()); var_dump($worksheet->getHeaderFooter()->getOddHeader()); var_dump($worksheet->getHeaderFooter()->getEvenHeader()); ``` That reveals the codes for the even/odd header and footer. Experienced users may find it easier to rename test.xlsx to test.zip, unzip it, and inspect directly the contents of the relevant xl/worksheets/sheetX.xml to find the codes for header/footer. **Tip for picture** ```php $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setPath('./images/PhpSpreadsheet_logo.png'); $drawing->setHeight(36); $spreadsheet->getActiveSheet() ->getHeaderFooter() ->addImage( $drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT ); ``` If you want your image to be used only on the first page or only on even pages, use, for example, `HeaderFooter::IMAGE_FOOTER_CENTER_EVEN`. You must still call [`setDifferentFirst/Even`](#setDifferent) for this to work. This will work only for Xlsx. ### Setting printing breaks on a row or column To set a print break, use the following code, which sets a row break on row 10. ```php $spreadsheet->getActiveSheet()->setBreak( 'A10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW ); ``` The following line of code sets a print break on column D: ```php $spreadsheet->getActiveSheet()->setBreak( 'D10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_COLUMN ); ``` ### Show/hide gridlines when printing To show/hide gridlines when printing, use the following code: ```php $spreadsheet->getActiveSheet()->setPrintGridlines(true); ``` ### Setting rows/columns to repeat at top/left PhpSpreadsheet can repeat specific rows/cells at top/left of a page. The following code is an example of how to repeat row 1 to 5 on each printed page of a specific worksheet: ```php $spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5); ``` ### Specify printing area To specify a worksheet's printing area, use the following code: ```php $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5'); ``` There can also be multiple printing areas in a single worksheet: ```php $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20'); ``` ## Styles ### Formatting cells A cell can be formatted with font, border, fill, ... style information. For example, one can set the foreground colour of a cell to red, aligned to the right, and the border to black and thick border style. Let's do that on cell B2: ```php $spreadsheet->getActiveSheet()->getStyle('B2') ->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED); $spreadsheet->getActiveSheet()->getStyle('B2') ->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('B2') ->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK); $spreadsheet->getActiveSheet()->getStyle('B2') ->getBorders()->getBottom()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK); $spreadsheet->getActiveSheet()->getStyle('B2') ->getBorders()->getLeft()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK); $spreadsheet->getActiveSheet()->getStyle('B2') ->getBorders()->getRight()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK); $spreadsheet->getActiveSheet()->getStyle('B2') ->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID); $spreadsheet->getActiveSheet()->getStyle('B2') ->getFill()->getStartColor()->setARGB('FFFF0000'); ``` `getStyle()` also accepts a cell range as a parameter. For example, you can set a red background color on a range of cells: ```php $spreadsheet->getActiveSheet()->getStyle('B3:B7')->getFill() ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID) ->getStartColor()->setARGB('FFFF0000'); ``` **Tip** It is recommended to style many cells at once, using e.g. getStyle('A1:M500'), rather than styling the cells individually in a loop. This is much faster compared to looping through cells and styling them individually. **Tip** If you are styling entire row(s) or column(s), e.g. getStyle('A:A'), it is recommended to use applyFromArray as described below rather than setting the styles individually as described above. Also, starting with release 3.9.0, you should use getRowStyle or getColumnStyle to get the style for an entire row or column. There is also an alternative manner to set styles. The following code sets a cell's style to font bold, alignment right, top border thin and a gradient fill: ```php $styleArray = [ 'font' => [ 'bold' => true, ], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT, ], 'borders' => [ 'top' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, ], ], 'fill' => [ 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR, 'rotation' => 90, 'startColor' => [ 'argb' => 'FFA0A0A0', ], 'endColor' => [ 'argb' => 'FFFFFFFF', ], ], ]; $spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray); ``` Or with a range of cells: ```php $spreadsheet->getActiveSheet()->getStyle('B3:B7')->applyFromArray($styleArray); ``` This alternative method using arrays should be faster in terms of execution whenever you are setting more than one style property. But the difference may barely be measurable unless you have many different styles in your workbook. You can perform the opposite function, exporting a Style as an array, as follows: ``` php $styleArray = $spreadsheet->getActiveSheet()->getStyle('A3')->exportArray(); ``` ### Number formats You often want to format numbers in Excel. For example you may want a thousands separator plus a fixed number of decimals after the decimal separator. Or perhaps you want some numbers to be zero-padded. In Microsoft Office Excel you may be familiar with selecting a number format from the "Format Cells" dialog. Here there are some predefined number formats available including some for dates. The dialog is designed in a way so you don't have to interact with the underlying raw number format code unless you need a custom number format. In PhpSpreadsheet, you can also apply various predefined number formats. Example: ```php $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); ``` This will format a number e.g. 1587.2 so it shows up as 1,587.20 when you open the workbook in MS Office Excel. (Depending on settings for decimal and thousands separators in Microsoft Office Excel it may show up as 1.587,20) You can achieve exactly the same as the above by using this: ```php $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode('#,##0.00'); ``` In Microsoft Office Excel, as well as in PhpSpreadsheet, you will have to interact with raw number format codes whenever you need some special custom number format. Example: ```php $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode('[Blue][>=3000]$#,##0;[Red][<0]$#,##0;$#,##0'); ``` Another example is when you want numbers zero-padded with leading zeros to a fixed length: ```php $spreadsheet->getActiveSheet()->getCell('A1')->setValue(19); $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode('0000'); // will show as 0019 in Excel ``` **Tip** The rules for composing a number format code in Excel can be rather complicated. Sometimes you know how to create some number format in Microsoft Office Excel, but don't know what the underlying number format code looks like. How do you find it? The readers shipped with PhpSpreadsheet come to the rescue. Load your template workbook using e.g. Xlsx reader to reveal the number format code. Example how read a number format code for cell A1: ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $spreadsheet = $reader->load('template.xlsx'); var_dump($spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()->getFormatCode()); ``` Advanced users may find it faster to inspect the number format code directly by renaming template.xlsx to template.zip, unzipping, and looking for the relevant piece of XML code holding the number format code in *xl/styles.xml*. ### Alignment and wrap text Let's set vertical alignment to the top for cells A1:D4 ```php $spreadsheet->getActiveSheet()->getStyle('A1:D4') ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP); ``` Here is how to achieve wrap text: ```php $spreadsheet->getActiveSheet()->getStyle('A1:D4') ->getAlignment()->setWrapText(true); ``` ### Setting the default style of a workbook It is possible to set the default style of a workbook. Let's set the default font to Arial size 8: ```php $spreadsheet->getDefaultStyle()->getFont()->setName('Arial'); $spreadsheet->getDefaultStyle()->getFont()->setSize(8); ``` Excel also offers "theme fonts", with separate font names for major (header) and minor (body) text. PhpSpreadsheet will use the Excel 2007 default (Cambria) for major (default is Calibri Light in Excel 2013+); PhpSpreadsheet default for minor is Calibri, which is used by Excel 2007+. To align the default font name with the minor font name: ```php $spreadsheet->getTheme() ->setThemeFontName('custom') ->setMinorFontValues('Arial', 'Arial', 'Arial', []); $spreadsheet->getDefaultStyle()->getFont()->setScheme('minor'); ``` All cells bound to the theme fonts (via the `Font::setScheme` method) can be easily changed to a different font in Excel. To do this in PhpSpreadsheet, an additional method call is needed: ```php $spreadsheet->resetThemeFonts(); ``` ### Charset for Arabic and Persian Fonts It is unknown why this should be needed. However, some Excel users have reported better results if the internal declaration for an Arabic/Persian font includes a `charset` declaration. This seems like a bug in Excel, but, starting with release 4.4, this can be accomplished at the spreadsheet level, via: ```php $spreadsheet->addFontCharset('C Nazanin'); ``` As many charsets as desired can be added in this manner. There is a second optional parameter specifying the charset id to this method, but, since this seems to be needed only for Arabic/Persian, that is its default value. ### Styling cell borders In PhpSpreadsheet it is easy to apply various borders on a rectangular selection. Here is how to apply a thick red border outline around cells B2:G8. ```php $styleArray = [ 'borders' => [ 'outline' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK, 'color' => ['argb' => 'FFFF0000'], ], ], ]; $worksheet->getStyle('B2:G8')->applyFromArray($styleArray); ``` In Microsoft Office Excel, the above operation would correspond to selecting the cells B2:G8, launching the style dialog, choosing a thick red border, and clicking on the "Outline" border component. Note that the border outline is applied to the rectangular selection B2:G8 as a whole, not on each cell individually. You can achieve any border effect by using just the 5 basic borders and operating on a single cell at a time: - left - right - top - bottom - diagonal Additional shortcut borders come in handy like in the example above. These are the shortcut borders available: - allBorders - outline - inside - vertical - horizontal An overview of all border shortcuts can be seen in the following image: ![08-styling-border-options.png](./images/08-styling-border-options.png) If you simultaneously set e.g. allBorders and vertical, then we have "overlapping" borders, and one of the components has to win over the other where there is border overlap. In PhpSpreadsheet, from weakest to strongest borders, the list is as follows: allBorders, outline/inside, vertical/horizontal, left/right/top/bottom/diagonal. This border hierarchy can be utilized to achieve various effects in an easy manner. #### Advanced borders There is a second parameter `$advancedBorders` which can be supplied to applyFromArray. The default is `true`; when set to this value, the border styles are applied to the range as a whole, not to the individual cells. When set to `false`, the border styles are applied to each cell. The following code and screenshot demonstrates the difference. ```php $sheet->setShowGridlines(false); $styleArray = [ 'borders' => [ 'bottom' => ['borderStyle' => 'hair', 'color' => ['argb' => 'FFFF0000']], 'top' => ['borderStyle' => 'hair', 'color' => ['argb' => 'FFFF0000']], 'right' => ['borderStyle' => 'hair', 'color' => ['argb' => 'FF00FF00']], 'left' => ['borderStyle' => 'hair', 'color' => ['argb' => 'FF00FF00']], ], ]; $sheet->getStyle('B2:C3')->applyFromArray($styleArray); $sheet->getStyle('B5:C6')->applyFromArray($styleArray, false); ``` ![08-advance-borders.png](./images/08-advanced-borders.png) ### Valid array keys for style `applyFromArray()` The following table lists the valid array keys for `\PhpOffice\PhpSpreadsheet\Style\Style::applyFromArray()` classes. If the "Maps to property" column maps a key to a setter, the value provided for that key will be applied directly. If the "Maps to property" column maps a key to a getter, the value provided for that key will be applied as another style array. **\PhpOffice\PhpSpreadsheet\Style\Style** Array key | Maps to property -------------|------------------- alignment | setAlignment() borders | setBorders() fill | setFill() font | setFont() numberFormat | setNumberFormat() protection | setProtection() quotePrefix | setQuotePrefix() **\PhpOffice\PhpSpreadsheet\Style\Alignment** Array key | Maps to property ----------------|------------------- horizontal | setHorizontal() justifyLastLine | setJustifyLastLine() indent | setIndent() readOrder | setReadOrder() shrinkToFit | setShrinkToFit() textRotation | setTextRotation() vertical | setVertical() wrapText | setWrapText() **\PhpOffice\PhpSpreadsheet\Style\Border** Array key | Maps to property ------------|------------------- borderStyle | setBorderStyle() color | setColor() **\PhpOffice\PhpSpreadsheet\Style\Borders** Array key | Maps to property ------------------|------------------- allBorders | getLeft(); getRight(); getTop(); getBottom() bottom | getBottom() diagonal | getDiagonal() diagonalDirection | setDiagonalDirection() left | getLeft() right | getRight() top | getTop() **\PhpOffice\PhpSpreadsheet\Style\Color** Array key | Maps to property ------------|------------------- argb | setARGB() **\PhpOffice\PhpSpreadsheet\Style\Fill** Array key | Maps to property -----------|------------------- color | getStartColor() endColor | getEndColor() fillType | setFillType() rotation | setRotation() startColor | getStartColor() **\PhpOffice\PhpSpreadsheet\Style\Font** Array key | Maps to property ------------|------------------- bold | setBold() color | getColor() italic | setItalic() name | setName() size | setSize() strikethrough | setStrikethrough() subscript | setSubscript() superscript | setSuperscript() underline | setUnderline() **\PhpOffice\PhpSpreadsheet\Style\NumberFormat** Array key | Maps to property ----------|------------------- formatCode | setFormatCode() **\PhpOffice\PhpSpreadsheet\Style\Protection** Array key | Maps to property ----------|------------------- locked | setLocked() hidden | setHidden() ## Conditional formatting a cell A cell can be formatted conditionally, based on a specific rule. For example, one can set the foreground colour of a cell to red if its value is below zero, and to green if its value is zero or more. One can set a conditional style ruleset to a cell using the following code: ```php $conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional(); $conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS); $conditional1->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN); $conditional1->addCondition('0'); $conditional1->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED); $conditional1->getStyle()->getFont()->setBold(true); $conditional2 = new \PhpOffice\PhpSpreadsheet\Style\Conditional(); $conditional2->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS); $conditional2->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_GREATERTHANOREQUAL); $conditional2->addCondition('0'); $conditional2->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_GREEN); $conditional2->getStyle()->getFont()->setBold(true); $conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles(); $conditionalStyles[] = $conditional1; $conditionalStyles[] = $conditional2; $spreadsheet->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles); ``` If you want to copy the ruleset to other cells, you can duplicate the style object: ```php $spreadsheet->getActiveSheet() ->duplicateConditionalStyle( $spreadsheet->getActiveSheet()->getConditionalStyles('B2'), 'B3:B7' ); ``` More detailed documentation of the Conditional Formatting options and rules, and the use of Wizards to help create them, can be found in [a dedicated section of the documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/conditional-formatting/). ### DataBar of Conditional formatting The basics are the same as conditional formatting. Additional DataBar object to conditional formatting. For example, the following code will result in the conditional formatting shown in the image. ```php $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_DATABAR); $conditional->setDataBar(new ConditionalDataBar()); $conditional->getDataBar() ->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject('num', '2')) ->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject('max')) ->setColor('FFFF555A'); $ext = $conditional ->getDataBar() ->setConditionalFormattingRuleExt(new ConditionalFormattingRuleExtension()) ->getConditionalFormattingRuleExt(); $ext->setCfRule('dataBar'); $ext->setSqref('A1:A5'); // target CellCoordinates $ext->setDataBarExt(new ConditionalDataBarExtension()); $ext->getDataBarExt() ->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject('num', '2')) ->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject('autoMax')) ->setMinLength(0) ->setMaxLength(100) ->setBorder(true) ->setDirection('rightToLeft') ->setNegativeBarBorderColorSameAsPositive(false) ->setBorderColor('FFFF555A') ->setNegativeFillColor('FFFF0000') ->setNegativeBorderColor('FFFF0000') ->setAxisColor('FF000000'); ``` ![10-databar-of-conditional-formatting.png](./images/10-databar-of-conditional-formatting.png) ## Add a comment to a cell To add a comment to a cell, use the following code. The example below adds a comment to cell E11: ```php $spreadsheet->getActiveSheet() ->getComment('E11') ->setAuthor('Mark Baker'); $commentRichText = $spreadsheet->getActiveSheet() ->getComment('E11') ->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFont()->setBold(true); $spreadsheet->getActiveSheet() ->getComment('E11') ->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet() ->getComment('E11') ->getText()->createTextRun('Total amount on the current invoice, excluding VAT.'); ``` ![08-cell-comment.png](./images/08-cell-comment.png) ## Add a comment with background image to a cell To add a comment with background image to a cell, use the following code: ```php $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('B5', 'Gibli Chromo'); // Add png image to comment background $drawing = new Drawing(); $drawing->setName('Gibli Chromo'); $drawing->setPath('/tmp/gibli_chromo.png'); $comment = $sheet->getComment('B5'); $comment->setBackgroundImage($drawing); // Set the size of the comment equal to the size of the image $comment->setSizeAsBackgroundImage(); ``` ![08-cell-comment-with-image.png](./images/08-cell-comment-with-image.png) ## Apply autofilter to a range of cells To apply an autofilter to a range of cells, use the following code: ```php $spreadsheet->getActiveSheet()->setAutoFilter('A1:C9'); ``` **Make sure that you always include the complete filter range!** Excel does support setting only the caption row, but that's **not** a best practice... ## Setting security on a spreadsheet Excel offers 3 levels of "protection": - Document: allows you to set a password on a complete spreadsheet, allowing changes to be made only when that password is entered. - Worksheet: offers other security options: you can disallow inserting rows on a specific sheet, disallow sorting, ... - Cell: offers the option to lock/unlock a cell as well as show/hide the internal formula. **Make sure you enable worksheet protection if you need any of the worksheet or cell protection features!** This can be done using the following code: ```php $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); ``` > Note that "protection" is not the same as "encryption". > Protection is about preventing parts of a spreadsheet from being changed, not about preventing the spreadsheet from being looked at.

PhpSpreadsheet does not support encrypting a spreadsheet; nor can it read encrypted spreadsheets. ### Document An example on setting document security: ```php $security = $spreadsheet->getSecurity(); $security->setLockWindows(true); $security->setLockStructure(true); $security->setWorkbookPassword("PhpSpreadsheet"); ``` Note that there are additional methods setLockRevision and setRevisionsPassword which apply only to change tracking and history for shared workbooks. ### Worksheet An example on setting worksheet security (user can sort, insert rows, or format cells without unprotecting): ```php $protection = $spreadsheet->getActiveSheet()->getProtection(); $protection->setPassword('PhpSpreadsheet'); $protection->setSheet(true); $protection->setSort(false); $protection->setInsertRows(false); $protection->setFormatCells(false); ``` Note that allowing sort without providing the sheet password (similarly with autoFilter) requires that you explicitly enable the cell ranges for which sort is permitted, with or without a range password: ```php $sheet->protectCells('A:A'); // column A can be sorted without password $sheet->protectCells('B:B', 'sortpw'); // column B can be sorted if the range password sortpw is supplied ``` If writing Xlsx files you can specify the algorithm used to hash the password before calling `setPassword()` like so: ```php $protection = $spreadsheet->getActiveSheet()->getProtection(); $protection->setAlgorithm(Protection::ALGORITHM_SHA_512); $protection->setSpinCount(20000); $protection->setPassword('PhpSpreadsheet'); ``` The salt should **not** be set manually and will be automatically generated when setting a new password. ### Cell An example on setting cell security. Note that cell security is honored only when sheet is protected. Also note that the `hidden` property applies only to formulas, and tells whether the formula is hidden on the formula bar, not in the cell. ```php $spreadsheet->getActiveSheet()->getStyle('B1') ->getProtection() ->setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED) ->setHidden(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_PROTECTED); ``` ## Reading protected spreadsheet Spreadsheets that are protected as described above can always be read by PhpSpreadsheet. There is no need to know the password or do anything special in order to read a protected file. However if you need to implement a password verification mechanism, you can use the following helper method: ```php $protection = $spreadsheet->getActiveSheet()->getProtection(); $allowed = $protection->verify('my password'); if ($allowed) { doSomething(); } else { throw new Exception('Incorrect password'); } ``` If you need to completely prevent reading a file by any tool, including PhpSpreadsheet, then you are looking for "encryption", not "protection". ## Setting data validation on a cell Data validation is a powerful feature of Xlsx. It allows to specify an input filter on the data that can be inserted in a specific cell. This filter can be a range (i.e. value must be between 0 and 10), a list (i.e. value must be picked from a list), ... The following piece of code only allows numbers between 10 and 20 to be entered in cell B3: ```php $validation = $spreadsheet->getActiveSheet()->getCell('B3') ->getDataValidation(); $validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_WHOLE ); $validation->setErrorStyle( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_STOP ); $validation->setAllowBlank(true); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setErrorTitle('Input error'); $validation->setError('Number is not allowed!'); $validation->setPromptTitle('Allowed input'); $validation->setPrompt('Only numbers between 10 and 20 are allowed.'); $validation->setFormula1(10); $validation->setFormula2(20); ``` The following piece of code only allows an item picked from a list of data to be entered in cell B5: ```php $validation = $spreadsheet->getActiveSheet()->getCell('B5') ->getDataValidation(); $validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_LIST ); $validation->setErrorStyle( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_INFORMATION ); $validation->setAllowBlank(false); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setShowDropDown(true); $validation->setErrorTitle('Input error'); $validation->setError('Value is not in list.'); $validation->setPromptTitle('Pick from list'); $validation->setPrompt('Please pick a value from the drop-down list.'); $validation->setFormula1('"Item A,Item B,Item C"'); ``` When using a data validation list like above, make sure you put the list between `"` and `"` and that you split the items with a comma (`,`). It is important to remember that any string participating in an Excel formula is allowed to be maximum 255 characters (not bytes). This sets a limit on how many items you can have in the string "Item A,Item B,Item C". Therefore it is normally a better idea to type the item values directly in some cell range, say A1:A3, and instead use, say, `$validation->setFormula1('\'Sheet title\'!$A$1:$A$3')`. Another benefit is that the item values themselves can contain the comma `,` character itself. ### Setting Validation on Multiple Cells - Release 3 and Below If you need data validation on multiple cells, one can clone the ruleset: ```php $spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $validation); ``` Alternatively, one can apply the validation to a range of cells: ```php $validation->setSqref('B5:B1048576'); ``` ### Setting Validation on Multiple Cells - Release 4 and Above Starting with Release 4, Data Validation can be set simultaneously on several cells/cell ranges. ```php $spreadsheet->getActiveSheet()->getDataValidation('A1:A4 D5 E6:E7') ->set...(...); ``` In theory, this means that more than one Data Validation can apply to a cell. It appears that, when Excel reads a spreadsheet with more than one Data Validation applying to a cell, whichever appears first in the Xml is what Xml uses. PhpSpreadsheet will instead apply a DatValidation applying to a single cell first; then, if it doesn't find such a match, it will use the first applicable definition which is read (or created after or in lieu of reading). This allows you, for example, to set Data Validation on all but a few cells in a column: ```php $dv = new DataValidation(); $dv->setType(DataValidation::TYPE_NONE); $sheet->setDataValidation('A5:A7', $dv); $dv = new DataValidation(); $dv->set...(...); $sheet->setDataValidation('A:A', $dv); $dv = new DataValidation(); $dv->setType(DataValidation::TYPE_NONE); $sheet->setDataValidation('A9', $dv); ``` ## Setting a column's width A column's width can be set using the following code: ```php $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12); ``` If you want to set a column width using a different UoM (Unit of Measure), then you can do so by telling PhpSpreadsheet what UoM the width value that you are setting is measured in. Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), `cm` (centimeters) and `mm` (millimeters). Setting the column width to `-1` tells MS Excel to display the column using its default width. ```php $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(120, 'pt'); ``` If you want PhpSpreadsheet to perform an automatic width calculation, use the following code. PhpSpreadsheet will approximate the column width to the width of the widest value displayed in that column. ```php $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); ``` ![08-column-width.png](./images/08-column-width.png) The measure for column width in PhpSpreadsheet does **not** correspond exactly to the measure you may be used to in Microsoft Office Excel. Column widths are difficult to deal with in Excel, and there are several measures for the column width. 1. Inner width in character units (e.g. 8.43 this is probably what you are familiar with in Excel) 2. Full width in pixels (e.g. 64 pixels) 3. Full width in character units (e.g. 9.140625, value -1 indicates unset width) **PhpSpreadsheet always operates with "3. Full width in character units"** which is in fact the only value that is stored in any Excel file, hence the most reliable measure. Unfortunately, **Microsoft Office Excel does not present you with this measure**. Instead measures 1 and 2 are computed by the application when the file is opened and these values are presented in various dialogues and tool tips. The character width unit is the width of a `0` (zero) glyph in the workbooks default font. Therefore column widths measured in character units in two different workbooks can only be compared if they have the same default workbook font.If you have some Excel file and need to know the column widths in measure 3, you can read the Excel file with PhpSpreadsheet and echo the retrieved values. ## Show/hide a column To set a worksheet's column visibility, you can use the following code. The first line explicitly shows the column C, the second line hides column D. ```php $spreadsheet->getActiveSheet()->getColumnDimension('C')->setVisible(true); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false); ``` ## Group/outline a column To group/outline a column, you can use the following code: ```php $spreadsheet->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1); ``` You can also collapse the column. Note that you should also set the column invisible, otherwise the collapse will not be visible in Excel 2007. ```php $spreadsheet->getActiveSheet()->getColumnDimension('E')->setCollapsed(true); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setVisible(false); ``` Please refer to the section "group/outline a row" for a complete example on collapsing. You can instruct PhpSpreadsheet to add a summary to the right (default), or to the left. The following code adds the summary to the left: ```php $spreadsheet->getActiveSheet()->setShowSummaryRight(false); ``` ## Setting a row's height A row's height can be set using the following code: ```php $spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100); ``` Excel measures row height in points, where 1 pt is 1/72 of an inch (or about 0.35mm). The default value is 12.75 pts; and the permitted range of values is between 0 and 409 pts, where 0 pts is a hidden row. If you want to set a row height using a different UoM (Unit of Measure), then you can do so by telling PhpSpreadsheet what UoM the height value that you are setting is measured in. Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), `cm` (centimeters) and `mm` (millimeters). ```php $spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100, 'pt'); ``` Setting the row height to `-1` tells MS Excel to display the column using its default height, which is based on the character font size. If you have wrapped text in a cell, then the `-1` default will only set the row height to display a single line of that wrapped text. If you need to calculate the actual height for the row, then count the lines that should be displayed (count the `\n` and add 1); then adjust for the font. The adjustment for Calibri 11 is approximately 14.5; for Calibri 12 15.9, etc. ```php $spreadsheet->getActiveSheet()->getRowDimension(1)->setRowHeight( 14.5 * (substr_count($sheet->getCell('A1')->getValue(), "\n") + 1) ); ``` ## Show/hide a row To set a worksheet''s row visibility, you can use the following code. The following example hides row number 10. ```php $spreadsheet->getActiveSheet()->getRowDimension('10')->setVisible(false); ``` Note that if you apply active filters using an AutoFilter, then this will override any rows that you hide or unhide manually within that AutoFilter range if you save the file. ## Group/outline a row To group/outline a row, you can use the following code: ```php $spreadsheet->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1); ``` You can also collapse the row. Note that you should also set the row invisible, otherwise the collapse will not be visible in Excel 2007. ```php $spreadsheet->getActiveSheet()->getRowDimension('5')->setCollapsed(true); $spreadsheet->getActiveSheet()->getRowDimension('5')->setVisible(false); ``` Here's an example which collapses rows 50 to 80: ```php for ($i = 51; $i <= 80; $i++) { $spreadsheet->getActiveSheet()->setCellValue('A' . $i, "FName $i"); $spreadsheet->getActiveSheet()->setCellValue('B' . $i, "LName $i"); $spreadsheet->getActiveSheet()->setCellValue('C' . $i, "PhoneNo $i"); $spreadsheet->getActiveSheet()->setCellValue('D' . $i, "FaxNo $i"); $spreadsheet->getActiveSheet()->setCellValue('E' . $i, true); $spreadsheet->getActiveSheet()->getRowDimension($i)->setOutlineLevel(1); $spreadsheet->getActiveSheet()->getRowDimension($i)->setVisible(false); } $spreadsheet->getActiveSheet()->getRowDimension(81)->setCollapsed(true); ``` You can instruct PhpSpreadsheet to add a summary below the collapsible rows (default), or above. The following code adds the summary above: ```php $spreadsheet->getActiveSheet()->setShowSummaryBelow(false); ``` ## Merge/Unmerge cells If you have a big piece of data you want to display in a worksheet, or a heading that needs to span multiple sub-heading columns, you can merge two or more cells together, to become one cell. This can be done using the following code: ```php $spreadsheet->getActiveSheet()->mergeCells('A18:E22'); ``` Removing a merge can be done using the `unmergeCells()` method: ```php $spreadsheet->getActiveSheet()->unmergeCells('A18:E22'); ``` MS Excel itself doesn't yet offer the functionality to simply hide the merged cells, or to merge the content of cells into a single cell, but it is available in Open/Libre Office. ### Merge with MERGE_CELL_CONTENT_EMPTY The default behaviour is to empty all cells except for the top-left corner cell in the merge range; and this is also the default behaviour for the `mergeCells()` method in PhpSpreadsheet. When this behaviour is applied, those cell values will be set to null; and if they are subsequently Unmerged, they will be empty cells. Passing an extra flag value to the `mergeCells()` method in PhpSpreadsheet can change this behaviour. ![12-01-MergeCells-Options.png](./images/12-01-MergeCells-Options.png) Possible flag values are: - Worksheet::MERGE_CELL_CONTENT_EMPTY (the default) - Worksheet::MERGE_CELL_CONTENT_HIDE - Worksheet::MERGE_CELL_CONTENT_MERGE ### Merge with MERGE_CELL_CONTENT_HIDE The first alternative, available only in OpenOffice, is to hide those cells, but to leave their content intact. When a file saved as `Xlsx` in those applications is opened in MS Excel, and those cells are unmerged, the original content will still be present. ```php $spreadsheet->getActiveSheet()->mergeCells('A1:C3', Worksheet::MERGE_CELL_CONTENT_HIDE); ``` Will replicate that behaviour. ### Merge with MERGE_CELL_CONTENT_MERGE The second alternative, available in both OpenOffice and LibreOffice is to merge the content of every cell in the merge range into the top-left cell, while setting those hidden cells to empty. ```php $spreadsheet->getActiveSheet()->mergeCells('A1:C3', Worksheet::MERGE_CELL_CONTENT_MERGE); ``` Particularly when the merged cells contain formulas, the logic for this merge seems strange: walking through the merge range, each cell is calculated in turn, and appended to the "master" cell, then it is emptied, so any subsequent calculations that reference the cell see an empty cell, not the pre-merge value. For example, suppose our spreadsheet contains ![12-01-MergeCells-Options-2.png](./images/12-01-MergeCells-Options-2.png) where `B2` is the formula `=5-B1` and `C2` is the formula `=A2/B2`, and we want to merge cells `A2` to `C2` with all the cell values merged. The result is: ![12-01-MergeCells-Options-3.png](./images/12-01-MergeCells-Options-3.png) The cell value `12` from cell `A2` is fixed; the value from `B2` is the result of the formula `=5-B1` (`4`, which is appended to our merged value), and cell `B2` is then emptied, so when we evaluate cell `C2` with the formula `=A2/B2` it gives us `12 / 0` which results in a `#DIV/0!` error (so the error `#DIV/0!` is appended to our merged value rather than the original calculation result of `3`). ## Inserting or Removing rows/columns You can insert/remove rows/columns at a specific position. The following code inserts 2 new rows, right before row 7: ```php $spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2); ``` while ```php $spreadsheet->getActiveSheet()->removeRow(7, 2); ``` will remove 2 rows starting at row number 7 (ie. rows 7 and 8). Equivalent methods exist for inserting/removing columns: ```php $spreadsheet->getActiveSheet()->removeColumn('C', 2); ``` All subsequent rows (or columns) will be moved to allow the insertion (or removal) with all formulas referencing thise cells adjusted accordingly. Note that this is a fairly intensive process, particularly with large worksheets, and especially if you are inserting/removing rows/columns from near beginning of the worksheet. If you need to insert/remove several consecutive rows/columns, always use the second argument rather than making multiple calls to insert/remove a single row/column if possible. ## Add a drawing to a worksheet A drawing is always represented as a separate object, which can be added to a worksheet. Therefore, you must first instantiate a new `\PhpOffice\PhpSpreadsheet\Worksheet\Drawing`, and assign its properties a meaningful value: ```php $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $drawing->setName('Logo'); $drawing->setDescription('Logo'); $drawing->setPath('./images/officelogo.jpg'); $drawing->setHeight(36); ``` To add the above drawing to the worksheet, use the following snippet of code. PhpSpreadsheet creates the link between the drawing and the worksheet: ```php $drawing->setWorksheet($spreadsheet->getActiveSheet()); ``` You can set numerous properties on a drawing, here are some examples: ```php $drawing->setName('Paid'); $drawing->setDescription('Paid'); $drawing->setPath('./images/paid.png'); $drawing->setCoordinates('B15'); $drawing->setOffsetX(110); $drawing->setRotation(25); $drawing->getShadow()->setVisible(true); $drawing->getShadow()->setDirection(45); ``` You can also add images created using GD functions without needing to save them to disk first as In-Memory drawings. ```php // Use GD to create an in-memory image $gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream'); $textColor = imagecolorallocate($gdImage, 255, 255, 255); imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor); // Add the In-Memory image to a worksheet $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing(); $drawing->setName('In-Memory image 1'); $drawing->setDescription('In-Memory image 1'); $drawing->setCoordinates('A1'); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction( \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG ); $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT); $drawing->setHeight(36); $drawing->setWorksheet($spreadsheet->getActiveSheet()); ``` Note that GD images are memory-intensive. ### Creating a Drawing from string or stream data If you want to create a drawing from a string containing the binary image data, or from an external datasource such as an S3 bucket, then you can create a new MemoryDrawing from these sources using the `fromString()` or `fromStream()` static methods. ```php $drawing = MemoryDrawing::fromString($imageString); ``` ```php $drawing = MemoryDrawing::fromStream($imageStreamFromS3Bucket); ``` Note that this is a memory-intensive process, like all gd images; and also creates a temporary file. ## Reading Images from a worksheet A commonly asked question is how to retrieve the images from a workbook that has been loaded, and save them as individual image files to disk. The following code extracts images from the current active worksheet, and writes each as a separate file. ```php use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; $i = 0; foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) { if ($drawing instanceof MemoryDrawing) { ob_start(); call_user_func( $drawing->getRenderingFunction(), $drawing->getImageResource() ); $imageContents = ob_get_contents(); ob_end_clean(); switch ($drawing->getMimeType()) { case MemoryDrawing::MIMETYPE_PNG : $extension = 'png'; break; case MemoryDrawing::MIMETYPE_GIF: $extension = 'gif'; break; case MemoryDrawing::MIMETYPE_JPEG : $extension = 'jpg'; break; } } else { if ($drawing->getPath()) { // Check if the source is a URL or a file path if ($drawing->getIsURL()) { $imageContents = file_get_contents($drawing->getPath()); $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); file_put_contents($filePath , $imageContents); $mimeType = mime_content_type($filePath); // You could use the below to find the extension from mime type. // https://gist.github.com/alexcorvi/df8faecb59e86bee93411f6a7967df2c#gistcomment-2722664 $extension = File::mime2ext($mimeType); unlink($filePath); } else { $zipReader = fopen($drawing->getPath(),'r'); $imageContents = ''; while (!feof($zipReader)) { $imageContents .= fread($zipReader,1024); } fclose($zipReader); $extension = $drawing->getExtension(); } } } $myFileName = '00_Image_'.++$i.'.'.$extension; file_put_contents($myFileName,$imageContents); } ``` ## Add rich text to a cell Adding rich text to a cell can be done using `\PhpOffice\PhpSpreadsheet\RichText\RichText` instances. Here''s an example, which creates the following rich text string: > This invoice is ***payable within thirty days after the end of the > month*** unless specified otherwise on the invoice. ```php $richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText(); $richText->createText('This invoice is '); $payable = $richText->createTextRun('payable within thirty days after the end of the month'); $payable->getFont()->setBold(true); $payable->getFont()->setItalic(true); $payable->getFont()->setColor( new \PhpOffice\PhpSpreadsheet\Style\Color( \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN ) ); $richText->createText(', unless specified otherwise on the invoice.'); $spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText); ``` ## Define a named range PhpSpreadsheet supports the definition of named ranges. These can be defined using the following code: ```php // Add some data $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:'); $spreadsheet->getActiveSheet()->setCellValue('A2', 'Lastname:'); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Maarten'); $spreadsheet->getActiveSheet()->setCellValue('B2', 'Balliauw'); // Define named ranges $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonFN', $spreadsheet->getActiveSheet(), '$B$1')); $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonLN', $spreadsheet->getActiveSheet(), '$B$2')); ``` Optionally, a fourth parameter can be passed defining the named range local (i.e. only usable on the current worksheet). Named ranges are global by default. ## Define a named formula In addition to named ranges, PhpSpreadsheet also supports the definition of named formulas. These can be defined using the following code: ```php // Add some data $spreadsheet->setActiveSheetIndex(0); $worksheet = $spreadsheet->getActiveSheet(); $worksheet ->setCellValue('A1', 'Product') ->setCellValue('B1', 'Quantity') ->setCellValue('C1', 'Unit Price') ->setCellValue('D1', 'Price') ->setCellValue('E1', 'VAT') ->setCellValue('F1', 'Total'); // Define named formula $spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('GERMAN_VAT_RATE', $worksheet, '=16.0%')); $spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('CALCULATED_PRICE', $worksheet, '=$B1*$C1')); $spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('GERMAN_VAT', $worksheet, '=$D1*GERMAN_VAT_RATE')); $spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('TOTAL_INCLUDING_VAT', $worksheet, '=$D1+$E1')); $worksheet ->setCellValue('A2', 'Advanced Web Application Architecture') ->setCellValue('B2', 2) ->setCellValue('C2', 23.0) ->setCellValue('D2', '=CALCULATED_PRICE') ->setCellValue('E2', '=GERMAN_VAT') ->setCellValue('F2', '=TOTAL_INCLUDING_VAT'); $spreadsheet->getActiveSheet() ->setCellValue('A3', 'Object Design Style Guide') ->setCellValue('B3', 5) ->setCellValue('C3', 12.0) ->setCellValue('D3', '=CALCULATED_PRICE') ->setCellValue('E3', '=GERMAN_VAT') ->setCellValue('F3', '=TOTAL_INCLUDING_VAT'); $spreadsheet->getActiveSheet() ->setCellValue('A4', 'PHP For the Web') ->setCellValue('B4', 3) ->setCellValue('C4', 10.0) ->setCellValue('D4', '=CALCULATED_PRICE') ->setCellValue('E4', '=GERMAN_VAT') ->setCellValue('F4', '=TOTAL_INCLUDING_VAT'); // Use a relative named range to provide the totals for rows 2-4 $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('COLUMN_TOTAL', $worksheet, '=A$2:A$4') ); $spreadsheet->getActiveSheet() ->setCellValue('B6', '=SUBTOTAL(109,COLUMN_TOTAL)') ->setCellValue('D6', '=SUBTOTAL(109,COLUMN_TOTAL)') ->setCellValue('E6', '=SUBTOTAL(109,COLUMN_TOTAL)') ->setCellValue('F6', '=SUBTOTAL(109,COLUMN_TOTAL)'); ``` As with named ranges, an optional fourth parameter can be passed defining the named formula scope as local (i.e. only usable on the specified worksheet). Otherwise, named formulas are global by default. ## Redirect output to a client's web browser Sometimes, one really wants to output a file to a client''s browser, especially when creating spreadsheets on-the-fly. There are some easy steps that can be followed to do this: 1. Create your PhpSpreadsheet spreadsheet 2. Output HTTP headers for the type of document you wish to output 3. Use the `\PhpOffice\PhpSpreadsheet\Writer\*` of your choice, and save to `'php://output'` `\PhpOffice\PhpSpreadsheet\Writer\Xlsx` uses temporary storage when writing to `php://output`. By default, temporary files are stored in the script's working directory. When there is no access, it falls back to the operating system's temporary files location. **This may not be safe for unauthorized viewing!** Depending on the configuration of your operating system, temporary storage can be read by anyone using the same temporary storage folder. When confidentiality of your document is needed, it is recommended not to use `php://output`. ### HTTP headers Example of a script redirecting an Excel 2007 file to the client's browser: ```php /* Here there will be some code where you create $spreadsheet */ // redirect output to client browser header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="myfile.xlsx"'); header('Cache-Control: max-age=0'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('php://output'); ``` Example of a script redirecting an Xls file to the client's browser: ```php /* Here there will be some code where you create $spreadsheet */ // redirect output to client browser header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="myfile.xls"'); header('Cache-Control: max-age=0'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('php://output'); ``` **Caution:** Make sure not to include any echo statements or output any other contents than the Excel file. There should be no whitespace before the opening `` tag (which can also be omitted to avoid problems). Make sure that your script is saved without a BOM (Byte-order mark) because this counts as echoing output. The same things apply to all included files. Failing to follow the above guidelines may result in corrupt Excel files arriving at the client browser, and/or that headers cannot be set by PHP (resulting in warning messages). ## Setting the default column width Default column width can be set using the following code: ```php $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12); ``` Excel measures column width in its own proprietary units, based on the number of characters that will be displayed in the default font. If you want to set the default column width using a different UoM (Unit of Measure), then you can do so by telling PhpSpreadsheet what UoM the width value that you are setting is measured in. Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), `cm` (centimeters) and `mm` (millimeters). ```php $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(400, 'pt'); ``` and PhpSpreadsheet will handle the internal conversion. ## Setting the default row height Default row height can be set using the following code: ```php $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15); ``` Excel measures row height in points, where 1 pt is 1/72 of an inch (or about 0.35mm). The default value is 12.75 pts; and the permitted range of values is between 0 and 409 pts, where 0 pts is a hidden row. If you want to set a row height using a different UoM (Unit of Measure), then you can do so by telling PhpSpreadsheet what UoM the height value that you are setting is measured in. Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), `cm` (centimeters) and `mm` (millimeters). ```php $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(100, 'pt'); ``` ## Add a GD drawing to a worksheet There might be a situation where you want to generate an in-memory image using GD and add it to a `Spreadsheet` without first having to save this file to a temporary location. Here''s an example which generates an image in memory and adds it to the active worksheet: ```php // Generate an image $gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream'); $textColor = imagecolorallocate($gdImage, 255, 255, 255); imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor); // Add a drawing to the worksheet $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing(); $drawing->setName('Sample image'); $drawing->setDescription('Sample image'); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG); $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT); $drawing->setHeight(36); $drawing->setWorksheet($spreadsheet->getActiveSheet()); ``` ## Setting worksheet zoom level To set a worksheet's zoom level, the following code can be used: ```php $spreadsheet->getActiveSheet()->getSheetView()->setZoomScale(75); ``` Note that zoom level should be in range 10 - 400. ## Sheet tab color Sometimes you want to set a color for sheet tab. For example you can have a red sheet tab: ```php $worksheet->getTabColor()->setRGB('FF0000'); ``` ## Creating worksheets in a workbook If you need to create more worksheets in the workbook, here is how: ```php $worksheet1 = $spreadsheet->createSheet(); $worksheet1->setTitle('Another sheet'); ``` Think of `createSheet()` as the "Insert sheet" button in Excel. When you hit that button a new sheet is appended to the existing collection of worksheets in the workbook. ## Hidden worksheets (Sheet states) Set a worksheet to be **hidden** using this code: ```php $spreadsheet->getActiveSheet() ->setSheetState(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN); ``` Sometimes you may even want the worksheet to be **"very hidden"**. The available sheet states are : - `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE` - `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN` - `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN` In Excel the sheet state "very hidden" can only be set programmatically, e.g. with Visual Basic Macro. It is not possible to make such a sheet visible via the user interface. ## Right-to-left worksheet Worksheets can be set individually whether column `A` should start at left or right side. Default is left. Here is how to set columns from right-to-left. ```php // right-to-left worksheet $spreadsheet->getActiveSheet()->setRightToLeft(true); ``` ================================================ FILE: docs/topics/settings.md ================================================ # Configuration Settings Once you have included the PhpSpreadsheet files in your script, but before instantiating a `Spreadsheet` object or loading a workbook file, there are a number of configuration options that can be set which will affect the subsequent behaviour of the script. ## Cell collection caching By default, PhpSpreadsheet holds all cell objects in memory, but you can specify alternatives to reduce memory consumption at the cost of speed. Read more about [memory saving](./memory_saving.md). To enable cell caching, you must provide your own implementation of cache like so: ```php $cache = new MyCustomPsr16Implementation(); \PhpOffice\PhpSpreadsheet\Settings::setCache($cache); ``` ## Language/Locale Some localisation elements have been included in PhpSpreadsheet. You can set a locale by changing the settings. To set the locale to Brazilian Portuguese you would use: ```php $locale = 'pt_br'; $validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale); if (!$validLocale) { echo 'Unable to set locale to ' . $locale . " - reverting to en_us" . PHP_EOL; } ``` - If Brazilian Portuguese language files aren't available, then Portuguese will be enabled instead - If Portuguese language files also aren't available, then the `setLocale` method will return `false`, and American English (en\_us) settings will be used throughout. More details of the features available once a locale has been set, including a list of the languages and locales currently supported, can be found in [Locale Settings for Formulas](./recipes.md#locale-settings-for-formulas). Additional localization elements (currency code, thousands separator, and decimal separator) are available in `PhpOffice\PhpSpreadsheet\Shared\StringHelper`: ```php StringHelper::setCurrencyCode('€'); StringHelper::setThousandsSeparator('.'); StringHelper::setDecimalSeparator(','); ``` You can use the Php function `setLocale` to try to set these values without knowing beforehand what symbols are needed. ```php StringHelper::setCurrencyCode(null); StringHelper::setThousandsSeparator(null); StringHelper::setDecimalSeparator(null); $result = setLocale(LC_ALL, 'pt_br.UTF-8'); ``` However, this function maintains its information at the process level, not the thread level, and its use is therefore discouraged. A less-troublesome replacement is available starting with PhpSpreadsheet 5.4. ```php $result = StringHelper::setLocale('pt_br'); // will restore defaults if argument is null ``` This will set the locale and the 3 StringHelper values all at once. It requires the `Intl` extension, which is not a requirement for PhpSpreadsheet as a whole. For that reason, it returns a boolean result, which will be `false` if `Intl` is not available, or if it does not consider the supplied locale to be valid. ================================================ FILE: docs/topics/tables.md ================================================ # Tables ## Introduction To make managing and analyzing a group of related data easier, you can turn a range of cells into an Excel table (previously known as an Excel list). ## Support Currently tables are supported in Xlsx reader and Html Writer To enable table formatting for Html writer, use: ```php $writer = new HtmlWriter($spreadsheet); $writer->setConditionalFormatting(true); ``` ================================================ FILE: docs/topics/worksheets.md ================================================ # Worksheets A worksheet is a collection of cells, formulae, images, graphs, etc. It holds all data necessary to represent a spreadsheet worksheet. When you load a workbook from a spreadsheet file, it will be loaded with all its existing worksheets (unless you specified that only certain sheets should be loaded). When you load from non-spreadsheet files (such as a CSV or HTML file) or from spreadsheet formats that don't identify worksheets by name (such as SYLK), then a single worksheet called "WorkSheet1" will be created containing the data from that file. When you instantiate a new workbook, PhpSpreadsheet will create it with a single worksheet called "WorkSheet1". The `getSheetCount()` method will tell you the number of worksheets in the workbook; while the `getSheetNames()` method will return a list of all worksheets in the workbook, indexed by the order in which their "tabs" would appear when opened in MS Excel (or other appropriate Spreadsheet program). Individual worksheets can be accessed by name, or by their index position in the workbook. The index position represents the order that each worksheet "tab" is shown when the workbook is opened in MS Excel (or other appropriate Spreadsheet program). To access a sheet by its index, use the `getSheet()` method. ```php // Get the second sheet in the workbook // Note that sheets are indexed from 0 $spreadsheet->getSheet(1); ``` Methods also exist allowing you to reorder the worksheets in the workbook. To access a sheet by name, use the `getSheetByName()` method, specifying the name of the worksheet that you want to access. ```php // Retrieve the worksheet called 'Worksheet 1' $spreadsheet->getSheetByName('Worksheet 1'); ``` Alternatively, one worksheet is always the currently active worksheet, and you can access that directly. The currently active worksheet is the one that will be active when the workbook is opened in MS Excel (or other appropriate Spreadsheet program). ```php // Retrieve the current active worksheet $spreadsheet->getActiveSheet(); ``` You can change the currently active sheet by index or by name using the `setActiveSheetIndex()` and `setActiveSheetIndexByName()` methods. ## Adding a new Worksheet You can add a new worksheet to the workbook using the `createSheet()` method of the `Spreadsheet` object. By default, this will be created as a new "last" sheet; but you can also specify an index position as an argument, and the worksheet will be inserted at that position, shuffling all subsequent worksheets in the collection down a place. ```php $spreadsheet->createSheet(); ``` A new worksheet created using this method will be called `Worksheet` where `` is the lowest number possible to guarantee that the title is unique. Alternatively, you can instantiate a new worksheet (setting the title to whatever you choose) and then insert it into your workbook using the `addSheet()` method. ```php // Create a new worksheet called "My Data" $myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'My Data'); // Attach the "My Data" worksheet as the first worksheet in the Spreadsheet object $spreadsheet->addSheet($myWorkSheet, 0); ``` If you don't specify an index position as the second argument, then the new worksheet will be added after the last existing worksheet. ## Copying Worksheets Sheets within the same workbook can be copied by creating a clone of the worksheet you wish to copy, and then using the `addSheet()` method to insert the clone into the workbook. ```php $clonedWorksheet = clone $spreadsheet->getSheetByName('Worksheet 1'); $clonedWorksheet->setTitle('Copy of Worksheet 1'); // must be unique $spreadsheet->addSheet($clonedWorksheet); ``` Starting with PhpSpreadsheet 3.9.0, this can be done more simply (copied sheet's title will be set to something unique): ```php $copiedWorksheet = $spreadsheet->duplicateWorksheetByTitle('sheetname'); ``` You can also copy worksheets from one workbook to another, though this is more complex as PhpSpreadsheet also has to replicate the styling between the two workbooks. The `addExternalSheet()` method is provided for this purpose. ```php $clonedWorksheet = clone $spreadsheet1->getSheetByName('Worksheet 1'); $clonedWorksheet->setTitle('Copy of Worksheet 1'); // must be unique $spreadsheet1->addSheet($clonedWorksheet); $spreadsheet->addExternalSheet($clonedWorksheet); ``` Starting with PhpSpreadsheet 3.8.0, this can be simplified: ```php $clonedWorksheet = clone $spreadsheet1->getSheetByName('Worksheet 1'); $spreadsheet1->addSheet($clonedWorksheet, null, true); $spreadsheet->addExternalSheet($clonedWorksheet); ``` Starting with PhpSpreadsheet 3.9.0, this can be simplified even further: ```php $clonedWorksheet = $spreadsheet1->duplicateWorksheetByTitle('sheetname'); $spreadsheet->addExternalSheet($clonedWorksheet); ``` In the cases commented "must be unique", it is the developer's responsibility to ensure that worksheet names are not duplicated. PhpSpreadsheet will throw an exception if you attempt to copy worksheets that will result in a duplicate name. ## Removing a Worksheet You can delete a worksheet from a workbook, identified by its index position, using the `removeSheetByIndex()` method ```php $sheetIndex = $spreadsheet->getIndex( $spreadsheet->getSheetByName('Worksheet 1') ); $spreadsheet->removeSheetByIndex($sheetIndex); ``` If the currently active worksheet is deleted, then the sheet at the previous index position will become the currently active sheet. ================================================ FILE: infra/DocumentGenerator.php ================================================ $phpSpreadsheetFunctions */ public static function generateFunctionListByCategory($phpSpreadsheetFunctions): string { $result = "# Function list by category\n"; foreach (self::getCategories() as $categoryConstant => $category) { $result .= "\n"; $result .= "## {$categoryConstant}\n"; $result .= "\n"; $lengths = [25, 37]; $result .= self::tableRow($lengths, ['Excel Function', 'PhpSpreadsheet Function']) . "\n"; $result .= self::tableRow($lengths, null) . "\n"; foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) { if (in_array($excelFunction, self::EXCLUDED_FUNCTIONS, true)) { continue; } if ($category === $functionInfo['category']) { $phpFunction = self::getPhpSpreadsheetFunctionText($functionInfo['functionCall']); $result .= self::tableRow($lengths, [$excelFunction, $phpFunction]) . "\n"; } } } return $result; } /** @return array */ private static function getCategories(): array { /** @var array */ $x = (new ReflectionClass(Category::class))->getConstants(); return $x; } /** * @param int[] $lengths * @param null|array $values */ private static function tableRow(array $lengths, ?array $values = null): string { $result = ''; foreach (array_map(null, $lengths, $values ?? []) as $i => [$length, $value]) { $pad = $value === null ? '-' : ' '; if ($i > 0) { $result .= '|' . $pad; } $result .= str_pad("$value", $length ?? 0, $pad); } return rtrim($result, ' '); } /** @param scalar|string|string[] $functionCall */ private static function getPhpSpreadsheetFunctionText(mixed $functionCall): string { if (is_string($functionCall)) { return $functionCall; } if ($functionCall === [Functions::class, 'DUMMY']) { return '**Not yet Implemented**'; } if (is_array($functionCall)) { return "\\{$functionCall[0]}::{$functionCall[1]}"; } throw new UnexpectedValueException( '$functionCall is of type ' . gettype($functionCall) . '. string or array expected' ); } /** * @param array $phpSpreadsheetFunctions */ public static function generateFunctionListByName(array $phpSpreadsheetFunctions, bool $compact = false): string { $categoryConstants = array_flip(self::getCategories()); if ($compact) { $result = "# Function list by name compact\n"; $result .= "\n"; $result .= 'Category should be prefixed by `CATEGORY_` to match the values in \PhpOffice\PhpSpreadsheet\Calculation\Category'; $result .= "\n\n"; $result .= 'Function should be prefixed by `PhpOffice\PhpSpreadsheet\Calculation\`'; $result .= "\n\n"; $result .= 'A less compact list can be found [here](./function-list-by-name.md)'; $result .= "\n\n"; } else { $result = "# Function list by name\n"; $result .= "\n"; $result .= 'A more compact list can be found [here](./function-list-by-name-compact.md)'; $result .= "\n\n"; } $lastAlphabet = null; $lengths = $compact ? [25, 22, 37] : [25, 31, 37]; foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) { if (in_array($excelFunction, self::EXCLUDED_FUNCTIONS, true)) { continue; } if ($lastAlphabet !== $excelFunction[0]) { $lastAlphabet = $excelFunction[0]; $result .= "\n"; $result .= "## {$lastAlphabet}\n"; $result .= "\n"; $result .= self::tableRow($lengths, ['Excel Function', 'Category', 'PhpSpreadsheet Function']) . "\n"; $result .= self::tableRow($lengths, null) . "\n"; } $category = $categoryConstants[$functionInfo['category']]; $phpFunction = self::getPhpSpreadsheetFunctionText($functionInfo['functionCall']); if ($compact) { $category = str_replace('CATEGORY_', '', $category); $phpFunction = str_replace( '\PhpOffice\PhpSpreadsheet\Calculation\\', '', $phpFunction ); } $result .= self::tableRow($lengths, [$excelFunction, $category, $phpFunction]) . "\n"; } return $result; } } ================================================ FILE: infra/LocaleGenerator.php ================================================ */ protected array $phpSpreadsheetFunctions; protected Spreadsheet $translationSpreadsheet; protected bool $verbose; protected Worksheet $localeTranslations; /** @var string[] */ protected array $localeLanguageMap = []; /** @var int[] */ protected array $errorCodeMap = []; private Worksheet $functionNameTranslations; /** @var string[] */ protected array $functionNameLanguageMap = []; /** @var array */ protected array $functionNameMap = []; /** * @param array $phpSpreadsheetFunctions */ public function __construct( string $translationBaseFolder, string $translationSpreadsheetName, array $phpSpreadsheetFunctions, bool $verbose = false ) { $this->translationBaseFolder = $translationBaseFolder; $this->translationSpreadsheetName = $translationSpreadsheetName; $this->phpSpreadsheetFunctions = $phpSpreadsheetFunctions; $this->verbose = $verbose; } public function generateLocales(): void { $this->openTranslationWorkbook(); $this->localeTranslations = $this->getTranslationSheet(self::EXCEL_LOCALISATION_WORKSHEET); $this->localeLanguageMap = $this->mapLanguageColumns($this->localeTranslations); $this->mapErrorCodeRows(); $this->functionNameTranslations = $this->getTranslationSheet(self::EXCEL_FUNCTIONS_WORKSHEET); $this->functionNameLanguageMap = $this->mapLanguageColumns($this->functionNameTranslations); $this->mapFunctionNameRows(); foreach ($this->localeLanguageMap as $column => $locale) { $this->buildConfigFileForLocale($column, $locale); } foreach ($this->functionNameLanguageMap as $column => $locale) { $this->buildFunctionsFileForLocale($column, $locale); } } protected function buildConfigFileForLocale(string $column, string $locale): void { $language = $this->localeTranslations->getCell($column . self::ENGLISH_LANGUAGE_NAME_ROW)->getValue(); if (!is_string($language)) { throw new Exception('Non-string language value at ' . $column . self::ENGLISH_LANGUAGE_NAME_ROW); } $localeLanguage = $this->localeTranslations->getCell($column . self::LOCALE_LANGUAGE_NAME_ROW)->getValue(); if (!is_string($localeLanguage)) { throw new Exception('Non-string locale language value at ' . $column . self::LOCALE_LANGUAGE_NAME_ROW); } $configFile = $this->openConfigFile($locale, $language, $localeLanguage); $this->writeConfigArgumentSeparator($configFile, $column); $this->writeConfigCurrencySymbol($configFile, $column); $this->writeFileSectionHeader($configFile, 'Error Codes'); foreach ($this->errorCodeMap as $errorCode => $row) { $translationCell = $this->localeTranslations->getCell($column . $row); $translationValue = $translationCell->getValue(); if ($translationValue !== null && !is_string($translationValue)) { throw new Exception('Non-string translation value at ' . $column . $row); } if (!empty($translationValue)) { $errorCodeTranslation = "{$errorCode} = {$translationValue}" . self::EOL; fwrite($configFile, $errorCodeTranslation); } else { $errorCodeTranslation = "{$errorCode}" . self::EOL; fwrite($configFile, $errorCodeTranslation); $this->log("No {$language} translation available for error code {$errorCode}"); } } fclose($configFile); } /** @param resource $configFile resource to write to */ protected function writeConfigArgumentSeparator($configFile, string $column): void { $translationCell = $this->localeTranslations->getCell($column . self::ARGUMENT_SEPARATOR_ROW); $localeValue = $translationCell->getValue(); if ($localeValue !== null && !is_string($localeValue)) { throw new Exception('Non-string locale value at ' . $column . self::CURRENCY_SYMBOL_ROW); } if (!empty($localeValue)) { $functionTranslation = "ArgumentSeparator = {$localeValue}" . self::EOL; fwrite($configFile, $functionTranslation); } else { $this->log('No Argument Separator defined'); } } /** @param resource $configFile resource to write to */ protected function writeConfigCurrencySymbol($configFile, string $column): void { $translationCell = $this->localeTranslations->getCell($column . self::CURRENCY_SYMBOL_ROW); $localeValue = $translationCell->getValue(); if ($localeValue !== null && !is_string($localeValue)) { throw new Exception('Non-string locale value at ' . $column . self::CURRENCY_SYMBOL_ROW); } if (!empty($localeValue)) { $functionTranslation = "currencySymbol = {$localeValue}" . self::EOL; fwrite($configFile, '##' . self::EOL); fwrite($configFile, '## (For future use)' . self::EOL); fwrite($configFile, '##' . self::EOL); fwrite($configFile, $functionTranslation); } else { $this->log('No Currency Symbol defined'); } } protected function buildFunctionsFileForLocale(string $column, string $locale): void { $language = $this->functionNameTranslations->getCell($column . self::ENGLISH_LANGUAGE_NAME_ROW)->getValue(); if (!is_string($language)) { throw new Exception('Non-string language value at ' . $column . self::ENGLISH_LANGUAGE_NAME_ROW); } $localeLanguage = $this->functionNameTranslations->getCell($column . self::LOCALE_LANGUAGE_NAME_ROW) ->getValue(); if (!is_string($localeLanguage)) { throw new Exception('Non-string locale language value at ' . $column . self::LOCALE_LANGUAGE_NAME_ROW); } $functionFile = $this->openFunctionNameFile($locale, $language, $localeLanguage); foreach ($this->functionNameMap as $functionName => $row) { $translationCell = $this->functionNameTranslations->getCell($column . $row); $translationValue = $translationCell->getValue(); if ($translationValue !== null && !is_string($translationValue)) { throw new Exception('Non-string translation value at ' . $column . $row); } if ($this->isFunctionCategoryEntry($translationCell)) { $this->writeFileSectionHeader($functionFile, "{$translationValue} ({$functionName})"); } elseif (!array_key_exists($functionName, $this->phpSpreadsheetFunctions) && substr($functionName, 0, 1) !== '*') { $this->log("Function {$functionName} is not defined in PhpSpreadsheet"); } elseif (!empty($translationValue)) { $functionTranslation = "{$functionName} = {$translationValue}" . self::EOL; fwrite($functionFile, $functionTranslation); } else { $this->log("No {$language} translation available for function {$functionName}"); } } fclose($functionFile); } /** @return resource used by other methods in this class */ protected function openConfigFile(string $locale, string $language, string $localeLanguage) { $this->log("Building locale {$locale} ($language) configuration"); $localeFolder = $this->getLocaleFolder($locale); $configFileName = realpath($localeFolder) . DIRECTORY_SEPARATOR . 'config'; $this->log("Writing locale configuration to {$configFileName}"); $configFile = fopen($configFileName, 'wb'); if ($configFile === false) { throw new Exception('Unable to open $configFileName for write'); } $this->writeFileHeader($configFile, $localeLanguage, $language, 'locale settings'); return $configFile; } /** @return resource used by other methods in this class */ protected function openFunctionNameFile(string $locale, string $language, string $localeLanguage) { $this->log("Building locale {$locale} ($language) function names"); $localeFolder = $this->getLocaleFolder($locale); $functionFileName = realpath($localeFolder) . DIRECTORY_SEPARATOR . 'functions'; $this->log("Writing local function names to {$functionFileName}"); $functionFile = fopen($functionFileName, 'wb'); if ($functionFile === false) { throw new Exception('Unable to open $functionFileName for write'); } $this->writeFileHeader($functionFile, $localeLanguage, $language, 'function name translations'); return $functionFile; } protected function getLocaleFolder(string $locale): string { $lastchar = substr($this->translationBaseFolder, -1); $dirsep = ($lastchar === '/' || $lastchar === '\\') ? '' : DIRECTORY_SEPARATOR; $localeFolder = $this->translationBaseFolder . $dirsep . str_replace('_', DIRECTORY_SEPARATOR, $locale); if (!file_exists($localeFolder) || !is_dir($localeFolder)) { mkdir($localeFolder, 7 * 64 + 7 * 8 + 7, true); // octal 777 } return $localeFolder; } /** @param resource $localeFile file being written to */ protected function writeFileHeader($localeFile, string $localeLanguage, string $language, string $title): void { fwrite($localeFile, str_repeat('#', 60) . self::EOL); fwrite($localeFile, '##' . self::EOL); fwrite($localeFile, "## PhpSpreadsheet - {$title}" . self::EOL); fwrite($localeFile, '##' . self::EOL); fwrite($localeFile, "## {$localeLanguage} ({$language})" . self::EOL); fwrite($localeFile, '##' . self::EOL); fwrite($localeFile, str_repeat('#', 60) . self::EOL . self::EOL); } /** @param resource $localeFile file being written to */ protected function writeFileSectionHeader($localeFile, string $header): void { fwrite($localeFile, self::EOL . '##' . self::EOL); fwrite($localeFile, "## {$header}" . self::EOL); fwrite($localeFile, '##' . self::EOL); } protected function openTranslationWorkbook(): void { $filepathName = $this->translationBaseFolder . '/' . $this->translationSpreadsheetName; $this->translationSpreadsheet = IOFactory::load($filepathName); } protected function getTranslationSheet(string $sheetName): Worksheet { $worksheet = $this->translationSpreadsheet->setActiveSheetIndexByName($sheetName); return $worksheet; } /** @return string[] */ protected function mapLanguageColumns(Worksheet $translationWorksheet): array { $sheetName = $translationWorksheet->getTitle(); $this->log("Mapping Languages for {$sheetName}:"); $baseColumn = self::ENGLISH_REFERENCE_COLUMN; $languagesList = $translationWorksheet->getColumnIterator(StringHelper::stringIncrement($baseColumn)); $languageNameMap = []; foreach ($languagesList as $languageColumn) { $cells = $languageColumn->getCellIterator(self::LOCALE_NAME_ROW, self::LOCALE_NAME_ROW); $cells->setIterateOnlyExistingCells(true); foreach ($cells as $cell) { if ($this->localeCanBeSupported($translationWorksheet, $cell)) { $languageNameMap[$cell->getColumn()] = $cell->getValueString(); $this->log($cell->getColumn() . ' -> ' . $cell->getValueString()); } } } return $languageNameMap; } protected function localeCanBeSupported(Worksheet $worksheet, Cell $cell): bool { if ($worksheet->getTitle() === self::EXCEL_LOCALISATION_WORKSHEET) { // Only provide support for languages that have a function argument separator defined // in the localisation worksheet return !empty( $worksheet->getCell($cell->getColumn() . self::ARGUMENT_SEPARATOR_ROW)->getValue() ); } // If we're processing other worksheets, then language support is determined by whether we included the // language in the map when we were processing the localisation worksheet (which is always processed first) return in_array($cell->getValue(), $this->localeLanguageMap, true); } protected function mapErrorCodeRows(): void { $this->log('Mapping Error Codes:'); $errorList = $this->localeTranslations->getRowIterator(self::ERROR_CODES_FIRST_ROW); foreach ($errorList as $errorRow) { $cells = $errorRow->getCellIterator(self::ENGLISH_REFERENCE_COLUMN, self::ENGLISH_REFERENCE_COLUMN); $cells->setIterateOnlyExistingCells(true); foreach ($cells as $cell) { if ($cell->getValue() != '') { $this->log($cell->getRow() . ' -> ' . $cell->getValueString()); $this->errorCodeMap[$cell->getValueString()] = $cell->getRow(); } } } } protected function mapFunctionNameRows(): void { $this->log('Mapping Functions:'); $functionList = $this->functionNameTranslations->getRowIterator(self::FUNCTION_NAME_LIST_FIRST_ROW); foreach ($functionList as $functionRow) { $cells = $functionRow->getCellIterator(self::ENGLISH_REFERENCE_COLUMN, self::ENGLISH_REFERENCE_COLUMN); $cells->setIterateOnlyExistingCells(true); foreach ($cells as $cell) { if ($this->isFunctionCategoryEntry($cell)) { if (!empty($cell->getValue())) { $this->log('CATEGORY: ' . $cell->getValueString()); $this->functionNameMap[$cell->getValueString()] = $cell->getRow(); } continue; } if ($cell->getValue() !== '' && $cell->getValue() !== null) { if (is_bool($cell->getValue())) { $this->log($cell->getRow() . ' -> ' . ($cell->getValue() ? 'TRUE' : 'FALSE')); $this->functionNameMap[($cell->getValue() ? 'TRUE' : 'FALSE')] = $cell->getRow(); } else { $this->log($cell->getRow() . ' -> ' . $cell->getValueString()); $this->functionNameMap[$cell->getValueString()] = $cell->getRow(); } } } } } private function isFunctionCategoryEntry(Cell $cell): bool { $categoryCheckCell = self::ENGLISH_FUNCTION_CATEGORIES_COLUMN . $cell->getRow(); if ($this->functionNameTranslations->getCell($categoryCheckCell)->getValue() != '') { return true; } return false; } private function log(string $message): void { if ($this->verbose === false) { return; } echo $message, self::EOL; } } ================================================ FILE: mkdocs.yml ================================================ site_name: PhpSpreadsheet Documentation repo_url: https://github.com/PHPOffice/phpspreadsheet edit_uri: edit/master/docs/ theme: readthedocs extra_css: - extra/extra.css extra_javascript: - extra/extrajs.js markdown_extensions: - md_in_html ================================================ FILE: phpstan-baseline.neon ================================================ parameters: ignoreErrors: - message: '#^Parameter \#1 \$array of function array_multisort expects array, mixed given\.$#' identifier: argument.type count: 1 path: src/PhpSpreadsheet/Calculation/LookupRef/Sort.php - message: '#^Cannot access offset 0 on mixed\.$#' identifier: offsetAccess.nonOffsetAccessible count: 1 path: src/PhpSpreadsheet/ReferenceHelper.php - message: '#^Parameter \#1 \$string of function trim expects string, mixed given\.$#' identifier: argument.type count: 1 path: src/PhpSpreadsheet/ReferenceHelper.php ================================================ FILE: phpstan.neon.dist ================================================ includes: - phpstan-baseline.neon - vendor/phpstan/phpstan-phpunit/extension.neon - vendor/phpstan/phpstan-phpunit/rules.neon - vendor/composer/pcre/extension.neon - vendor/phpstan/phpstan/conf/bleedingEdge.neon - vendor/phpstan/phpstan-deprecation-rules/rules.neon parameters: level: 10 paths: - samples/ - src/ - tests/ - infra/ - bin/ excludePaths: - src/PhpSpreadsheet/Calculation/FormulaParser.php - src/PhpSpreadsheet/Calculation/FormulaToken.php - src/PhpSpreadsheet/Chart/Renderer/JpGraph.php - src/PhpSpreadsheet/Chart/Renderer/JpGraphRendererBase.php - src/PhpSpreadsheet/Collection/Memory/SimpleCache1.php - src/PhpSpreadsheet/Collection/Memory/SimpleCache3.php - src/PhpSpreadsheet/Writer/ZipStream2.php - src/PhpSpreadsheet/Writer/ZipStream3.php - tests/PhpSpreadsheetTests/Calculation/FormulaParserTest.php - tests/PhpSpreadsheetTests/Writer/Xlsx/ArrayFunctions2Test.php parallel: processTimeout: 300.0 ignoreErrors: # Accept a bit anything for assert methods - '~^Parameter \#2 .* of static method PHPUnit\\Framework\\Assert\:\:assert\w+\(\) expects .*, .* given\.$~' - '~Method .*rovider.* return type has no value type specified in iterable type array\.$~' - '~Method .*rovider.* should return array but returns mixed\.$~' - '~.* has parameter \$expectedResult with no value type specified in iterable type array\.$~' #- identifier: missingType.iterableValue ================================================ FILE: phpunit.xml.dist ================================================ ./tests/PhpSpreadsheetTests ./src ================================================ FILE: samples/Autofilter/10_Autofilter.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Year') ->setCellValue('B1', 'Quarter') ->setCellValue('C1', 'Country') ->setCellValue('D1', 'Sales'); $dataArray = [ ['2010', 'Q1', 'United States', 790], ['2010', 'Q2', 'United States', 730], ['2010', 'Q3', 'United States', 860], ['2010', 'Q4', 'United States', 850], ['2011', 'Q1', 'United States', 800], ['2011', 'Q2', 'United States', 700], ['2011', 'Q3', 'United States', 900], ['2011', 'Q4', 'United States', 950], ['2010', 'Q1', 'Belgium', 380], ['2010', 'Q2', 'Belgium', 390], ['2010', 'Q3', 'Belgium', 420], ['2010', 'Q4', 'Belgium', 460], ['2011', 'Q1', 'Belgium', 400], ['2011', 'Q2', 'Belgium', 350], ['2011', 'Q3', 'Belgium', 450], ['2011', 'Q4', 'Belgium', 500], ['2010', 'Q1', 'UK', 690], ['2010', 'Q2', 'UK', 610], ['2010', 'Q3', 'UK', 620], ['2010', 'Q4', 'UK', 600], ['2011', 'Q1', 'UK', 720], ['2011', 'Q2', 'UK', 650], ['2011', 'Q3', 'UK', 580], ['2011', 'Q4', 'UK', 510], ['2010', 'Q1', 'France', 510], ['2010', 'Q2', 'France', 490], ['2010', 'Q3', 'France', 460], ['2010', 'Q4', 'France', 590], ['2011', 'Q1', 'France', 620], ['2011', 'Q2', 'France', 650], ['2011', 'Q3', 'France', 415], ['2011', 'Q4', 'France', 570], ['2010', 'Q1', 'Germany', 720], ['2010', 'Q2', 'Germany', 680], ['2010', 'Q3', 'Germany', 640], ['2010', 'Q4', 'Germany', 660], ['2011', 'Q1', 'Germany', 680], ['2011', 'Q2', 'Germany', 620], ['2011', 'Q3', 'Germany', 710], ['2011', 'Q4', 'Germany', 690], ['2010', 'Q1', 'Spain', 510], ['2010', 'Q2', 'Spain', 490], ['2010', 'Q3', 'Spain', 470], ['2010', 'Q4', 'Spain', 420], ['2011', 'Q1', 'Spain', 460], ['2011', 'Q2', 'Spain', 390], ['2011', 'Q3', 'Spain', 430], ['2011', 'Q4', 'Spain', 415], ['2010', 'Q1', 'Italy', 440], ['2010', 'Q2', 'Italy', 410], ['2010', 'Q3', 'Italy', 420], ['2010', 'Q4', 'Italy', 450], ['2011', 'Q1', 'Italy', 430], ['2011', 'Q2', 'Italy', 370], ['2011', 'Q3', 'Italy', 350], ['2011', 'Q4', 'Italy', 335], ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A2'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, false, true), true); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true); // Set autofilter $filterRange = $spreadsheet->getActiveSheet()->calculateWorksheetDimension(); $helper->log("Set autofilter for cells {$filterRange}"); // Always include the complete filter range if you can! // Excel does support setting only the caption // row, but that's not a best practise... $spreadsheet->getActiveSheet()->setAutoFilter($filterRange); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Autofilter/10_Autofilter_dynamic_dates.php ================================================ log('Add data'); $sheet = $spreadsheet->createSheet(); $sheet->setTitle($rule); $sheet->getCell('A1')->setValue('Date'); $row = 1; $date = new DateTime(); $year = (int) $date->format('Y'); $month = (int) $date->format('m'); $day = (int) $date->format('d'); $yearMinus2 = $year - 2; $sheet->getCell('B1')->setValue("=DATE($year, $month, $day)"); // Each day for two weeks before today through 2 weeks after for ($dayOffset = -14; $dayOffset < 14; ++$dayOffset) { ++$row; $sheet->getCell("A$row")->setValue("=B1+($dayOffset)"); } // First and last day of each month, starting with January 2 years before, // through December 2 years after. for ($monthOffset = 0; $monthOffset < 48; ++$monthOffset) { ++$row; $sheet->getCell("A$row")->setValue("=DATE($yearMinus2, $monthOffset, 1)"); ++$row; $sheet->getCell("A$row")->setValue("=DATE($yearMinus2, $monthOffset + 1, 0)"); } $sheet->getStyle("A2:A$row")->getNumberFormat()->setFormatCode('yyyy-mm-dd'); $sheet->getStyle('B1')->getNumberFormat()->setFormatCode('yyyy-mm-dd'); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); if ($displayInitialWorksheet) { $helper->log('Unfiltered Dates'); $helper->displayGrid($sheet->toArray(null, true, true, true)); } $helper->log("Filter for $rule"); $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $autoFilter->setRange("A1:A{$row}"); $columnFilter = $autoFilter->getColumn('A'); $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); $columnFilter->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, '', $rule) ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); $sheet->setSelectedCell('B1'); $helper->log('Execute filtering (apply the filter rules)'); $autoFilter->showHideRows(); $helper->log('Filtered Dates'); $helper->displayGrid($sheet->toArray(null, true, true, true, true)); } // Create new Spreadsheet object /** @var Sample $helper */ $helper->log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Owen Leibman') ->setLastModifiedBy('Owen Leibman') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); $ruleNames = [ Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, Rule::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, Rule::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, ]; // Create the worksheets foreach ($ruleNames as $index => $ruleName) { createSheet($helper, $spreadsheet, $ruleName, $index === 0); } $spreadsheet->removeSheetByIndex(0); $spreadsheet->setActiveSheetIndex(0); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Autofilter/10_Autofilter_selection_1.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Year') ->setCellValue('B1', 'Period') ->setCellValue('C1', 'Country') ->setCellValue('D1', 'Date') ->setCellValue('E1', 'Sales') ->setCellValue('F1', 'Expenditure'); $dateTime = new DateTime(); $startYear = $endYear = $currentYear = (int) $dateTime->format('Y'); --$startYear; ++$endYear; $years = range($startYear, $endYear); $periods = range(1, 12); $countries = [ 'United States', 'UK', 'France', 'Germany', 'Italy', 'Spain', 'Portugal', 'Japan', ]; $row = 2; foreach ($years as $year) { foreach ($periods as $period) { foreach ($countries as $country) { $dateString = sprintf('%04d-%02d-01T00:00:00', $year, $period); $dateTime = new DateTime($dateString); $endDays = (int) $dateTime->format('t'); for ($i = 1; $i <= $endDays; ++$i) { $eDate = Date::formattedPHPToExcel( $year, $period, $i ); $value = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); $salesValue = $invoiceValue = null; $incomeOrExpenditure = mt_rand(-1, 1); if ($incomeOrExpenditure == -1) { $expenditure = mt_rand(-1000, -500) * (1 + (mt_rand(-1, 1) / 4)); $income = null; } elseif ($incomeOrExpenditure == 1) { $expenditure = mt_rand(-1000, -500) * (1 + (mt_rand(-1, 1) / 4)); $income = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); } else { $expenditure = null; $income = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); } $dataArray = [$year, $period, $country, $eDate, $income, $expenditure, ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A' . $row++); } } } } --$row; // Set styling $helper->log('Set styling'); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->getAlignment()->setWrapText(true); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(12.5); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(10.5); $spreadsheet->getActiveSheet()->getStyle('D2:D' . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD); $spreadsheet->getActiveSheet()->getStyle('E2:F' . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD_INTEGER); $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(14); $spreadsheet->getActiveSheet()->freezePane('A2'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true)); // Set autofilter range $filterRange = $spreadsheet->getActiveSheet()->calculateWorksheetDimension(); $helper->log("Set autofilter for cells {$filterRange}"); // Always include the complete filter range if you can! // Excel does support setting only the caption row, but that's not a best practise... $spreadsheet->getActiveSheet()->setAutoFilter($filterRange); // Set active filters $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $helper->log('Set active filters'); // Filter the Country column on a filter value of countries beginning with the letter U (or Japan) // We use * as a wildcard, so specify as U* and using a wildcard requires customFilter $autoFilter->getColumn('C') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'u*') ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); $helper->log('Set country code filter (Column C) to countries beginning with "U" ("United States" and "UK")'); $autoFilter->getColumn('C') ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'japan') ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); $helper->log('Add "Japan" to the country code filter (Column C)'); // Filter the Date column on a filter value of the last day of every period of the current year // We use a dateGroup ruletype for this, although it is still a standard filter foreach ($periods as $period) { $dateString = sprintf('%04d-%02d-01T00:00:00', $currentYear, $period); $dateTime = new DateTime($dateString); $endDate = (int) $dateTime->format('t'); $autoFilter->getColumn('D') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) ->createRule() ->setRule( Rule::AUTOFILTER_COLUMN_RULE_EQUAL, [ 'year' => $currentYear, 'month' => $period, 'day' => $endDate, ] ) ->setRuleType(Rule::AUTOFILTER_RULETYPE_DATEGROUP); } $helper->log('Add filter on the Date (Column D) to display only rows for the last day of each month'); // Display only sales values that are blank // Standard filter, operator equals, and value of NULL or empty space $autoFilter->getColumn('E') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, ''); $helper->log('Add filter on Sales Values (Column E) to display only blank values'); $helper->log('NOTE: We don\'t apply the filter rules in this example, so we can\'t see the result here; although Excel will apply the rules when the file is loaded'); $helper->log('See 10_Autofilter_selection_display.php for an example that actually executes the filter rules'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Autofilter/10_Autofilter_selection_2.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Year') ->setCellValue('B1', 'Period') ->setCellValue('C1', 'Country') ->setCellValue('D1', 'Date') ->setCellValue('E1', 'Sales') ->setCellValue('F1', 'Expenditure'); $dateTime = new DateTime(); $startYear = $endYear = $currentYear = (int) $dateTime->format('Y'); --$startYear; ++$endYear; $years = range($startYear, $endYear); $periods = range(1, 12); $countries = [ 'United States', 'UK', 'France', 'Germany', 'Italy', 'Spain', 'Portugal', 'Japan', ]; $row = 2; foreach ($years as $year) { foreach ($periods as $period) { foreach ($countries as $country) { $dateString = sprintf('%04d-%02d-01T00:00:00', $year, $period); $dateTime = new DateTime($dateString); $endDays = (int) $dateTime->format('t'); for ($i = 1; $i <= $endDays; ++$i) { $eDate = Date::formattedPHPToExcel( $year, $period, $i ); $value = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); $salesValue = $invoiceValue = null; $incomeOrExpenditure = mt_rand(-1, 1); if ($incomeOrExpenditure == -1) { $expenditure = mt_rand(-1000, -500) * (1 + (mt_rand(-1, 1) / 4)); $income = null; } elseif ($incomeOrExpenditure == 1) { $expenditure = mt_rand(-1000, -500) * (1 + (mt_rand(-1, 1) / 4)); $income = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); } else { $expenditure = null; $income = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); } $dataArray = [$year, $period, $country, $eDate, $income, $expenditure, ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A' . $row++); } } } } --$row; // Set styling $helper->log('Set styling'); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->getAlignment()->setWrapText(true); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(12.5); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(10.5); $spreadsheet->getActiveSheet()->getStyle('D2:D' . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD); $spreadsheet->getActiveSheet()->getStyle('E2:F' . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD_INTEGER); $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(14); $spreadsheet->getActiveSheet()->freezePane('A2'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true)); // Set autofilter range $filterRange = $spreadsheet->getActiveSheet()->calculateWorksheetDimension(); $helper->log("Set autofilter for cells {$filterRange}"); // Always include the complete filter range if you can! // Excel does support setting only the caption row, but that's not a best practise... $spreadsheet->getActiveSheet()->setAutoFilter($filterRange); // Set active filters $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $helper->log('Set active filters'); // Filter the Country column on a filter value of Germany // As it's just a simple value filter, we can use FILTERTYPE_FILTER $autoFilter->getColumn('C') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'Germany'); $helper->log('Set country code filter (Column C) to "Germany"'); // Filter the Date column on a filter value of the year to date $autoFilter->getColumn('D') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, '', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE) ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); $helper->log('Add filter on the Date (Column D) to display year to date'); // Display only sales values that are between 400 and 600 $autoFilter->getColumn('E') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 400) ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); $autoFilter->getColumn('E') ->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, 600) ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); $helper->log('Add filter on Sales Values (Column E) between 400 and 600'); $helper->log('NOTE: We don\'t apply the filter rules in this example, so we can\'t see the result here; although Excel will apply the rules when the file is loaded'); $helper->log('See 10_Autofilter_selection_display.php for an example that actually executes the filter rules inside PhpSpreadsheet'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Autofilter/10_Autofilter_selection_display.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Year') ->setCellValue('B1', 'Period') ->setCellValue('C1', 'Country') ->setCellValue('D1', 'Date') ->setCellValue('E1', 'Sales') ->setCellValue('F1', 'Expenditure'); $dateTime = new DateTime(); $startYear = $endYear = $currentYear = (int) $dateTime->format('Y'); --$startYear; ++$endYear; $years = range($startYear, $endYear); $periods = range(1, 12); $countries = [ 'United States', 'UK', 'France', 'Germany', 'Italy', 'Spain', 'Portugal', 'Japan', ]; $row = 2; foreach ($years as $year) { foreach ($periods as $period) { foreach ($countries as $country) { $dateString = sprintf('%04d-%02d-01T00:00:00', $year, $period); $dateTime = new DateTime($dateString); $endDays = (int) $dateTime->format('t'); for ($i = 1; $i <= $endDays; ++$i) { $eDate = Date::formattedPHPToExcel( $year, $period, $i ); $value = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); $salesValue = $invoiceValue = null; $incomeOrExpenditure = mt_rand(-1, 1); if ($incomeOrExpenditure == -1) { $expenditure = mt_rand(-1000, -500) * (1 + (mt_rand(-1, 1) / 4)); $income = null; } elseif ($incomeOrExpenditure == 1) { $expenditure = mt_rand(-1000, -500) * (1 + (mt_rand(-1, 1) / 4)); $income = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); } else { $expenditure = null; $income = mt_rand(500, 1000) * (1 + (mt_rand(-1, 1) / 4)); } $dataArray = [$year, $period, $country, $eDate, $income, $expenditure, ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A' . $row++); } } } } --$row; // Set styling $helper->log('Set styling'); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->getAlignment()->setWrapText(true); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(12.5); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(10.5); $spreadsheet->getActiveSheet()->getStyle('D2:D' . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD); $spreadsheet->getActiveSheet()->getStyle('E2:F' . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD_INTEGER); $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(14); $spreadsheet->getActiveSheet()->freezePane('A2'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true)); // Set autofilter range $filterRange = $spreadsheet->getActiveSheet()->calculateWorksheetDimension(); $helper->log("Set autofilter for cells {$filterRange}"); // Always include the complete filter range if you can! // Excel does support setting only the caption row, but that's not a best practise... $spreadsheet->getActiveSheet()->setAutoFilter($filterRange); // Set active filters $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $helper->log('Set active filters'); // Filter the Country column on a filter value of countries beginning with the letter U (or Japan) // We use * as a wildcard, so specify as U* and using a wildcard requires customFilter $autoFilter->getColumn('C') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'u*') ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); $helper->log('Set country code filter (Column C) to countries beginning with "U" ("United States" and "UK")'); $autoFilter->getColumn('C') ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, 'japan') ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); $helper->log('Add "Japan" to the country code filter (Column C)'); // Filter the Date column on a filter value of the last day of every period of the current year // We us a dateGroup ruletype for this, although it is still a standard filter foreach ($periods as $period) { $dateString = sprintf('%04d-%02d-01T00:00:00', $currentYear, $period); $dateTime = new DateTime($dateString); $endDate = (int) $dateTime->format('t'); $autoFilter->getColumn('D') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) ->createRule() ->setRule( Rule::AUTOFILTER_COLUMN_RULE_EQUAL, [ 'year' => $currentYear, 'month' => $period, 'day' => $endDate, ] ) ->setRuleType(Rule::AUTOFILTER_RULETYPE_DATEGROUP); } $helper->log('Add filter on the Date (Column D) to display only rows for the last day of each month'); // Display only sales values that are blank // Standard filter, operator equals, and value of NULL $autoFilter->getColumn('E') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) ->createRule() ->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, ''); $helper->log('Add filter on Sales Values (Column E) to display only blank values'); // Execute filtering $helper->log('Execute filtering (apply the filter rules)'); $autoFilter->showHideRows(); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); // Display Results of filtering $helper->log('Display filtered rows'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true, true)); ================================================ FILE: samples/Basic/01_Simple.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties() ->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!') ->setCellValue('C1', 'Hello') ->setCellValue('D2', 'world!'); // Miscellaneous glyphs, UTF-8 $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', 'Miscellaneous glyphs') ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç'); $spreadsheet->getActiveSheet() ->setCellValue('A8', "Hello\nWorld"); $spreadsheet->getActiveSheet() ->getRowDimension(8) ->setRowHeight(-1); $spreadsheet->getActiveSheet() ->getStyle('A8') ->getAlignment() ->setWrapText(true); $value = "-ValueA\n-Value B\n-Value C"; $spreadsheet->getActiveSheet() ->setCellValue('A10', $value); $spreadsheet->getActiveSheet() ->getRowDimension(10) ->setRowHeight(-1); $spreadsheet->getActiveSheet() ->getStyle('A10') ->getAlignment() ->setWrapText(true); $spreadsheet->getActiveSheet() ->getStyle('A10') ->setQuotePrefix(true); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet() ->setTitle('Simple'); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Xls', 'Ods']); ================================================ FILE: samples/Basic/01_Simple_download_ods.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); // Set document properties $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'); // Add some data $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!') ->setCellValue('C1', 'Hello') ->setCellValue('D2', 'world!'); // Miscellaneous glyphs, UTF-8 $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', 'Miscellaneous glyphs') ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç'); // Rename worksheet $spreadsheet->getActiveSheet()->setTitle('Simple'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); // Redirect output to a client’s web browser (Ods) header('Content-Type: application/vnd.oasis.opendocument.spreadsheet'); header('Content-Disposition: attachment;filename="01simple.ods"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 $writer = IOFactory::createWriter($spreadsheet, 'Ods'); $writer->save('php://output'); exit; ================================================ FILE: samples/Basic/01_Simple_download_pdf.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); // Set document properties $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PDF Test Document') ->setSubject('PDF Test Document') ->setDescription('Test document for PDF, generated using PHP classes.') ->setKeywords('pdf php') ->setCategory('Test result file'); // Add some data $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!') ->setCellValue('C1', 'Hello') ->setCellValue('D2', 'world!'); // Miscellaneous glyphs, UTF-8 $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', 'Miscellaneous glyphs') ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç'); // Rename worksheet $spreadsheet->getActiveSheet()->setTitle('Simple'); $spreadsheet->getActiveSheet()->setShowGridLines(false); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); IOFactory::registerWriter('Pdf', PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class); // Redirect output to a client’s web browser (PDF) header('Content-Type: application/pdf'); header('Content-Disposition: attachment;filename="01simple.pdf"'); header('Cache-Control: max-age=0'); $writer = IOFactory::createWriter($spreadsheet, 'Pdf'); $writer->save('php://output'); exit; ================================================ FILE: samples/Basic/01_Simple_download_xls.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); // Set document properties $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'); // Add some data $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!') ->setCellValue('C1', 'Hello') ->setCellValue('D2', 'world!'); // Miscellaneous glyphs, UTF-8 $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', 'Miscellaneous glyphs') ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç'); // Rename worksheet $spreadsheet->getActiveSheet()->setTitle('Simple'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); // Redirect output to a client’s web browser (Xls) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="01simple.xls"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 $writer = IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('php://output'); exit; ================================================ FILE: samples/Basic/01_Simple_download_xlsx.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); // Set document properties $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'); // Add some data $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!') ->setCellValue('C1', 'Hello') ->setCellValue('D2', 'world!'); // Miscellaneous glyphs, UTF-8 $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', 'Miscellaneous glyphs') ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç'); // Rename worksheet $spreadsheet->getActiveSheet()->setTitle('Simple'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); // Redirect output to a client’s web browser (Xlsx) header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="01simple.xlsx"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('php://output'); exit; ================================================ FILE: samples/Basic/02_Types.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Set default font $helper->log('Set default font'); $spreadsheet->getDefaultStyle() ->getFont() ->setName('Arial') ->setSize(10); // Add some data, resembling some different data types $helper->log('Add some data'); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'String') ->setCellValue('B1', 'Simple') ->setCellValue('C1', 'PhpSpreadsheet'); $spreadsheet->getActiveSheet() ->setCellValue('A2', 'String') ->setCellValue('B2', 'Symbols') ->setCellValue('C2', '!+&=()~§±æþ'); $spreadsheet->getActiveSheet() ->setCellValue('A3', 'String') ->setCellValue('B3', 'UTF-8') ->setCellValue('C3', 'Создать MS Excel Книги из PHP скриптов'); $spreadsheet->getActiveSheet() ->setCellValue('A4', 'Number') ->setCellValue('B4', 'Integer') ->setCellValue('C4', 12); $spreadsheet->getActiveSheet() ->setCellValue('A5', 'Number') ->setCellValue('B5', 'Float') ->setCellValue('C5', 34.56); $spreadsheet->getActiveSheet() ->setCellValue('A6', 'Number') ->setCellValue('B6', 'Negative') ->setCellValue('C6', -7.89); $spreadsheet->getActiveSheet() ->setCellValue('A7', 'Boolean') ->setCellValue('B7', 'True') ->setCellValue('C7', true); $spreadsheet->getActiveSheet() ->setCellValue('A8', 'Boolean') ->setCellValue('B8', 'False') ->setCellValue('C8', false); $dateTimeNow = time(); $spreadsheet->getActiveSheet() ->setCellValue('A9', 'Date/Time') ->setCellValue('B9', 'Date') ->setCellValue('C9', Date::PHPToExcel($dateTimeNow)); $spreadsheet->getActiveSheet() ->getStyle('C9') ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD); $spreadsheet->getActiveSheet() ->setCellValue('A10', 'Date/Time') ->setCellValue('B10', 'Time') ->setCellValue('C10', Date::PHPToExcel($dateTimeNow)); $spreadsheet->getActiveSheet() ->getStyle('C10') ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); $spreadsheet->getActiveSheet() ->setCellValue('A11', 'Date/Time') ->setCellValue('B11', 'Date and Time') ->setCellValue('C11', Date::PHPToExcel($dateTimeNow)); $spreadsheet->getActiveSheet() ->getStyle('C11') ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME); $spreadsheet->getActiveSheet() ->setCellValue('A12', 'NULL') ->setCellValue('C12', null); $richText = new RichText(); $richText->createText('你好 '); $payable = $richText->createTextRun('你 好 吗?'); $payable->getFontOrThrow()->setBold(true); $payable->getFontOrThrow()->setItalic(true); $payable->getFontOrThrow()->setColor(new Color(Color::COLOR_DARKGREEN)); $richText->createText(', unless specified otherwise on the invoice.'); $spreadsheet->getActiveSheet() ->setCellValue('A13', 'Rich Text') ->setCellValue('C13', $richText); $richText2 = new RichText(); $richText2->createText("black text\n"); $red = $richText2->createTextRun('red text'); $red->getFontOrThrow()->setColor(new Color(Color::COLOR_RED)); $spreadsheet->getActiveSheet() ->getCell('C14') ->setValue($richText2); $spreadsheet->getActiveSheet() ->getStyle('C14') ->getAlignment()->setWrapText(true); $spreadsheet->getActiveSheet()->setCellValue('A17', 'Hyperlink'); $spreadsheet->getActiveSheet() ->setCellValue('C17', 'PhpSpreadsheet Web Site'); $spreadsheet->getActiveSheet() ->getCell('C17') ->getHyperlink() ->setUrl('https://github.com/PHPOffice/PhpSpreadsheet') ->setTooltip('Navigate to PhpSpreadsheet website'); $spreadsheet->getActiveSheet()->getStyle('C17')->getFont()->setHyperlinkTheme(); $spreadsheet->getActiveSheet() ->setCellValue('C18', '=HYPERLINK("mailto:abc@def.com","abc@def.com")'); $spreadsheet->getActiveSheet()->getStyle('C18')->getFont()->setHyperlinkTheme(); $spreadsheet->getActiveSheet() ->setCellValue('A20', 'String') ->setCellValue('B20', 'inline') ->setCellValueExplicit('C20', 'This will not be added to sharedStrings.xml', DataType::TYPE_INLINE); $spreadsheet->getActiveSheet() ->getColumnDimension('B') ->setAutoSize(true); $spreadsheet->getActiveSheet() ->getColumnDimension('C') ->setAutoSize(true); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Datatypes'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/03_Formulas.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Add some data, we will use some formulas here $helper->log('Add some data'); $spreadsheet->getActiveSheet() ->setCellValue('A5', 'Sum:'); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Range #1') ->setCellValue('B2', 3) ->setCellValue('B3', 7) ->setCellValue('B4', 13) ->setCellValue('B5', '=SUM(B2:B4)'); $helper->log('Sum of Range #1 is ' . $spreadsheet->getActiveSheet()->getCell('B5')->getCalculatedValueString()); $spreadsheet->getActiveSheet()->setCellValue('C1', 'Range #2') ->setCellValue('C2', 5) ->setCellValue('C3', 11) ->setCellValue('C4', 17) ->setCellValue('C5', '=SUM(C2:C4)'); $helper->log('Sum of Range #2 is ' . $spreadsheet->getActiveSheet()->getCell('C5')->getCalculatedValueString()); $spreadsheet->getActiveSheet() ->setCellValue('A7', 'Total of both ranges:'); $spreadsheet->getActiveSheet() ->setCellValue('B7', '=SUM(B5:C5)'); $helper->log('Sum of both Ranges is ' . $spreadsheet->getActiveSheet()->getCell('B7')->getCalculatedValueString()); $spreadsheet->getActiveSheet() ->setCellValue('A8', 'Minimum of both ranges:'); $spreadsheet->getActiveSheet() ->setCellValue('B8', '=MIN(B2:C4)'); $helper->log('Minimum value in either Range is ' . $spreadsheet->getActiveSheet()->getCell('B8')->getCalculatedValueString()); $spreadsheet->getActiveSheet() ->setCellValue('A9', 'Maximum of both ranges:'); $spreadsheet->getActiveSheet() ->setCellValue('B9', '=MAX(B2:C4)'); $helper->log('Maximum value in either Range is ' . $spreadsheet->getActiveSheet()->getCell('B9')->getCalculatedValueString()); $spreadsheet->getActiveSheet() ->setCellValue('A10', 'Average of both ranges:'); $spreadsheet->getActiveSheet() ->setCellValue('B10', '=AVERAGE(B2:C4)'); $helper->log('Average value of both Ranges is ' . $spreadsheet->getActiveSheet()->getCell('B10')->getCalculatedValueString()); $spreadsheet->getActiveSheet() ->getColumnDimension('A') ->setAutoSize(true); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet() ->setTitle('Formulas'); // // If we set Pre Calculated Formulas to true then PhpSpreadsheet will calculate all formulae in the // workbook before saving. This adds time and memory overhead, and can cause some problems with formulae // using functions or features (such as array formulae) that aren't yet supported by the calculation engine // If the value is false (the default) for the Xlsx Writer, then MS Excel (or the application used to // open the file) will need to recalculate values itself to guarantee that the correct results are available. // //$writer->setPreCalculateFormulas(true); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/04_Printing.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Add some data, we will use printing features $helper->log('Add some data'); for ($i = 1; $i < 200; ++$i) { $spreadsheet->getActiveSheet()->setCellValue('A' . $i, $i); $spreadsheet->getActiveSheet()->setCellValue('B' . $i, 'Test value'); } // Set header and footer. When no different headers for odd/even are used, odd header is assumed. $helper->log('Set header/footer'); $spreadsheet->getActiveSheet() ->getHeaderFooter() ->setOddHeader('&L&G&C&HPlease treat this document as confidential!'); $spreadsheet->getActiveSheet() ->getHeaderFooter() ->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N'); // Add a drawing to the header $helper->log('Add a drawing to the header'); $drawing = new HeaderFooterDrawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setPath(__DIR__ . '/../images/PhpSpreadsheet_logo.png'); $drawing->setHeight(36); $spreadsheet->getActiveSheet() ->getHeaderFooter() ->addImage($drawing, HeaderFooter::IMAGE_HEADER_LEFT); // Set page orientation and size $helper->log('Set page orientation and size'); $spreadsheet->getActiveSheet() ->getPageSetup() ->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $spreadsheet->getActiveSheet() ->getPageSetup() ->setPaperSize(PageSetup::PAPERSIZE_A4); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Printing'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/05_Feature_demo.php ================================================ write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/05_UnexpectedCharacters.php ================================================ write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/06_Largescale.php ================================================ write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/07_Reader.php ================================================ getTemporaryFilename(); $writer = new Xlsx($sampleSpreadsheet); $writer->save($filename); $callStartTime = microtime(true); $spreadsheet = IOFactory::load($filename); $helper->logRead('Xlsx', $filename, $callStartTime); // Save $helper->write($spreadsheet, __FILE__); unlink($filename); ================================================ FILE: samples/Basic/08_Conditional_formatting.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Create a first sheet, representing sales data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Description') ->setCellValue('B1', 'Amount'); $spreadsheet->getActiveSheet()->setCellValue('A2', 'Paycheck received') ->setCellValue('B2', 100); $spreadsheet->getActiveSheet()->setCellValue('A3', 'Cup of coffee bought') ->setCellValue('B3', -1.5); $spreadsheet->getActiveSheet()->setCellValue('A4', 'Cup of coffee bought') ->setCellValue('B4', -1.5); $spreadsheet->getActiveSheet()->setCellValue('A5', 'Cup of tea bought') ->setCellValue('B5', -1.2); $spreadsheet->getActiveSheet()->setCellValue('A6', 'Found some money') ->setCellValue('B6', 8); $spreadsheet->getActiveSheet()->setCellValue('A7', 'Total:') ->setCellValue('B7', '=SUM(B2:B6)'); // Set column widths $helper->log('Set column widths'); $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(30); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(12); // Add conditional formatting $helper->log('Add conditional formatting'); $conditional1 = new Conditional(); $conditional1->setConditionType(Conditional::CONDITION_CELLIS) ->setOperatorType(Conditional::OPERATOR_BETWEEN) ->addCondition('200') ->addCondition('400'); $conditional1->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_YELLOW); $conditional1->getStyle()->getFont()->setBold(true); $conditional1->getStyle()->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_INTEGER); $conditional2 = new Conditional(); $conditional2->setConditionType(Conditional::CONDITION_CELLIS) ->setOperatorType(Conditional::OPERATOR_LESSTHAN) ->addCondition('0'); $conditional2->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_RED); $conditional2->getStyle()->getFont()->setItalic(true); $conditional2->getStyle()->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_INTEGER); $conditional3 = new Conditional(); $conditional3->setConditionType(Conditional::CONDITION_CELLIS) ->setOperatorType(Conditional::OPERATOR_GREATERTHANOREQUAL) ->addCondition('0'); $conditional3->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_GREEN); $conditional3->getStyle()->getFont()->setItalic(true); $conditional3->getStyle()->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_INTEGER); $conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles(); $conditionalStyles[] = $conditional1; $conditionalStyles[] = $conditional2; $conditionalStyles[] = $conditional3; $spreadsheet->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles); // duplicate the conditional styles across a range of cells $helper->log('Duplicate the conditional formatting across a range of cells'); $spreadsheet->getActiveSheet()->duplicateConditionalStyle( $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles(), 'B3:B7' ); // Set fonts $helper->log('Set fonts'); $spreadsheet->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true); //$spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A7:B7')->getFont()->setBold(true); //$spreadsheet->getActiveSheet()->getStyle('B7')->getFont()->setBold(true); // Set header and footer. When no different headers for odd/even are used, odd header is assumed. $helper->log('Set header/footer'); $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BPersonal cash register&RPrinted on &D'); $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N'); // Set page orientation and size $helper->log('Set page orientation and size'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT); $spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Invoice'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/08_Conditional_formatting_2.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Create a first sheet, representing sales data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', '-0.5') ->setCellValue('A2', '-0.25') ->setCellValue('A3', '0.0') ->setCellValue('A4', '0.25') ->setCellValue('A5', '0.5') ->setCellValue('A6', '0.75') ->setCellValue('A7', '1.0') ->setCellValue('A8', '1.25'); $spreadsheet->getActiveSheet()->getStyle('A1:A8') ->getNumberFormat() ->setFormatCode( NumberFormat::FORMAT_PERCENTAGE_00 ); // Add conditional formatting $helper->log('Add conditional formatting'); $conditional1 = new Conditional(); $conditional1->setConditionType(Conditional::CONDITION_CELLIS) ->setOperatorType(Conditional::OPERATOR_LESSTHAN) ->addCondition('0'); $conditional1->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_RED); $conditional3 = new Conditional(); $conditional3->setConditionType(Conditional::CONDITION_CELLIS) ->setOperatorType(Conditional::OPERATOR_GREATERTHANOREQUAL) ->addCondition('1'); $conditional3->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_GREEN); $conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('A1')->getConditionalStyles(); $conditionalStyles[] = $conditional1; $conditionalStyles[] = $conditional3; $spreadsheet->getActiveSheet()->getStyle('A1')->setConditionalStyles($conditionalStyles); // duplicate the conditional styles across a range of cells $helper->log('Duplicate the conditional formatting across a range of cells'); $spreadsheet->getActiveSheet()->duplicateConditionalStyle( $spreadsheet->getActiveSheet()->getStyle('A1')->getConditionalStyles(), 'A2:A8' ); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic/09_Pagebreaks.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Create a first sheet $helper->log('Add data and page breaks'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname') ->setCellValue('B1', 'Lastname') ->setCellValue('C1', 'Phone') ->setCellValue('D1', 'Fax') ->setCellValue('E1', 'Is Client ?'); // Add data for ($i = 2; $i <= 50; ++$i) { $spreadsheet->getActiveSheet()->setCellValue('A' . $i, "FName $i"); $spreadsheet->getActiveSheet()->setCellValue('B' . $i, "LName $i"); $spreadsheet->getActiveSheet()->setCellValue('C' . $i, "PhoneNo $i"); $spreadsheet->getActiveSheet()->setCellValue('D' . $i, "FaxNo $i"); $spreadsheet->getActiveSheet()->setCellValue('E' . $i, true); // Add page breaks every 10 rows if ($i % 10 == 0) { // Add a page break $spreadsheet->getActiveSheet()->setBreak('A' . $i, Worksheet::BREAK_ROW); } } // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setTitle('Printing Options'); // Set print headers $spreadsheet->getActiveSheet() ->getHeaderFooter()->setOddHeader('&C&24&K0000FF&B&U&A'); $spreadsheet->getActiveSheet() ->getHeaderFooter()->setEvenHeader('&C&24&K0000FF&B&U&A'); // Set print footers $spreadsheet->getActiveSheet() ->getHeaderFooter()->setOddFooter('&R&D &T&C&F&LPage &P / &N'); $spreadsheet->getActiveSheet() ->getHeaderFooter()->setEvenFooter('&L&D &T&C&F&RPage &P / &N'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic1/11_Documentsecurity.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Hello'); $spreadsheet->getActiveSheet()->setCellValue('B2', 'world!'); $spreadsheet->getActiveSheet()->setCellValue('C1', 'Hello'); $spreadsheet->getActiveSheet()->setCellValue('D2', 'world!'); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Simple'); // Set document security $helper->log('Set document security'); $spreadsheet->getSecurity()->setLockWindows(true); $spreadsheet->getSecurity()->setLockStructure(true); $spreadsheet->getSecurity()->setWorkbookPassword('PhpSpreadsheet'); // Set sheet security $helper->log('Set sheet security'); $spreadsheet->getActiveSheet()->getProtection()->setPassword('PhpSpreadsheet'); // setSheet should be true in order to enable protection! $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); // The following are set to false, i.e. user is allowed to // sort, insert rows, or format cells without unprotecting sheet. $spreadsheet->getActiveSheet()->getProtection()->setSort(false); $spreadsheet->getActiveSheet()->getProtection()->setInsertRows(false); $spreadsheet->getActiveSheet()->getProtection()->setFormatCells(false); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic1/12_CellProtection.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->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'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Crouching'); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Tiger'); $spreadsheet->getActiveSheet()->setCellValue('A2', 'Hidden'); $spreadsheet->getActiveSheet()->setCellValue('B2', 'Dragon'); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Simple'); // Set document security $helper->log('Set cell protection'); // Set sheet security $helper->log('Set sheet security'); $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); $spreadsheet->getActiveSheet() ->getStyle('A2:B2') ->getProtection()->setLocked( Protection::PROTECTION_UNPROTECTED ); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic1/13_Calculation.php ================================================ log('List implemented functions'); $calc = Calculation::getInstance(); print_r($calc->getImplementedFunctionNames()); // Create new Spreadsheet object $helper->log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Add some data, we will use some formulas here $helper->log('Add some data and formulas'); $spreadsheet->getActiveSheet()->setCellValue('A14', 'Count:') ->setCellValue('A15', 'Sum:') ->setCellValue('A16', 'Max:') ->setCellValue('A17', 'Min:') ->setCellValue('A18', 'Average:') ->setCellValue('A19', 'Median:') ->setCellValue('A20', 'Mode:'); $spreadsheet->getActiveSheet()->setCellValue('A22', 'CountA:') ->setCellValue('A23', 'MaxA:') ->setCellValue('A24', 'MinA:'); $spreadsheet->getActiveSheet()->setCellValue('A26', 'StDev:') ->setCellValue('A27', 'StDevA:') ->setCellValue('A28', 'StDevP:') ->setCellValue('A29', 'StDevPA:'); $spreadsheet->getActiveSheet()->setCellValue('A31', 'DevSq:') ->setCellValue('A32', 'Var:') ->setCellValue('A33', 'VarA:') ->setCellValue('A34', 'VarP:') ->setCellValue('A35', 'VarPA:'); $spreadsheet->getActiveSheet()->setCellValue('A37', 'Date:'); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Range 1') ->setCellValue('B2', 2) ->setCellValue('B3', 8) ->setCellValue('B4', 10) ->setCellValue('B5', true) ->setCellValue('B6', false) ->setCellValue('B7', 'Text String') ->setCellValue('B9', '22') ->setCellValue('B10', 4) ->setCellValue('B11', 6) ->setCellValue('B12', 12); $spreadsheet->getActiveSheet()->setCellValue('B14', '=COUNT(B2:B12)') ->setCellValue('B15', '=SUM(B2:B12)') ->setCellValue('B16', '=MAX(B2:B12)') ->setCellValue('B17', '=MIN(B2:B12)') ->setCellValue('B18', '=AVERAGE(B2:B12)') ->setCellValue('B19', '=MEDIAN(B2:B12)') ->setCellValue('B20', '=MODE(B2:B12)'); $spreadsheet->getActiveSheet()->setCellValue('B22', '=COUNTA(B2:B12)') ->setCellValue('B23', '=MAXA(B2:B12)') ->setCellValue('B24', '=MINA(B2:B12)'); $spreadsheet->getActiveSheet()->setCellValue('B26', '=STDEV(B2:B12)') ->setCellValue('B27', '=STDEVA(B2:B12)') ->setCellValue('B28', '=STDEVP(B2:B12)') ->setCellValue('B29', '=STDEVPA(B2:B12)'); $spreadsheet->getActiveSheet()->setCellValue('B31', '=DEVSQ(B2:B12)') ->setCellValue('B32', '=VAR(B2:B12)') ->setCellValue('B33', '=VARA(B2:B12)') ->setCellValue('B34', '=VARP(B2:B12)') ->setCellValue('B35', '=VARPA(B2:B12)'); $spreadsheet->getActiveSheet()->setCellValue('B37', '=DATE(2007, 12, 21)') ->setCellValue('B38', '=DATEDIF( DATE(2007, 12, 21), DATE(2007, 12, 22), "D" )') ->setCellValue('B39', '=DATEVALUE("01-Feb-2006 10:06 AM")') ->setCellValue('B40', '=DAY( DATE(2006, 1, 2) )') ->setCellValue('B41', '=DAYS360( DATE(2002, 2, 3), DATE(2005, 5, 31) )'); $spreadsheet->getActiveSheet()->setCellValue('C1', 'Range 2') ->setCellValue('C2', 1) ->setCellValue('C3', 2) ->setCellValue('C4', 2) ->setCellValue('C5', 3) ->setCellValue('C6', 3) ->setCellValue('C7', 3) ->setCellValue('C8', '0') ->setCellValue('C9', 4) ->setCellValue('C10', 4) ->setCellValue('C11', 4) ->setCellValue('C12', 4); $spreadsheet->getActiveSheet()->setCellValue('C14', '=COUNT(C2:C12)') ->setCellValue('C15', '=SUM(C2:C12)') ->setCellValue('C16', '=MAX(C2:C12)') ->setCellValue('C17', '=MIN(C2:C12)') ->setCellValue('C18', '=AVERAGE(C2:C12)') ->setCellValue('C19', '=MEDIAN(C2:C12)') ->setCellValue('C20', '=MODE(C2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('C22', '=COUNTA(C2:C12)') ->setCellValue('C23', '=MAXA(C2:C12)') ->setCellValue('C24', '=MINA(C2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('C26', '=STDEV(C2:C12)') ->setCellValue('C27', '=STDEVA(C2:C12)') ->setCellValue('C28', '=STDEVP(C2:C12)') ->setCellValue('C29', '=STDEVPA(C2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('C31', '=DEVSQ(C2:C12)') ->setCellValue('C32', '=VAR(C2:C12)') ->setCellValue('C33', '=VARA(C2:C12)') ->setCellValue('C34', '=VARP(C2:C12)') ->setCellValue('C35', '=VARPA(C2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('D1', 'Range 3') ->setCellValue('D2', 2) ->setCellValue('D3', 3) ->setCellValue('D4', 4); $spreadsheet->getActiveSheet()->setCellValue('D14', '=((D2 * D3) + D4) & " should be 10"'); $spreadsheet->getActiveSheet()->setCellValue('E12', 'Other functions') ->setCellValue('E14', '=PI()') ->setCellValue('E15', '=RAND()') ->setCellValue('E16', '=RANDBETWEEN(5, 10)'); $spreadsheet->getActiveSheet()->setCellValue('E17', 'Count of both ranges:') ->setCellValue('F17', '=COUNT(B2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('E18', 'Total of both ranges:') ->setCellValue('F18', '=SUM(B2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('E19', 'Maximum of both ranges:') ->setCellValue('F19', '=MAX(B2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('E20', 'Minimum of both ranges:') ->setCellValue('F20', '=MIN(B2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('E21', 'Average of both ranges:') ->setCellValue('F21', '=AVERAGE(B2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('E22', 'Median of both ranges:') ->setCellValue('F22', '=MEDIAN(B2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('E23', 'Mode of both ranges:') ->setCellValue('F23', '=MODE(B2:C12)'); // Calculated data $helper->log('Calculated data'); for ($col = 'B'; $col != 'G'; StringHelper::stringIncrement($col)) { for ($row = 14; $row <= 41; ++$row) { $formula = $spreadsheet->getActiveSheet()->getCell($col . $row)->getValue(); if ( is_string($formula) && ($formula[0] == '=') ) { $helper->log('Value of ' . $col . $row . ' [' . $formula . ']: ' . $spreadsheet->getActiveSheet()->getCell($col . $row)->getCalculatedValueString()); } } } // // If we set Pre Calculated Formulas to true then PhpSpreadsheet will calculate all formulae in the // workbook before saving. This adds time and memory overhead, and can cause some problems with formulae // using functions or features (such as array formulae) that aren't yet supported by the calculation engine // If the value is false (the default) for the Xlsx Writer, then MS Excel (or the application used to // open the file) will need to recalculate values itself to guarantee that the correct results are available. // //$writer->setPreCalculateFormulas(true); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic1/13_CalculationCyclicFormulae.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Add some data, we will use some formulas here $helper->log('Add some data and formulas'); $spreadsheet->getActiveSheet()->setCellValue('A1', '=B1') ->setCellValue('A2', '=B2+1') ->setCellValue('B1', '=A1+1') ->setCellValue('B2', '=A2'); Calculation::getInstance($spreadsheet)->cyclicFormulaCount = 15; // Calculated data $helper->log('Calculated data'); for ($row = 1; $row <= 2; ++$row) { for ($col = 'A'; $col != 'C'; StringHelper::stringIncrement($col)) { $formula = $spreadsheet->getActiveSheet()->getCell($col . $row)->getValue(); if ( is_string($formula) && ($formula[0] == '=') ) { $helper->log('Value of ' . $col . $row . ' [' . $formula . ']: ' . $spreadsheet->getActiveSheet()->getCell($col . $row)->getCalculatedValueString()); } } } // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic1/14_Xls.php ================================================ getFilename(__FILE__, 'xls'); $writer = IOFactory::createWriter($spreadsheet, 'Xls'); $callStartTime = microtime(true); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); ================================================ FILE: samples/Basic1/15_Datavalidation.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Create a first sheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Cell B3 and B5 contain data validation...') ->setCellValue('A3', 'Number:') ->setCellValue('B3', '10') ->setCellValue('A5', 'List:') ->setCellValue('B5', 'Item A') ->setCellValue('A7', 'List #2:') ->setCellValue('B7', 'Item #2') ->setCellValue('D2', 'Item #1') ->setCellValue('D3', 'Item #2') ->setCellValue('D4', 'Item #3') ->setCellValue('D5', 'Item #4') ->setCellValue('D6', 'Item #5'); // Set data validation $helper->log('Set data validation'); $validation = $spreadsheet->getActiveSheet()->getCell('B3')->getDataValidation(); $validation->setType(DataValidation::TYPE_WHOLE); $validation->setErrorStyle(DataValidation::STYLE_STOP); $validation->setAllowBlank(true); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setErrorTitle('Input error'); $validation->setError('Only numbers between 10 and 20 are allowed!'); $validation->setPromptTitle('Allowed input'); $validation->setPrompt('Only numbers between 10 and 20 are allowed.'); $validation->setFormula1('10'); $validation->setFormula2('20'); $validation = $spreadsheet->getActiveSheet()->getCell('B5')->getDataValidation(); $validation->setType(DataValidation::TYPE_LIST); $validation->setErrorStyle(DataValidation::STYLE_INFORMATION); $validation->setAllowBlank(false); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setShowDropDown(true); $validation->setErrorTitle('Input error'); $validation->setError('Value is not in list.'); $validation->setPromptTitle('Pick from list'); $validation->setPrompt('Please pick a value from the drop-down list.'); $validation->setFormula1('"Item A,Item B,Item C"'); // Make sure to put the list items between " and " if your list is simply a comma-separated list of values !!! $validation = $spreadsheet->getActiveSheet()->getCell('B7')->getDataValidation(); $validation->setType(DataValidation::TYPE_LIST); $validation->setErrorStyle(DataValidation::STYLE_INFORMATION); $validation->setAllowBlank(false); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setShowDropDown(true); $validation->setErrorTitle('Input error'); $validation->setError('Value is not in list.'); $validation->setPromptTitle('Pick from list'); $validation->setPrompt('Please pick a value from the drop-down list.'); $validation->setFormula1('$D$2:$D$6'); // Make sure NOT to put a range of cells or a formula between " and " // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic1/16_Csv.php ================================================ log('Write to CSV format'); $writer = new CsvWriter($spreadsheet); $writer->setDelimiter(',') ->setEnclosure('"') ->setSheetIndex(0); $callStartTime = microtime(true); $filename = $helper->getTemporaryFilename('csv'); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); $helper->log('Read from CSV format'); $reader = new CsvReader(); $reader->setDelimiter(',') ->setEnclosure('"') ->setSheetIndex(0); $callStartTime = microtime(true); $spreadsheetFromCSV = $reader->load($filename); $helper->logRead('Csv', $filename, $callStartTime); unlink($filename); // Write Xlsx $helper->write($spreadsheetFromCSV, __FILE__, ['Xlsx']); // Write CSV $filenameCSV = $helper->getFilename(__FILE__, 'csv'); $writerCSV = new CsvWriter($spreadsheetFromCSV); //$writerCSV->setExcelCompatibility(true); $writerCSV->setUseBom(true); // because of non-ASCII chars $callStartTime = microtime(true); $writerCSV->save($filenameCSV); $helper->logWrite($writerCSV, $filenameCSV, $callStartTime); ================================================ FILE: samples/Basic1/17_Html.php ================================================ getProperties()->setTitle('Non-embedded images'); /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->write($spreadsheet, __FILE__, ['Html']); ================================================ FILE: samples/Basic1/17a_Html.php ================================================ getProperties()->setTitle('Embedded images'); /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->write( $spreadsheet, __FILE__, ['Html'], false, function (Html $writer): void { $writer->setEmbedImages(true); } ); ================================================ FILE: samples/Basic1/17b_Html.php ================================================ write( $spreadsheet, __FILE__, ['Html'], false, function (Html $writer): void { $writer->setEmbedImages(true); $writer->setEditHtmlCallback('changeGridlines'); } ); ================================================ FILE: samples/Basic1/18_Extendedcalculation.php ================================================ log('List implemented functions'); $calc = Calculation::getInstance(); print_r($calc->getImplementedFunctionNames()); // Create new Spreadsheet object $helper->log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Add some data, we will use some formulas here $helper->log('Add some data'); $spreadsheet->getActiveSheet()->setCellValue('A14', 'Count:'); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Range 1'); $spreadsheet->getActiveSheet()->setCellValue('B2', 2); $spreadsheet->getActiveSheet()->setCellValue('B3', 8); $spreadsheet->getActiveSheet()->setCellValue('B4', 10); $spreadsheet->getActiveSheet()->setCellValue('B5', true); $spreadsheet->getActiveSheet()->setCellValue('B6', false); $spreadsheet->getActiveSheet()->setCellValue('B7', 'Text String'); $spreadsheet->getActiveSheet()->setCellValue('B9', '22'); $spreadsheet->getActiveSheet()->setCellValue('B10', 4); $spreadsheet->getActiveSheet()->setCellValue('B11', 6); $spreadsheet->getActiveSheet()->setCellValue('B12', 12); $spreadsheet->getActiveSheet()->setCellValue('B14', '=COUNT(B2:B12)'); $spreadsheet->getActiveSheet()->setCellValue('C1', 'Range 2'); $spreadsheet->getActiveSheet()->setCellValue('C2', 1); $spreadsheet->getActiveSheet()->setCellValue('C3', 2); $spreadsheet->getActiveSheet()->setCellValue('C4', 2); $spreadsheet->getActiveSheet()->setCellValue('C5', 3); $spreadsheet->getActiveSheet()->setCellValue('C6', 3); $spreadsheet->getActiveSheet()->setCellValue('C7', 3); $spreadsheet->getActiveSheet()->setCellValue('C8', '0'); $spreadsheet->getActiveSheet()->setCellValue('C9', 4); $spreadsheet->getActiveSheet()->setCellValue('C10', 4); $spreadsheet->getActiveSheet()->setCellValue('C11', 4); $spreadsheet->getActiveSheet()->setCellValue('C12', 4); $spreadsheet->getActiveSheet()->setCellValue('C14', '=COUNT(C2:C12)'); $spreadsheet->getActiveSheet()->setCellValue('D1', 'Range 3'); $spreadsheet->getActiveSheet()->setCellValue('D2', 2); $spreadsheet->getActiveSheet()->setCellValue('D3', 3); $spreadsheet->getActiveSheet()->setCellValue('D4', 4); $spreadsheet->getActiveSheet()->setCellValue('D5', '=((D2 * D3) + D4) & " should be 10"'); $spreadsheet->getActiveSheet()->setCellValue('E1', 'Other functions'); $spreadsheet->getActiveSheet()->setCellValue('E2', '=PI()'); $spreadsheet->getActiveSheet()->setCellValue('E3', '=RAND()'); $spreadsheet->getActiveSheet()->setCellValue('E4', '=RANDBETWEEN(5, 10)'); $spreadsheet->getActiveSheet()->setCellValue('E14', 'Count of both ranges:'); $spreadsheet->getActiveSheet()->setCellValue('F14', '=COUNT(B2:C12)'); // Calculated data $helper->log('Calculated data'); $helper->log('Value of B14 [=COUNT(B2:B12)]: ' . $spreadsheet->getActiveSheet()->getCell('B14')->getCalculatedValueString()); $helper->logEndingNotes(); ================================================ FILE: samples/Basic1/19_Namedrange.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:') ->setCellValue('A2', 'Lastname:') ->setCellValue('A3', 'Fullname:') ->setCellValue('B1', 'Maarten') ->setCellValue('B2', 'Balliauw') ->setCellValue('B3', '=B1 & " " & B2'); // Define named ranges $helper->log('Define named ranges'); $spreadsheet->addNamedRange(new NamedRange('PersonName', $spreadsheet->getActiveSheet(), '$B$1')); $spreadsheet->addNamedRange(new NamedRange('PersonLN', $spreadsheet->getActiveSheet(), '$B$2')); // Rename named ranges $helper->log('Rename named ranges'); if ($spreadsheet->getNamedRange('PersonName') === null) { throw new Exception('named range not found'); } $spreadsheet->getNamedRange('PersonName')->setName('PersonFN'); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Person'); // Create a new worksheet, after the default sheet $helper->log('Create new Worksheet object'); $spreadsheet->createSheet(); // Add some data to the second sheet, resembling some different data types $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(1); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:') ->setCellValue('A2', 'Lastname:') ->setCellValue('A3', 'Fullname:') ->setCellValue('B1', '=PersonFN') ->setCellValue('B2', '=PersonLN') ->setCellValue('B3', '=PersonFN & " " & PersonLN'); // Resolve range $helper->log('Resolve range'); $helper->log('Cell B1 {=PersonFN}: ' . $spreadsheet->getActiveSheet()->getCell('B1')->getCalculatedValueString()); $helper->log('Cell B3 {=PersonFN & " " & PersonLN}: ' . $spreadsheet->getActiveSheet()->getCell('B3')->getCalculatedValueString()); $helper->log('Cell Person!B1: ' . $spreadsheet->getActiveSheet()->getCell('Person!B1')->getCalculatedValueString()); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Person (cloned)'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/20_Read_Excel2003XML.php ================================================ logRead('Xml', $filename, $callStartTime); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/20_Read_Gnumeric.php ================================================ logRead('Gnumeric', $filename, $callStartTime); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/20_Read_Ods.php ================================================ logRead('Ods', $filename, $callStartTime); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Xls', 'Ods']); ================================================ FILE: samples/Basic2/20_Read_Sylk.php ================================================ logRead('Slk', $filename, $callStartTime); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/20_Read_Xls.php ================================================ getTemporaryFilename('xls'); $writer = IOFactory::createWriter($spreadsheet, 'Xls'); $callStartTime = microtime(true); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); // Read Xls file $callStartTime = microtime(true); $spreadsheet = IOFactory::load($filename); $helper->logRead('Xls', $filename, $callStartTime); unlink($filename); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/22_Heavily_formatted.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->getStyle('A1:T100')->applyFromArray( ['fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FFCCFFCC'], ], 'borders' => [ 'bottom' => ['borderStyle' => Border::BORDER_THIN], 'right' => ['borderStyle' => Border::BORDER_MEDIUM], ], ] ); $spreadsheet->getActiveSheet()->getStyle('C5:R95')->applyFromArray( ['fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FFFFFF00'], ], ] ); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/23_Sharedstyles.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $sharedStyle1 = new Style(); $sharedStyle2 = new Style(); $sharedStyle1->applyFromArray( ['fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FFCCFFCC'], ], 'borders' => [ 'bottom' => ['borderStyle' => Border::BORDER_THIN], 'right' => ['borderStyle' => Border::BORDER_MEDIUM], ], ] ); $sharedStyle2->applyFromArray( ['fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FFFFFF00'], ], 'borders' => [ 'bottom' => ['borderStyle' => Border::BORDER_THIN], 'right' => ['borderStyle' => Border::BORDER_MEDIUM], ], ] ); $spreadsheet->getActiveSheet()->duplicateStyle($sharedStyle1, 'A1:T100'); $spreadsheet->getActiveSheet()->duplicateStyle($sharedStyle2, 'C5:R95'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/24_Readfilter.php ================================================ getTemporaryFilename(); $callStartTime = microtime(true); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); class MyReadFilter implements IReadFilter { public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; } return false; } } $helper->log('Load from Xlsx file'); $reader = new XlsxReader(); $reader->setReadFilter(new MyReadFilter()); $callStartTime = microtime(true); $spreadsheet = $reader->load($filename); unlink($filename); $helper->logRead('Xlsx', $filename, $callStartTime); $helper->log('Remove unnecessary rows'); $spreadsheet->getActiveSheet()->removeRow(2, 18); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/25_In_memory_image.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $sheet1 = $spreadsheet->getActiveSheet(); $sheet1->setTitle('SheetWithData'); $sheet1->getCell('G1')->setValue('X'); $sheet1->getCell('E5')->setValue('Y'); $sheet1->getCell('A8')->setValue('Z'); // Set document properties $helper->log('Set document properties'); $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'); // Generate an image $helper->log('Generate an image'); $gdImage = imagecreatetruecolor(120, 20); if (!$gdImage) { throw new Exception('Cannot Initialize new GD image stream'); } $textColor = imagecolorallocate($gdImage, 255, 255, 255); if ($textColor === false) { throw new Exception('imagecolorallocate failed'); } imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new MemoryDrawing(); $drawing->setName('Sample image'); $drawing->setDescription('Sample image'); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_DEFAULT); $drawing->setHeight(36); $drawing->setWorksheet($sheet1); $drawing->setCoordinates('C5'); $helper->log('Create new sheet'); $sheet2 = $spreadsheet->createSheet(); $sheet2->setTitle('SheetWithoutData'); // Add a drawing to the new worksheet $helper->log('Add a drawing to the new worksheet'); $drawing = new MemoryDrawing(); $drawing->setName('Sample image'); $drawing->setDescription('Sample image'); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_DEFAULT); $drawing->setHeight(36); $drawing->setWorksheet($sheet2); $drawing->setCoordinates('C5'); // Save $helper->write( $spreadsheet, __FILE__, ['Xlsx', 'Html'], false, function (BaseWriter $writer): void { if (method_exists($writer, 'writeAllSheets')) { $writer->writeAllSheets(); } } ); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic2/26_Utf8.php ================================================ log('Load Xlsx template file'); $reader = IOFactory::createReader('Xlsx'); $spreadsheet = $reader->load(__DIR__ . '/../templates/26template.xlsx'); $spreadsheet->getActiveSheet()->setPrintGridlines(true); // at this point, we could do some manipulations with the template, but we skip this step $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Xls', 'Html']); // Export to PDF (mpdf) $mpdfCjkWriter = function (Mpdf $writer): void { $mpdfCjk = function (string $html): string { $html = str_replace("'Calibri'", "'Calibri',Sun-ExtA", $html); return str_replace("'Times New Roman'", "'Times New Roman',Sun-ExtA", $html); }; $writer->setEditHtmlCallback($mpdfCjk); }; $helper->log('Write to Mpdf'); IOFactory::registerWriter('Pdf', Mpdf::class); $filename = __FILE__; $helper->write($spreadsheet, $filename, ['Pdf'], false, $mpdfCjkWriter); // Remove first two rows with field headers before exporting to CSV $helper->log('Removing first two heading rows for CSV export'); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->removeRow(1, 2); // Export to CSV (.csv) $helper->log('Write to CSV format'); /** @var Csv $writer */ $helper->write($spreadsheet, __FILE__, ['Csv']); // Export to CSV with BOM (.csv) $filename = str_replace('.php', '-bom.php', __FILE__); $helper->log('Write to CSV format (with BOM)'); $helper->write( $spreadsheet, $filename, ['Csv'], false, function (Csv $writer): void { $writer->setUseBOM(true); } ); ================================================ FILE: samples/Basic2/27_Images_Html_Pdf.php ================================================ log('Load Xlsx template file'); $reader = IOFactory::createReader('Xls'); $initialSpreadsheet = $reader->load(__DIR__ . '/../templates/27template.xls'); $xlsxFile = File::temporaryFilename(); $writer = new XlsxWriter($initialSpreadsheet); $helper->log('Save as Xlsx'); $writer->save($xlsxFile); $initialSpreadsheet->disconnectWorksheets(); $reader2 = new XlsxReader(); $helper->log('Load Xlsx'); $spreadsheet = $reader2->load($xlsxFile); $helper->log('Hide grid lines'); $spreadsheet->getActiveSheet()->setShowGridLines(false); $helper->log('Set orientation to landscape'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $className = Mpdf::class; $helper->log("Write to PDF format using {$className}, and to Html"); IOFactory::registerWriter('Pdf', $className); // Save $helper->write($spreadsheet, __FILE__, ['Pdf', 'Html']); unlink($xlsxFile); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic2/27_Images_Xls.php ================================================ log('Load Xls template file'); $reader = IOFactory::createReader('Xls'); $spreadsheet = $reader->load(__DIR__ . '/../templates/27template.xls'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/27_Images_Xlsx.php ================================================ log('Load Xlsx template file'); $reader = IOFactory::createReader('Xlsx'); // Note that Xlsx converts bmp to png, so it needs to be added // programmatically rather than in template. // Also note Xls converts both bmp and gif to png. $spreadsheet = $reader->load(__DIR__ . '/../templates/27template.xlsx'); $sheet = $spreadsheet->getActiveSheet(); $drawing = new Drawing(); $drawing->setName('Test BMP'); $drawing->setPath(__DIR__ . '/../images/bmp.bmp'); $drawing->setCoordinates('G17'); $drawing->setWorksheet($sheet); $sheet->getCell('G16')->setValue('BMP'); $sheet->getStyle('G16')->getFont()->setName('Arial Black')->setBold(true); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic2/28_Iterator.php ================================================ getTemporaryFilename(); $writer = new XlsxWriter($sampleSpreadsheet); $callStartTime = microtime(true); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); $callStartTime = microtime(true); $reader = new XlsxReader(); $spreadsheet = $reader->load($filename); $helper->logRead('Xlsx', $filename, $callStartTime); unlink($filename); $helper->log('Iterate worksheets'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $helper->log('Worksheet - ' . $worksheet->getTitle()); foreach ($worksheet->getRowIterator() as $row) { $helper->log(' Row number - ' . $row->getRowIndex()); $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set foreach ($cellIterator as $cell) { $helper->log(' Cell - ' . $cell->getCoordinate() . ' - ' . $cell->getCalculatedValueString()); } } } ================================================ FILE: samples/Basic2/29_Advanced_value_binder.php ================================================ log('Set timezone'); date_default_timezone_set('UTC'); // Set value binder $helper->log('Set value binder'); Cell::setValueBinder(new AdvancedValueBinder()); // Create new Spreadsheet object $helper->log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Set default font $helper->log('Set default font'); $spreadsheet->getDefaultStyle()->getFont()->setName('Arial'); $spreadsheet->getDefaultStyle()->getFont()->setSize(10); // Set column widths $helper->log('Set column widths'); $spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(14); // Add some data, resembling some different data types $helper->log('Add some data'); $spreadsheet->getActiveSheet()->setCellValue('A1', 'String value:') ->setCellValue('B1', 'Mark Baker'); $spreadsheet->getActiveSheet()->setCellValue('A2', 'Numeric value #1:') ->setCellValue('B2', 12345); $spreadsheet->getActiveSheet()->setCellValue('A3', 'Numeric value #2:') ->setCellValue('B3', -12.345); $spreadsheet->getActiveSheet()->setCellValue('A4', 'Numeric value #3:') ->setCellValue('B4', .12345); $spreadsheet->getActiveSheet()->setCellValue('A5', 'Numeric value #4:') ->setCellValue('B5', '12345'); $spreadsheet->getActiveSheet()->setCellValue('A6', 'Numeric value #5:') ->setCellValue('B6', '1.2345'); $spreadsheet->getActiveSheet()->setCellValue('A7', 'Numeric value #6:') ->setCellValue('B7', '.12345'); $spreadsheet->getActiveSheet()->setCellValue('A8', 'Numeric value #7:') ->setCellValue('B8', '1.234e-5'); $spreadsheet->getActiveSheet()->setCellValue('A9', 'Numeric value #8:') ->setCellValue('B9', '-1.234e+5'); $spreadsheet->getActiveSheet()->setCellValue('A10', 'Boolean value:') ->setCellValue('B10', 'TRUE'); $spreadsheet->getActiveSheet()->setCellValue('A11', 'Percentage value #1:') ->setCellValue('B11', '10%'); $spreadsheet->getActiveSheet()->setCellValue('A12', 'Percentage value #2:') ->setCellValue('B12', '12.5%'); $spreadsheet->getActiveSheet()->setCellValue('A13', 'Fraction value #1:') ->setCellValue('B13', '-1/2'); $spreadsheet->getActiveSheet()->setCellValue('A14', 'Fraction value #2:') ->setCellValue('B14', '3 1/2'); $spreadsheet->getActiveSheet()->setCellValue('A15', 'Fraction value #3:') ->setCellValue('B15', '-12 3/4'); $spreadsheet->getActiveSheet()->setCellValue('A16', 'Fraction value #4:') ->setCellValue('B16', '13/4'); $spreadsheet->getActiveSheet()->setCellValue('A17', 'Currency value #1:') ->setCellValue('B17', '$12345'); $spreadsheet->getActiveSheet()->setCellValue('A18', 'Currency value #2:') ->setCellValue('B18', '$12345.67'); $spreadsheet->getActiveSheet()->setCellValue('A19', 'Currency value #3:') ->setCellValue('B19', '$12,345.67'); $spreadsheet->getActiveSheet()->setCellValue('A20', 'Date value #1:') ->setCellValue('B20', '21 December 1983'); $spreadsheet->getActiveSheet()->setCellValue('A21', 'Date value #2:') ->setCellValue('B21', '19-Dec-1960'); $spreadsheet->getActiveSheet()->setCellValue('A22', 'Date value #3:') ->setCellValue('B22', '07/12/1982'); $spreadsheet->getActiveSheet()->setCellValue('A23', 'Date value #4:') ->setCellValue('B23', '24-11-1950'); $spreadsheet->getActiveSheet()->setCellValue('A24', 'Date value #5:') ->setCellValue('B24', '17-Mar'); $spreadsheet->getActiveSheet()->setCellValue('A25', 'Time value #1:') ->setCellValue('B25', '01:30'); $spreadsheet->getActiveSheet()->setCellValue('A26', 'Time value #2:') ->setCellValue('B26', '01:30:15'); $spreadsheet->getActiveSheet()->setCellValue('A27', 'Date/Time value:') ->setCellValue('B27', '19-Dec-1960 01:30'); $spreadsheet->getActiveSheet()->setCellValue('A28', 'Formula:') ->setCellValue('B28', '=SUM(B2:B9)'); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Advanced value binder'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic3/30_Template.php ================================================ log('Load from Xls template'); $reader = IOFactory::createReader('Xls'); $spreadsheet = $reader->load(__DIR__ . '/../templates/30template.xls'); $helper->log('Add new data to the template'); $data = [['title' => 'Excel for dummies', 'price' => 17.99, 'quantity' => 2, ], ['title' => 'PHP for dummies', 'price' => 15.99, 'quantity' => 1, ], ['title' => 'Inside OOP', 'price' => 12.95, 'quantity' => 1, ], ]; $spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel(time())); $baseRow = 5; foreach ($data as $r => $dataRow) { $row = $baseRow + $r; $spreadsheet->getActiveSheet()->insertNewRowBefore($row, 1); $spreadsheet->getActiveSheet()->setCellValue('A' . $row, $r + 1) ->setCellValue('B' . $row, $dataRow['title']) ->setCellValue('C' . $row, $dataRow['price']) ->setCellValue('D' . $row, $dataRow['quantity']) ->setCellValue('E' . $row, '=C' . $row . '*D' . $row); } $spreadsheet->getActiveSheet()->removeRow($baseRow - 1, 1); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic3/30_Templatebiff5.php ================================================ log('Load from Xls template'); $reader = IOFactory::createReader('Xls'); $spreadsheet = $reader->load(__DIR__ . '/../templates/30templatebiff5.xls'); $helper->log('Add new data to the template'); $data = [['title' => 'Excel for dummies', 'price' => 17.99, 'quantity' => 2, ], ['title' => 'PHP for dummies', 'price' => 15.99, 'quantity' => 1, ], ['title' => 'Inside OOP', 'price' => 12.95, 'quantity' => 1, ], ]; $spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel(time())); $baseRow = 5; foreach ($data as $r => $dataRow) { $row = $baseRow + $r; $spreadsheet->getActiveSheet()->insertNewRowBefore($row, 1); $spreadsheet->getActiveSheet()->setCellValue('A' . $row, $r + 1) ->setCellValue('B' . $row, $dataRow['title']) ->setCellValue('C' . $row, $dataRow['price']) ->setCellValue('D' . $row, $dataRow['quantity']) ->setCellValue('E' . $row, '=C' . $row . '*D' . $row); } $spreadsheet->getActiveSheet()->removeRow($baseRow - 1, 1); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic3/31_Document_properties_write.php ================================================ load($inputFileName); $helper->logRead($inputFileType, $inputFileName, $callStartTime); $helper->log('Adjust properties'); $spreadsheet->getProperties()->setTitle('Office 2007 XLSX Test Document') ->setSubject('Office 2007 XLSX Test Document') ->setDescription('Test XLSX document, generated using PhpSpreadsheet') ->setKeywords('office 2007 openxml php'); // Save Excel 2007 file $filename = $helper->getFilename(__FILE__); $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $callStartTime = microtime(true); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); $helper->logEndingNotes(); // Reread File $helper->log('Reread Xlsx file'); $spreadsheetRead = IOFactory::load($filename); // Set properties $helper->log('Get properties'); $helper->log('Core Properties:'); $helper->log(' Created by - ' . $spreadsheet->getProperties()->getCreator()); $helper->log(' Created on - ' . date('d-M-Y' . $spreadsheet->getProperties()->getCreated()) . ' at ' . date('H:i:s' . $spreadsheet->getProperties()->getCreated())); $helper->log(' Last Modified by - ' . $spreadsheet->getProperties()->getLastModifiedBy()); $helper->log(' Last Modified on - ' . date('d-M-Y' . $spreadsheet->getProperties()->getModified()) . ' at ' . date('H:i:s' . $spreadsheet->getProperties()->getModified())); $helper->log(' Title - ' . $spreadsheet->getProperties()->getTitle()); $helper->log(' Subject - ' . $spreadsheet->getProperties()->getSubject()); $helper->log(' Description - ' . $spreadsheet->getProperties()->getDescription()); $helper->log(' Keywords: - ' . $spreadsheet->getProperties()->getKeywords()); $helper->log('Extended (Application) Properties:'); $helper->log(' Category - ' . $spreadsheet->getProperties()->getCategory()); $helper->log(' Company - ' . $spreadsheet->getProperties()->getCompany()); $helper->log(' Manager - ' . $spreadsheet->getProperties()->getManager()); $helper->log('Custom Properties:'); $customProperties = $spreadsheet->getProperties()->getCustomProperties(); foreach ($customProperties as $customProperty) { $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); if ($propertyType == Properties::PROPERTY_TYPE_DATE) { $formattedValue = is_numeric($propertyValue) ? date('d-M-Y H:i:s', (int) $propertyValue) : '*****INVALID*****'; } elseif ($propertyType == Properties::PROPERTY_TYPE_BOOLEAN) { $formattedValue = $propertyValue ? 'TRUE' : 'FALSE'; } else { $formattedValue = $propertyValue; } $helper->log(' ' . $customProperty . ' - (' . $propertyType . ') - ' . $formattedValue); } $helper->logEndingNotes(); ================================================ FILE: samples/Basic3/31_Document_properties_write_xls.php ================================================ load($inputFileName); $helper->logRead($inputFileType, $inputFileName, $callStartTime); $helper->log('Adjust properties'); $spreadsheet->getProperties()->setTitle('Office 95 XLS Test Document') ->setSubject('Office 95 XLS Test Document') ->setDescription('Test XLS document, generated using PhpSpreadsheet') ->setKeywords('office 95 biff php'); // Save Excel 95 file $filename = $helper->getFilename(__FILE__, 'xls'); $writer = IOFactory::createWriter($spreadsheet, 'Xls'); $callStartTime = microtime(true); $writer->save($filename); $helper->logWrite($writer, $filename, $callStartTime); $helper->logEndingNotes(); // Reread File $helper->log('Reread Xls file'); $spreadsheetRead = IOFactory::load($filename); // Set properties $helper->log('Get properties'); $helper->log('Core Properties:'); $helper->log(' Created by - ' . $spreadsheet->getProperties()->getCreator()); $helper->log(' Created on - ' . date('d-M-Y' . $spreadsheet->getProperties()->getCreated()) . ' at ' . date('H:i:s' . $spreadsheet->getProperties()->getCreated())); $helper->log(' Last Modified by - ' . $spreadsheet->getProperties()->getLastModifiedBy()); $helper->log(' Last Modified on - ' . date('d-M-Y' . $spreadsheet->getProperties()->getModified()) . ' at ' . date('H:i:s' . $spreadsheet->getProperties()->getModified())); $helper->log(' Title - ' . $spreadsheet->getProperties()->getTitle()); $helper->log(' Subject - ' . $spreadsheet->getProperties()->getSubject()); $helper->log(' Description - ' . $spreadsheet->getProperties()->getDescription()); $helper->log(' Keywords: - ' . $spreadsheet->getProperties()->getKeywords()); $helper->log('Extended (Application) Properties:'); $helper->log(' Category - ' . $spreadsheet->getProperties()->getCategory()); $helper->log(' Company - ' . $spreadsheet->getProperties()->getCompany()); $helper->log(' Manager - ' . $spreadsheet->getProperties()->getManager()); $helper->log('Custom Properties:'); $customProperties = $spreadsheet->getProperties()->getCustomProperties(); foreach ($customProperties as $customProperty) { $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); if ($propertyType == Properties::PROPERTY_TYPE_DATE) { $formattedValue = is_numeric($propertyValue) ? date('d-M-Y H:i:s', (int) $propertyValue) : '*****INVALID*****'; } elseif ($propertyType == Properties::PROPERTY_TYPE_BOOLEAN) { $formattedValue = $propertyValue ? 'TRUE' : 'FALSE'; } else { $formattedValue = $propertyValue; } $helper->log(' ' . $customProperty . ' - (' . $propertyType . ') - ' . $formattedValue); } $helper->logEndingNotes(); ================================================ FILE: samples/Basic3/37_Page_layout_view.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('PHPOffice') ->setLastModifiedBy('PHPOffice') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('Office PhpSpreadsheet php') ->setCategory('Test result file'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!'); // Set the page layout view as page layout $spreadsheet->getActiveSheet()->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_LAYOUT); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic3/38_Clone_worksheet.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Add some data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B2', 'world!') ->setCellValue('C1', 'Hello') ->setCellValue('D2', 'world!'); // Miscellaneous glyphs, UTF-8 $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', 'Miscellaneous glyphs') ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç'); $spreadsheet->getActiveSheet()->setCellValue('A8', "Hello\nWorld"); $spreadsheet->getActiveSheet()->getRowDimension(8)->setRowHeight(-1); $spreadsheet->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet()->setTitle('Simple'); // Clone worksheet $helper->log('Clone worksheet'); $clonedSheet = clone $spreadsheet->getActiveSheet(); $clonedSheet ->setCellValue('A1', 'Goodbye') ->setCellValue('A2', 'cruel') ->setCellValue('C1', 'Goodbye') ->setCellValue('C2', 'cruel'); // Rename cloned worksheet $helper->log('Rename cloned worksheet'); $clonedSheet->setTitle('Simple Clone'); $spreadsheet->addSheet($clonedSheet); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic3/39_Dropdown.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties() ->setCreator('PHPOffice') ->setLastModifiedBy('PHPOffice') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('Office PhpSpreadsheet php') ->setCategory('Test result file'); /** @return array */ function transpose(string $value): array { return [$value]; } // Add some data $continentColumn = 'D'; $column = 'F'; // Set data for dropdowns $continents = glob(__DIR__ . '/data/continents/*') ?: []; foreach ($continents as $key => $filename) { $continent = pathinfo($filename, PATHINFO_FILENAME); $helper->log("Loading $continent"); $continent = str_replace(' ', '_', $continent); $countries = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; $countryCount = count($countries); // Transpose $countries from a row to a column array $countries = array_map(fn (mixed $value): array => [$value], $countries); $spreadsheet->getActiveSheet() ->fromArray($countries, null, $column . '1'); $spreadsheet->addNamedRange( new NamedRange( $continent, $spreadsheet->getActiveSheet(), '$' . $column . '$1:$' . $column . '$' . $countryCount ) ); $spreadsheet->getActiveSheet() ->getColumnDimension($column) ->setVisible(false); $spreadsheet->getActiveSheet() ->setCellValue($continentColumn . ($key + 1), $continent); StringHelper::stringIncrement($column); } // Hide the dropdown data $spreadsheet->getActiveSheet() ->getColumnDimension($continentColumn) ->setVisible(false); $spreadsheet->addNamedRange( new NamedRange( 'Continents', $spreadsheet->getActiveSheet(), '$' . $continentColumn . '$1:$' . $continentColumn . '$' . count($continents) ) ); // Set selection cells $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Continent:'); $spreadsheet->getActiveSheet() ->setCellValue('B1', 'Select continent'); $spreadsheet->getActiveSheet() ->setCellValue('B3', '=' . $column . 1); $spreadsheet->getActiveSheet() ->setCellValue('B3', 'Select country'); $spreadsheet->getActiveSheet() ->getStyle('A1:A3') ->getFont()->setBold(true); // Set linked validators $validation = $spreadsheet->getActiveSheet() ->getCell('B1') ->getDataValidation(); $validation->setType(DataValidation::TYPE_LIST) ->setErrorStyle(DataValidation::STYLE_INFORMATION) ->setAllowBlank(false) ->setShowInputMessage(true) ->setShowErrorMessage(true) ->setShowDropDown(true) ->setErrorTitle('Input error') ->setError('Continent is not in the list.') ->setPromptTitle('Pick from the list') ->setPrompt('Please pick a continent from the drop-down list.') ->setFormula1('=Continents'); $spreadsheet->getActiveSheet() ->setCellValue('A3', 'Country:'); $spreadsheet->getActiveSheet() ->getStyle('A3') ->getFont()->setBold(true); $validation = $spreadsheet->getActiveSheet() ->getCell('B3') ->getDataValidation(); $validation->setType(DataValidation::TYPE_LIST) ->setErrorStyle(DataValidation::STYLE_INFORMATION) ->setAllowBlank(false) ->setShowInputMessage(true) ->setShowErrorMessage(true) ->setShowDropDown(true) ->setErrorTitle('Input error') ->setError('Country is not in the list.') ->setPromptTitle('Pick from the list') ->setPrompt('Please pick a country from the drop-down list.') ->setFormula1('=INDIRECT($B$1)'); $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(12); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(30); // Save $helper->log('Not writing to Xls - formulae with defined names not yet supported'); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Basic3/data/continents/Africa.txt ================================================ Algeria Angola Benin Botswana Burkina Burundi Cameroon Cape Verde Central African Republic Chad Comoros Congo Congo, Democratic Republic of Djibouti Egypt Equatorial Guinea Eritrea Ethiopia Gabon Gambia Ghana Guinea Guinea-Bissau Ivory Coast Kenya Lesotho Liberia Libya Madagascar Malawi Mali Mauritania Mauritius Morocco Mozambique Namibia Niger Nigeria Rwanda Sao Tome and Principe Senegal Seychelles Sierra Leone Somalia South Africa South Sudan Sudan Swaziland Tanzania Togo Tunisia Uganda Zambia Zimbabwe ================================================ FILE: samples/Basic3/data/continents/Asia.txt ================================================ Afghanistan Bahrain Bangladesh Bhutan Brunei Burma (Myanmar) Cambodia China East Timor India Indonesia Iran Iraq Israel Japan Jordan Kazakhstan Korea, North Korea, South Kuwait Kyrgyzstan Laos Lebanon Malaysia Maldives Mongolia Nepal Oman Pakistan Philippines Qatar Russian Federation Saudi Arabia Singapore Sri Lanka Syria Tajikistan Thailand Turkey Turkmenistan United Arab Emirates Uzbekistan Vietnam Yemen ================================================ FILE: samples/Basic3/data/continents/Europe.txt ================================================ Albania Andorra Armenia Austria Azerbaijan Belarus Belgium Bosnia and Herzegovina Bulgaria Croatia Cyprus Czech Republic Denmark Estonia Finland France Georgia Germany Greece Hungary Iceland Ireland Italy Latvia Liechtenstein Lithuania Luxembourg Macedonia Malta Moldova Monaco Montenegro Netherlands Norway Poland Portugal Romania San Marino Serbia Slovakia Slovenia Spain Sweden Switzerland Ukraine United Kingdom Vatican City ================================================ FILE: samples/Basic3/data/continents/North America.txt ================================================ Antigua and Barbuda Bahamas Barbados Belize Canada Costa Rica Cuba Dominica Dominican Republic El Salvador Grenada Guatemala Haiti Honduras Jamaica Mexico Nicaragua Panama Saint Kitts and Nevis Saint Lucia Saint Vincent and the Grenadines Trinidad and Tobago United States ================================================ FILE: samples/Basic3/data/continents/Oceania.txt ================================================ Australia Fiji Kiribati Marshall Islands Micronesia Nauru New Zealand Palau Papua New Guinea Samoa Solomon Islands Tonga Tuvalu Vanuatu ================================================ FILE: samples/Basic3/data/continents/South America.txt ================================================ Argentina Bolivia Brazil Chile Colombia Ecuador Guyana Paraguay Peru Suriname Uruguay Venezuela ================================================ FILE: samples/Basic4/40_Duplicate_style.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $helper->log('Create styles array'); $styles = []; for ($i = 0; $i < 10; ++$i) { $style = new Style(); $style->getFont()->setSize($i + 4); $styles[] = $style; } $helper->log('Add data (begin)'); $t = microtime(true); for ($col = 1; $col <= 50; ++$col) { for ($row = 0; $row < 100; ++$row) { $str = ($row + $col); $style = $styles[$row % 10]; $coord = Coordinate::stringFromColumnIndex($col) . ($row + 1); $worksheet->setCellValue($coord, $str); $worksheet->duplicateStyle($style, $coord); } } $d = microtime(true) - $t; $helper->log('Add data (end) . time: ' . (string) round($d, 2) . ' s'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic4/41_Password.php ================================================ getSecurity()->setLockWindows(true); $spreadsheet->getSecurity()->setLockStructure(true); $spreadsheet->getSecurity()->setWorkbookPassword('secret'); // Save /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic4/42_RichText.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Maarten Balliauw') ->setLastModifiedBy('Maarten Balliauw') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Add some data $helper->log('Add some data'); $html1 = '

My very first example of rich text
generated from html markup

This block contains an italicized word; while this block uses an underline.

I want to eat healthy food pizza. '; $html2 = '

100°C is a hot temperature
10°F is cold

'; $html3 = '23 equals 8'; $html4 = 'H2SO4 is the chemical formula for Sulphuric acid'; $html5 = 'bold, italic, bold+italic'; $wizard = new HtmlHelper(); $richText = $wizard->toRichTextObject($html1); $spreadsheet->getActiveSheet() ->setCellValue('A1', $richText); $spreadsheet->getActiveSheet() ->getColumnDimension('A') ->setWidth(48); $spreadsheet->getActiveSheet() ->getRowDimension(1) ->setRowHeight(-1); $spreadsheet->getActiveSheet()->getStyle('A1') ->getAlignment() ->setWrapText(true); $richText = $wizard->toRichTextObject($html2); $spreadsheet->getActiveSheet() ->setCellValue('A2', $richText); $spreadsheet->getActiveSheet() ->getRowDimension(1) ->setRowHeight(-1); $spreadsheet->getActiveSheet() ->getStyle('A2') ->getAlignment() ->setWrapText(true); $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A3', $wizard->toRichTextObject($html3)); $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A4', $wizard->toRichTextObject($html4)); $spreadsheet->setActiveSheetIndex(0) ->setCellValue('A5', $wizard->toRichTextObject($html5)); // Rename worksheet $helper->log('Rename worksheet'); $spreadsheet->getActiveSheet() ->setTitle('Rich Text Examples'); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/Basic4/42b_RichText.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $rtf = new RichText(); $rtf->createText('~Cell Style~'); $rtf->createTextRun('~RTF Style~')->getFont()?->setItalic(true); $rtf->createText('~No Style~'); $sheet->getCell('A1')->setValue($rtf); $sheet->getStyle('A1')->getFont()->setBold(true); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Xls', 'Html']); ================================================ FILE: samples/Basic4/43_Merge_workbooks.php ================================================ log('Load MergeBook1 from Xlsx file'); $filename1 = __DIR__ . '/../templates/43mergeBook1.xlsx'; $callStartTime = microtime(true); $spreadsheet1 = IOFactory::load($filename1); $helper->logRead('Xlsx', $filename1, $callStartTime); $helper->log('Load MergeBook2 from Xlsx file'); $filename2 = __DIR__ . '/../templates/43mergeBook2.xlsx'; $callStartTime = microtime(true); $spreadsheet2 = IOFactory::load($filename2); $helper->logRead('Xlsx', $filename2, $callStartTime); foreach ($spreadsheet2->getSheetNames() as $sheetName) { $sheet = $spreadsheet2->getSheetByName($sheetName); if ($sheet === null) { continue; } $sheet->setTitle($sheet->getTitle() . ' copied'); $spreadsheet1->addExternalSheet($sheet); } // Save $helper->write($spreadsheet1, __FILE__); ================================================ FILE: samples/Basic4/44_Worksheet_info.php ================================================ getTemporaryFilename(); $writer = new Writer($sampleSpreadsheet); $writer->save($filename); $inputFileType = IOFactory::identify($filename); $reader = new Reader(); $sheetList = $reader->listWorksheetNames($filename); $sheetInfo = $reader->listWorksheetInfo($filename); $helper->log('File Type:'); var_dump($inputFileType); $helper->log('Worksheet Names:'); var_dump($sheetList); $helper->log('Worksheet Names:'); var_dump($sheetInfo); unlink($filename); ================================================ FILE: samples/Basic4/45_Quadratic_equation_solver.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } $postA = htmlentities(StringHelper::convertToString($_POST['A'] ?? '')); $postB = htmlentities(StringHelper::convertToString($_POST['B'] ?? '')); $postC = htmlentities(StringHelper::convertToString($_POST['C'] ?? '')); ?>
Enter the coefficients for Ax2 + Bx + C = 0

If A=0, the equation is not quadratic.
log('Non-numeric input'); } elseif ($postA == 0) { $helper->log('The equation is not quadratic'); } else { // Calculate and Display the results $helper->log('
Roots:
'); $discriminantFormula = '=POWER(' . $postB . ',2) - (4 * ' . $postA . ' * ' . $postC . ')'; $discriminant = Calculation::getInstance()->calculateFormula($discriminantFormula); $discriminant = StringHelper::convertToString($discriminant); $r1Formula = '=IMDIV(IMSUM(-' . $postB . ',IMSQRT(' . $discriminant . ')),2 * ' . $postA . ')'; $r2Formula = '=IF(' . $discriminant . '=0,"Only one root",IMDIV(IMSUB(-' . $postB . ',IMSQRT(' . $discriminant . ')),2 * ' . $postA . '))'; /** @var string */ $output = Calculation::getInstance()->calculateFormula($r1Formula); $helper->log("$output"); /** @var string */ $output = Calculation::getInstance()->calculateFormula($r2Formula); $helper->log("$output"); $callEndTime = microtime(true); $helper->logEndingNotes(); } } ================================================ FILE: samples/Basic4/46_ReadHtml.php ================================================ load($html); $helper->logRead('Html', $html, $callStartTime); // Save $helper->write($objPHPExcel, __FILE__); ================================================ FILE: samples/Basic4/47_xlsfill.php ================================================ log('Read spreadsheet'); $reader = new Xls(); $spreadsheet = $reader->load(__DIR__ . '/../templates/47_xlsfill.xls'); // Save $helper->write($spreadsheet, __FILE__, ['Xls']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic4/47_xlsxfill.php ================================================ log('Read spreadsheet'); $reader = new Xlsx(); $spreadsheet = $reader->load(__DIR__ . '/../templates/47_xlsxfill.xlsx'); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic4/48_Image_move_size_with_cells.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->getCell('A1')->setValue('twocell'); $sheet->getCell('A2')->setValue('twocell'); $sheet->getCell('A3')->setValue('onecell'); $sheet->getCell('A6')->setValue('absolute'); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet two-cell anchor not resized'); $drawing = new Drawing(); $drawing->setName('PhpSpreadsheet'); $drawing->setDescription('PhpSpreadsheet'); $drawing->setPath(__DIR__ . '/../images/PhpSpreadsheet_logo.png'); // anchor type will be two-cell because Coordinates2 is set //$drawing->setAnchorType(Drawing::ANCHORTYPE_TWOCELL); $drawing->setCoordinates('B1'); $drawing->setCoordinates2('B1'); $drawing->setOffsetX2($drawing->getImageWidth()); $drawing->setOffsetY2($drawing->getImageHeight()); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet two-cell anchor resized'); $drawing2 = new Drawing(); $drawing2->setName('PhpSpreadsheet'); $drawing2->setDescription('PhpSpreadsheet'); $drawing2->setPath(__DIR__ . '/../images/PhpSpreadsheet_logo.png'); // anchor type will be two-cell because Coordinates2 is set //$drawing->setAnchorType(Drawing::ANCHORTYPE_TWOCELL); $drawing2->setCoordinates('C2'); $drawing2->setCoordinates2('C2'); $drawing2->setOffsetX2($drawing->getImageWidth()); $drawing2->setOffsetY2($drawing->getImageHeight()); $drawing2->setWorksheet($spreadsheet->getActiveSheet()); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth($drawing->getImageWidth(), Dimension::UOM_PIXELS); $spreadsheet->getActiveSheet()->getRowDimension(2)->setRowHeight($drawing->getImageHeight(), Dimension::UOM_PIXELS); // Add a drawing to the worksheet one cell anchor $helper->log('Add a drawing to the worksheet one-cell anchor'); $drawing3 = new Drawing(); $drawing3->setName('PhpSpreadsheet'); $drawing3->setDescription('PhpSpreadsheet'); $drawing3->setPath(__DIR__ . '/../images/PhpSpreadsheet_logo.png'); // anchor type will be one-cell because Coordinates2 is not set //$drawing->setAnchorType(Drawing::ANCHORTYPE_ONECELL); $drawing3->setCoordinates('D3'); $drawing3->setWorksheet($spreadsheet->getActiveSheet()); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet two-cell anchor resized absolute'); $drawing4 = new Drawing(); $drawing4->setName('PhpSpreadsheet'); $drawing4->setDescription('PhpSpreadsheet'); $drawing4->setPath(__DIR__ . '/../images/PhpSpreadsheet_logo.png'); // anchor type will be two-cell because Coordinates2 is set //$drawing->setAnchorType(Drawing::ANCHORTYPE_TWOCELL); $drawing4->setCoordinates('C6'); $drawing4->setCoordinates2('C6'); $drawing4->setOffsetX2($drawing->getImageWidth()); $drawing4->setOffsetY2($drawing->getImageHeight()); $drawing4->setWorksheet($spreadsheet->getActiveSheet()); $drawing4->setEditAs(Drawing::EDIT_AS_ABSOLUTE); //$spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth($drawing->getImageWidth(), Dimension::UOM_PIXELS); $spreadsheet->getActiveSheet()->getRowDimension(6)->setRowHeight($drawing->getImageHeight(), Dimension::UOM_PIXELS); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Basic4/49_alignment.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $spreadsheet->getProperties()->setTitle('Alignment'); $sheet = $spreadsheet->getActiveSheet(); $hi = 'Hi There'; $ju = 'This is a longer than normal sentence'; $sheet->fromArray([ ['', 'default', 'bottom', 'top', 'center', 'justify', 'distributed'], ['default', $hi, $hi, $hi, $hi, $hi, $hi], ['left', $hi, $hi, $hi, $hi, $hi, $hi], ['right', $hi, $hi, $hi, $hi, $hi, $hi], ['center', $hi, $hi, $hi, $hi, $hi, $hi], ['justify', $ju, $ju, $ju, $ju, $ju, $ju], ['distributed', $ju, $ju, $ju, $ju, $ju, $ju], ]); $sheet->getColumnDimension('B')->setWidth(20); $sheet->getColumnDimension('C')->setWidth(20); $sheet->getColumnDimension('D')->setWidth(20); $sheet->getColumnDimension('E')->setWidth(20); $sheet->getColumnDimension('F')->setWidth(20); $sheet->getColumnDimension('G')->setWidth(20); $sheet->getRowDimension(2)->setRowHeight(30); $sheet->getRowDimension(3)->setRowHeight(30); $sheet->getRowDimension(4)->setRowHeight(30); $sheet->getRowDimension(5)->setRowHeight(30); $sheet->getRowDimension(6)->setRowHeight(40); $sheet->getRowDimension(7)->setRowHeight(40); $minRow = 2; $maxRow = 7; $minCol = 'B'; $maxCol = 'g'; $sheet->getStyle("C$minRow:C$maxRow") ->getAlignment() ->setVertical(Alignment::VERTICAL_BOTTOM); $sheet->getStyle("D$minRow:D$maxRow") ->getAlignment() ->setVertical(Alignment::VERTICAL_TOP); $sheet->getStyle("E$minRow:E$maxRow") ->getAlignment() ->setVertical(Alignment::VERTICAL_CENTER); $sheet->getStyle("F$minRow:F$maxRow") ->getAlignment() ->setVertical(Alignment::VERTICAL_JUSTIFY); $sheet->getStyle("G$minRow:G$maxRow") ->getAlignment() ->setVertical(Alignment::VERTICAL_DISTRIBUTED); $sheet->getStyle("{$minCol}3:{$maxCol}3") ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_LEFT); $sheet->getStyle("{$minCol}4:{$maxCol}4") ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_RIGHT); $sheet->getStyle("{$minCol}5:{$maxCol}5") ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_CENTER); $sheet->getStyle("{$minCol}6:{$maxCol}6") ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_JUSTIFY); $sheet->getStyle("{$minCol}7:{$maxCol}7") ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_DISTRIBUTED); $sheet->getCell('A9')->setValue('Center Continuous A9-C9'); $sheet->getStyle('A9:C9') ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_CENTER_CONTINUOUS); $sheet->getCell('A10')->setValue('Fill'); $sheet->getStyle('A10') ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_FILL); $sheet->setSelectedCells('A1'); $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Html', 'Xls']); ================================================ FILE: samples/Basic5/50_xlsverticalbreak.php ================================================ log('Read spreadsheet'); $reader = new Xls(); $spreadsheet = $reader->load(__DIR__ . '/../templates/50_xlsverticalbreak.xls'); // Save $helper->write($spreadsheet, __FILE__, ['Xls']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic5/51_ProtectedSort.php ================================================ log('First sheet - protected, sorts not allowed'); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('sorttrue'); $sheet->getCell('A1')->setValue(10); $sheet->getCell('A2')->setValue(5); $sheet->getCell('B1')->setValue(15); $protection = $sheet->getProtection(); $protection->setPassword('testpassword'); $protection->setSheet(true); $protection->setInsertRows(true); $protection->setFormatCells(true); $protection->setObjects(true); $protection->setAutoFilter(false); $protection->setSort(true); $comment = $sheet->getComment('A1'); $text = new RichText(); $text->addText(new TextElement('Sort options should be grayed out. Sheet password to remove protections is testpassword for all sheets.')); $comment->setText($text)->setHeight('120pt')->setWidth('120pt'); $helper->log('Second sheet - protected, sorts allowed, but no permitted range defined'); $sheet = $spreadsheet->createSheet(); $sheet->setTitle('sortfalse'); $sheet->getCell('A1')->setValue(10); $sheet->getCell('A2')->setValue(5); $sheet->getCell('B1')->setValue(15); $protection = $sheet->getProtection(); $protection->setPassword('testpassword'); $protection->setSheet(true); $protection->setInsertRows(true); $protection->setFormatCells(true); $protection->setObjects(true); $protection->setAutoFilter(false); $protection->setSort(false); $comment = $sheet->getComment('A1'); $text = new RichText(); $text->addText(new TextElement('Sort options not grayed out, but no permissible sort range.')); $comment->setText($text)->setHeight('120pt')->setWidth('120pt'); $helper->log('Third sheet - protected, sorts allowed, but only on permitted range A:A, no range password needed'); $sheet = $spreadsheet->createSheet(); $sheet->setTitle('sortfalsenocolpw'); $sheet->getCell('A1')->setValue(10); $sheet->getCell('A2')->setValue(5); $sheet->getCell('C1')->setValue(15); $protection = $sheet->getProtection(); $protection->setPassword('testpassword'); $protection->setSheet(true); $protection->setInsertRows(true); $protection->setFormatCells(true); $protection->setObjects(true); $protection->setAutoFilter(false); $protection->setSort(false); $sheet->protectCells('A:A'); $comment = $sheet->getComment('A1'); $text = new RichText(); $text->addText(new TextElement('Column A may be sorted without a password. No sort for any other column.')); $comment->setText($text)->setHeight('120pt')->setWidth('120pt'); $helper->log('Fourth sheet - protected, sorts allowed, but only on permitted range A:A, and range password needed'); $sheet = $spreadsheet->createSheet(); $sheet->setTitle('sortfalsecolpw'); $sheet->getCell('A1')->setValue(10); $sheet->getCell('A2')->setValue(5); $sheet->getCell('C1')->setValue(15); $protection = $sheet->getProtection(); $protection->setPassword('testpassword'); $protection->setSheet(true); $protection->setInsertRows(true); $protection->setFormatCells(true); $protection->setObjects(true); $protection->setAutoFilter(false); $protection->setSort(false); $sheet->protectCells('A:A', 'sortpw', false, 'sortrange'); $comment = $sheet->getComment('A1'); $text = new RichText(); $text->addText(new TextElement('Column A may be sorted with password sortpw. No sort for any other column.')); $comment->setText($text)->setHeight('120pt')->setWidth('120pt'); // Save $helper->write($spreadsheet, __FILE__, ['Xls', 'Xlsx']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic5/52_Currency.php ================================================ log('First sheet - Accounting Wizard'); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Accounting'); $sheet->getCell('A1')->setValue('Currency'); $sheet->getCell('B1')->setValue('Decimals'); $sheet->getCell('C1')->setValue('ThouSep'); $sheet->getCell('D1')->setValue('Lead'); $sheet->getCell('E1')->setValue('Spacing'); $sheet->getCell('F1')->setValue('Neg'); $sheet->getCell('G1')->setValue('Pos'); $sheet->getCell('H1')->setValue('Zero'); $sheet->getCell('I1')->setValue('Neg'); $sheet->getCell('J1')->setValue('Text'); $sheet->getCell('L1')->setValue('ActWiz$'); $sheet->getCell('M1')->setValue('ActWiz€Trl'); $sheet->freezePane('A2'); $sheet->getComment('E1')->getText()->createText('ignored, always true for Accounting'); $sheet->getComment('F1')->getText()->createText('ignored, always () for Accounting'); $sheet->getCell('A2')->setValue('AcctUSD'); $sheet->getCell('G2')->setValue(1234.56); $sheet->getCell('H2')->setValue(0); $sheet->getCell('I2')->setValue(-1234.56); $sheet->getCell('J2')->setValue('text'); $sheet->getStyle('G2:J2')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_ACCOUNTING_USD); $sheet->getCell('A3')->setValue('AcctEur'); $sheet->getCell('G3')->setValue(1234.56); $sheet->getCell('H3')->setValue(0); $sheet->getCell('I3')->setValue(-1234.56); $sheet->getCell('J3')->setValue('Text'); $sheet->getStyle('G3:J3')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_ACCOUNTING_EUR); $sheet->getCell('A4')->setValue('AcctWiz¥'); $sheet->getCell('E4')->setValue(true); $sheet->getCell('G4')->setValue(1234.56); $sheet->getCell('H4')->setValue(0); $sheet->getCell('I4')->setValue(-1234.56); $sheet->getCell('J4')->setValue('Text'); $sheet->getStyle('G4:J4')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('¥', currencySymbolSpacing: true))->format(), ], ] ); $sheet->getCell('A5')->setValue('StalePR¥'); $sheet->getCell('G5')->setValue(1234.56); $sheet->getCell('H5')->setValue(0); $sheet->getCell('I5')->setValue(-1234.56); $sheet->getCell('J5')->setValue('Text'); $sheet->getStyle('G5:J5')->getNumberFormat()->setFormatCode('_("¥"* #,##0.00_);_("¥"* -#,##0.00_);_("¥"* "-"??_);_(@_)'); $sheet->getCell('A6')->setValue('AcctWiz¥'); $sheet->getCell('E6')->setValue(true); $sheet->getCell('F6')->setValue(CurrencyNegative::minus->name); $sheet->getCell('G6')->setValue(1234.56); $sheet->getCell('H6')->setValue(0); $sheet->getCell('I6')->setValue(-1234.56); $sheet->getCell('J6')->setValue('Text'); $sheet->getStyle('G6:J6')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('¥', currencySymbolSpacing: true, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('A7')->setValue('AcctWiz¥'); $sheet->getCell('E7')->setValue(false); $sheet->getCell('F7')->setValue(CurrencyNegative::minus->name); $sheet->getCell('G7')->setValue(1234.56); $sheet->getCell('H7')->setValue(0); $sheet->getCell('I7')->setValue(-1234.56); $sheet->getCell('J7')->setValue('Text'); $sheet->getStyle('G7:J7')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('¥', currencySymbolSpacing: false, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('A8')->setValue('AcctWiz¥'); $sheet->getCell('E8')->setValue(false); $sheet->getCell('F8')->setValue(CurrencyNegative::parentheses->name); $sheet->getCell('G8')->setValue(1234.56); $sheet->getCell('H8')->setValue(0); $sheet->getCell('I8')->setValue(-1234.56); $sheet->getCell('J8')->setValue('Text'); $sheet->getStyle('G8:J8')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('¥', currencySymbolSpacing: false, negative: CurrencyNegative::parentheses))->format(), ], ] ); $sheet->getCell('A9')->setValue('AcctW HUF'); $sheet->getCell('E9')->setValue(true); $sheet->getCell('G9')->setValue(1234.56); $sheet->getCell('H9')->setValue(0); $sheet->getCell('I9')->setValue(-1234.56); $sheet->getCell('J9')->setValue('Text'); $sheet->getStyle('G9:J9')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('HUF', currencySymbolSpacing: true))->format(), ], ] ); $sheet->getCell('A10')->setValue('AcctW HUF'); $sheet->getCell('E10')->setValue(true); $sheet->getCell('F10')->setValue(CurrencyNegative::redParentheses->name); $sheet->getStyle('F10')->getFont()->getColor()->setRgb('FF0000'); $sheet->getCell('G10')->setValue(1234.56); $sheet->getCell('H10')->setValue(0); $sheet->getCell('I10')->setValue(-1234.56); $sheet->getCell('J10')->setValue('Text'); $sheet->getStyle('G10:J10')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('HUF', currencySymbolSpacing: true, negative: CurrencyNegative::redParentheses))->format(), ], ] ); $sheet->getCell('A11')->setValue('AcctW Kazakh'); $sheet->getCell('D11')->setValue(false); $sheet->getCell('G11')->setValue(1234.56); $sheet->getCell('H11')->setValue(0); $sheet->getCell('I11')->setValue(-1234.56); $sheet->getCell('J11')->setValue('Text'); $sheet->getStyle('G11:J11')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Accounting('₸', currencySymbolPosition: Accounting::TRAILING_SYMBOL))->format(), ], ] ); $sheet->getCell('A12')->setValue('AcctW $'); $sheet->getCell('B12')->setValue(3); $sheet->getCell('C12')->setValue(false); $sheet->getCell('D12')->setValue(false); $sheet->getCell('F12')->setValue(CurrencyNegative::redMinus->name); $sheet->getStyle('F12')->getFont()->getColor()->setRgb('FF0000'); $sheet->getCell('G12')->setValue(1234.56); $sheet->getCell('H12')->setValue(0); $sheet->getCell('I12')->setValue(-1234.56); $sheet->getCell('J12')->setValue('Text'); $format = new Accounting( '$', decimals: 3, thousandsSeparator: false, currencySymbolPosition: Accounting::TRAILING_SYMBOL, negative: CurrencyNegative::redMinus ); $sheet->getStyle('G12:J12')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => $format->format(), ], ] ); $sheet->getCell('L2')->setValue(1234.56); $sheet->getCell('L3')->setValue(0); $sheet->getCell('L4')->setValue(-1234.56); $format = new Accounting('$'); $sheet->getStyle('L2:L4')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => $format->format(), ], ] ); $sheet->getCell('M2')->setValue(1234.56); $sheet->getCell('M3')->setValue(0); $sheet->getCell('M4')->setValue(-1234.56); $format = new Accounting('€', currencySymbolPosition: Accounting::TRAILING_SYMBOL); $sheet->getStyle('M2:M4')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => $format->format(), ], ] ); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('F')->setAutoSize(true); $sheet->getColumnDimension('G')->setAutoSize(true); $sheet->getColumnDimension('I')->setAutoSize(true); $sheet->getColumnDimension('L')->setAutoSize(true); $sheet->getColumnDimension('M')->setAutoSize(true); $sheet->setSelectedCells('J1'); // second sheet $helper->log('Second sheet - Currency Wizard'); $sheet = $spreadsheet->createSheet(); $sheet->setTitle('Currency'); $sheet->getCell('A1')->setValue('Currency'); $sheet->getCell('B1')->setValue('Decimals'); $sheet->getCell('C1')->setValue('ThouSep'); $sheet->getCell('D1')->setValue('Lead'); $sheet->getCell('E1')->setValue('Spacing'); $sheet->getCell('F1')->setValue('Negative'); $sheet->getCell('G1')->setValue('Pos'); $sheet->getCell('H1')->setValue('Zero'); $sheet->getCell('I1')->setValue('Neg'); $sheet->getCell('J1')->setValue('Text'); $sheet->freezePane('A2'); $sheet->getComment('E1')->getText()->createText('ignored, always false for Currency'); $sheet->getCell('A2')->setValue('CurrUSD'); $sheet->getCell('G2')->setValue(1234.56); $sheet->getCell('H2')->setValue(0); $sheet->getCell('I2')->setValue(-1234.56); $sheet->getCell('J2')->setValue('text'); $sheet->getStyle('G2:J2')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD); $sheet->getCell('A3')->setValue('CurrEur'); $sheet->getCell('G3')->setValue(1234.56); $sheet->getCell('H3')->setValue(0); $sheet->getCell('I3')->setValue(-1234.56); $sheet->getCell('J3')->setValue('Text'); $sheet->getStyle('G3:J3')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR); $sheet->getCell('A4')->setValue('CurrWiz¥'); $sheet->getCell('E4')->setValue(true); $sheet->getCell('G4')->setValue(1234.56); $sheet->getCell('H4')->setValue(0); $sheet->getCell('I4')->setValue(-1234.56); $sheet->getCell('J4')->setValue('Text'); $sheet->getStyle('G4:J4')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('¥', currencySymbolSpacing: true))->format(), ], ] ); $sheet->getCell('A5')->setValue('StalePR¥'); $sheet->getCell('G5')->setValue(1234.56); $sheet->getCell('H5')->setValue(0); $sheet->getCell('I5')->setValue(-1234.56); $sheet->getCell('J5')->setValue('Text'); $sheet->getStyle('G5:J5')->getNumberFormat()->setFormatCode('¥ #,##0'); $sheet->getCell('A6')->setValue('CurrWiz¥'); $sheet->getCell('E6')->setValue(true); $sheet->getCell('F6')->setValue(CurrencyNegative::minus->name); $sheet->getCell('G6')->setValue(1234.56); $sheet->getCell('H6')->setValue(0); $sheet->getCell('I6')->setValue(-1234.56); $sheet->getCell('J6')->setValue('Text'); $sheet->getStyle('G6:J6')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('¥', currencySymbolSpacing: true, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('A7')->setValue('CurrWiz¥'); $sheet->getCell('E7')->setValue(false); $sheet->getCell('F7')->setValue(CurrencyNegative::minus->name); $sheet->getCell('G7')->setValue(1234.56); $sheet->getCell('H7')->setValue(0); $sheet->getCell('I7')->setValue(-1234.56); $sheet->getCell('J7')->setValue('Text'); $sheet->getStyle('G7:J7')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('¥', currencySymbolSpacing: false, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('A8')->setValue('CurrWiz¥'); $sheet->getCell('E8')->setValue(false); $sheet->getCell('F8')->setValue(CurrencyNegative::parentheses->name); $sheet->getCell('G8')->setValue(1234.56); $sheet->getCell('H8')->setValue(0); $sheet->getCell('I8')->setValue(-1234.56); $sheet->getCell('J8')->setValue('Text'); $sheet->getStyle('G8:J8')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('¥', currencySymbolSpacing: false, negative: CurrencyNegative::parentheses))->format(), ], ] ); $sheet->getCell('A9')->setValue('CurrW HUF'); $sheet->getCell('E9')->setValue(true); $sheet->getCell('G9')->setValue(1234.56); $sheet->getCell('H9')->setValue(0); $sheet->getCell('I9')->setValue(-1234.56); $sheet->getCell('J9')->setValue('Text'); $sheet->getStyle('G9:J9')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('HUF', currencySymbolSpacing: true))->format(), ], ] ); $sheet->getCell('A10')->setValue('CurrW HUF'); $sheet->getCell('E10')->setValue(true); $sheet->getCell('F10')->setValue(CurrencyNegative::redParentheses->name); $sheet->getStyle('F10')->getFont()->getColor()->setRgb('FF0000'); $sheet->getCell('G10')->setValue(1234.56); $sheet->getCell('H10')->setValue(0); $sheet->getCell('I10')->setValue(-1234.56); $sheet->getCell('J10')->setValue('Text'); $sheet->getStyle('G10:J10')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('HUF', currencySymbolSpacing: true, negative: CurrencyNegative::redParentheses))->format(), ], ] ); $sheet->getCell('A11')->setValue('CurrW Kazakh'); $sheet->getCell('D11')->setValue(false); $sheet->getCell('G11')->setValue(1234.56); $sheet->getCell('H11')->setValue(0); $sheet->getCell('I11')->setValue(-1234.56); $sheet->getCell('J11')->setValue('Text'); $sheet->getStyle('G11:J11')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new Currency('₸', currencySymbolPosition: Accounting::TRAILING_SYMBOL))->format(), ], ] ); $sheet->getCell('A12')->setValue('CurrW $'); $sheet->getCell('B12')->setValue(3); $sheet->getCell('C12')->setValue(false); $sheet->getCell('D12')->setValue(false); $sheet->getCell('F12')->setValue(CurrencyNegative::redMinus->name); $sheet->getStyle('F12')->getFont()->getColor()->setRgb('FF0000'); $sheet->getCell('G12')->setValue(1234.56); $sheet->getCell('H12')->setValue(0); $sheet->getCell('I12')->setValue(-1234.56); $sheet->getCell('J12')->setValue('Text'); $format = new Currency( '$', decimals: 3, thousandsSeparator: false, currencySymbolPosition: Currency::TRAILING_SYMBOL, negative: CurrencyNegative::redMinus ); $sheet->getStyle('G12:J12')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => $format->format(), ], ] ); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('F')->setAutoSize(true); $sheet->getColumnDimension('G')->setAutoSize(true); $sheet->getColumnDimension('H')->setAutoSize(true); $sheet->getColumnDimension('I')->setAutoSize(true); $sheet->setSelectedCells('J1'); // third sheet $helper->log('Third sheet - CurrencyBase Wizard'); $sheet = $spreadsheet->createSheet(); $sheet->setTitle('CurrencyBase'); $sheet->getCell('A1')->setValue('Currency'); $sheet->getCell('B1')->setValue('Decimals'); $sheet->getCell('C1')->setValue('ThouSep'); $sheet->getCell('D1')->setValue('Lead'); $sheet->getCell('E1')->setValue('Spacing'); $sheet->getCell('F1')->setValue('Negative'); $sheet->getCell('G1')->setValue('Pos'); $sheet->getCell('H1')->setValue('Zero'); $sheet->getCell('I1')->setValue('Neg'); $sheet->getCell('J1')->setValue('Text'); $sheet->freezePane('A2'); $sheet->getCell('A2')->setValue('StaleAct¥'); $sheet->getCell('G2')->setValue(1234.56); $sheet->getCell('H2')->setValue(0); $sheet->getCell('I2')->setValue(-1234.56); $sheet->getCell('J2')->setValue('Text'); $sheet->getStyle('G2:J2')->getNumberFormat()->setFormatCode('_("¥"* #,##0.00_);_("¥"* -#,##0.00_);_("¥"* "-"??_);_(@_)'); $sheet->getCell('A3')->setValue('CurBase ¥'); $sheet->getCell('E3')->setValue(true); $sheet->getCell('F3')->setValue(CurrencyNegative::minus->name); $sheet->getCell('G3')->setValue(1234.56); $sheet->getCell('H3')->setValue(0); $sheet->getCell('I3')->setValue(-1234.56); $sheet->getCell('J3')->setValue('Text'); $sheet->getStyle('G3:J3')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new CurrencyBase('¥', currencySymbolSpacing: true, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('G4')->setValue(-1234.56); $sheet->getStyle('G4')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new CurrencyBase('¥', currencySymbolSpacing: true, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('G5')->setValue(0); $sheet->getStyle('G5')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new CurrencyBase('¥', currencySymbolSpacing: true, negative: CurrencyNegative::minus))->format(), ], ] ); $sheet->getCell('A6')->setValue('StaleCur¥'); $sheet->getCell('G6')->setValue(1234.56); $sheet->getCell('H6')->setValue(0); $sheet->getCell('I6')->setValue(-1234.56); $sheet->getCell('J6')->setValue('Text'); $sheet->getStyle('G6:J6')->getNumberFormat()->setFormatCode('¥ #,##0'); $sheet->getCell('A7')->setValue('CurBase ¥'); $sheet->getCell('B7')->setValue(0); $sheet->getCell('G7')->setValue(1234.56); $sheet->getCell('H7')->setValue(0); $sheet->getCell('I7')->setValue(-1234.56); $sheet->getCell('J7')->setValue('Text'); $sheet->getStyle('G7:J7')->applyFromArray( [ 'numberFormat' => [ 'formatCode' => (new CurrencyBase('¥', 0))->format(), ], ] ); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('F')->setAutoSize(true); $sheet->getColumnDimension('G')->setAutoSize(true); $sheet->getColumnDimension('H')->setAutoSize(true); $sheet->getColumnDimension('I')->setAutoSize(true); $sheet->setSelectedCells('J1'); $spreadsheet->setActiveSheetIndex(0); $helper->write($spreadsheet, __FILE__, ['Xls', 'Xlsx']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic5/53_ImageOpacity.php ================================================ getProperties()->setTitle('53_ImageOpacity'); $helper->log('Add image to spreadsheet 6 times with different opacities'); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Squares different opacities'); $sheet->setShowGridLines(false); $drawing = new Drawing(); $drawing->setName('Blue Square opacity not specified'); $drawing->setPath($path); $drawing->setCoordinates('A1'); $drawing->setCoordinates2('B5'); $drawing->setWorksheet($sheet); $drawing = new Drawing(); $drawing->setName('Blue Square opacity 80%'); $drawing->setPath($path); $drawing->setCoordinates('C1'); $drawing->setCoordinates2('D5'); $drawing->setOpacity(80000); $drawing->setWorksheet($sheet); $drawing = new Drawing(); $drawing->setWorksheet($sheet); $drawing->setName('Blue Square opacity 60%'); $drawing->setPath($path); $drawing->setCoordinates('E1'); $drawing->setCoordinates2('F5'); $drawing->setOpacity(60000); $drawing = new Drawing(); $drawing->setName('Blue Square opacity 40%'); $drawing->setPath($path); $drawing->setCoordinates('A8'); $drawing->setCoordinates2('B12'); $drawing->setOpacity(40000); $drawing->setWorksheet($sheet); $drawing = new Drawing(); $drawing->setName('Blue Square opacity 20%'); $drawing->setPath($path); $drawing->setCoordinates('C8'); $drawing->setCoordinates2('D12'); $drawing->setOpacity(20000); $drawing->setWorksheet($sheet); $drawing = new Drawing(); $drawing->setWorksheet($sheet); $drawing->setName('Blue Square opacity 0%'); $drawing->setPath($path); $drawing->setCoordinates('E8'); $drawing->setCoordinates2('F12'); $drawing->setOpacity(0); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Html', 'Dompdf', 'Mpdf']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic5/54_ImagesInAndOut.php ================================================ getProperties()->setTitle('53_ImageOpacity'); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Images in-cell and out'); $sheet->setShowGridLines(false); $helper->log('Add in-cell image to spreadsheet'); $sheet->setCellValue('B1', 'inside'); $drawing = new Drawing(); $drawing->setName('Blue Square in-cell'); $drawing->setPath($path); $sheet->getCell('B2')->setValue($drawing); $helper->log('Add image over cell to spreadsheet'); $sheet->setCellValue('C1', 'outside'); $drawing = new Drawing(); $drawing->setName('Blue Square out-of-cell'); $drawing->setPath($path); $drawing->setCoordinates('C2'); $drawing->setCoordinates2('D6'); $drawing->setWorksheet($sheet); $helper->log('In-cell supported only for Xlsx'); $helper->write($spreadsheet, __FILE__, ['Xlsx']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic5/55_DefinedStyles.php ================================================ getActiveSheet(); $array = [ ['NUMBER', 1, NumberFormat::FORMAT_NUMBER], ['NUMBER_0', 1, NumberFormat::FORMAT_NUMBER_0], ['NUMBER_00', 1, NumberFormat::FORMAT_NUMBER_00], ['NUMBER_COMMA_SEPARATED1', 1234, NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1], ['NUMBER_COMMA_SEPARATED2', 1234, NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2], ['PERCENTAGE', 0.98, NumberFormat::FORMAT_PERCENTAGE], ['PERCENTAGE_0', 0.985, NumberFormat::FORMAT_PERCENTAGE_0], ['PERCENTAGE_00', 0.9856, NumberFormat::FORMAT_PERCENTAGE_00], ['DATE_YYYYMMDD', 46000, NumberFormat::FORMAT_DATE_YYYYMMDD], ['DATE_DDMMYYYY', 46000, NumberFormat::FORMAT_DATE_DDMMYYYY], ['DATE_DMYSLASH', 46000, NumberFormat::FORMAT_DATE_DMYSLASH], ['DATE_DMYMINUS', 46000, NumberFormat::FORMAT_DATE_DMYMINUS], ['DATE_DMMINUS', 46000, NumberFormat::FORMAT_DATE_DMMINUS], ['DATE_MYMINUS', 46000, NumberFormat::FORMAT_DATE_MYMINUS], ['DATE_XLSX14', 46000, NumberFormat::FORMAT_DATE_XLSX14], ['DATE_XLSX14_ACTUAL', 46000, NumberFormat::FORMAT_DATE_XLSX14_ACTUAL], ['DATE_XLSX15', 46000, NumberFormat::FORMAT_DATE_XLSX15], ['DATE_XLSX15_YYYY', 46000, NumberFormat::FORMAT_DATE_XLSX15_YYYY], ['DATE_XLSX16', 46000, NumberFormat::FORMAT_DATE_XLSX16], ['DATE_XLSX17', 46000, NumberFormat::FORMAT_DATE_XLSX17], ['DATE_XLSX22', 46000, NumberFormat::FORMAT_DATE_XLSX22], ['DATE_XLSX22_ACTUAL', 46000, NumberFormat::FORMAT_DATE_XLSX22_ACTUAL], ['DATE_DATETIME', 46000.25, NumberFormat::FORMAT_DATE_DATETIME], ['DATE_DATETIME_BETTER', 46000.25, NumberFormat::FORMAT_DATE_DATETIME_BETTER], ['DATE_TIME1', 46000.25, NumberFormat::FORMAT_DATE_TIME1], ['DATE_TIME2', 46000.25, NumberFormat::FORMAT_DATE_TIME2], ['DATE_TIME3', 46000.25, NumberFormat::FORMAT_DATE_TIME3], ['DATE_TIME4', 46000.25, NumberFormat::FORMAT_DATE_TIME4], ['DATE_TIME5', 46000.25, NumberFormat::FORMAT_DATE_TIME5], ['DATE_TIME6', 46000.25, NumberFormat::FORMAT_DATE_TIME6], ['DATE_TIME7', 46000.25, NumberFormat::FORMAT_DATE_TIME7], ['DATE_TIME8', 46000.25, NumberFormat::FORMAT_DATE_TIME8], [' DATE_TIME_INTERVAL_HMS', 0.0087731481481482, NumberFormat::FORMAT_DATE_TIME_INTERVAL_HMS], ['DATE_YYYYMMDDSLASH', 46000, NumberFormat::FORMAT_DATE_YYYYMMDDSLASH], ['DATE_LONG_DATE', 46000, NumberFormat::FORMAT_DATE_LONG_DATE], ['CURRENCY_USD_INTEGER', 1234.56, NumberFormat::FORMAT_CURRENCY_USD_INTEGER], ['CURRENCY_USD', 1234.56, NumberFormat::FORMAT_CURRENCY_USD], ['CURRENCY_EUR_INTEGER', 1234.56, NumberFormat::FORMAT_CURRENCY_EUR_INTEGER], ['CURRENCY_EUR', 1234.56, NumberFormat::FORMAT_CURRENCY_EUR], ['CURRENCY_GBP_INTEGER', 1234.56, NumberFormat::FORMAT_CURRENCY_GBP_INTEGER], ['CURRENCY_GBP', 1234.56, NumberFormat::FORMAT_CURRENCY_GBP], ['CURRENCY_YEN_YUAN_INTEGER', 1234.56, NumberFormat::FORMAT_CURRENCY_YEN_YUAN_INTEGER], ['CURRENCY_YEN_YUAN', 1234.56, NumberFormat::FORMAT_CURRENCY_YEN_YUAN], ['ACCOUNTING_USD', 1234.56, NumberFormat::FORMAT_CURRENCY_USD], ['ACCOUNTING_EUR', 1234.56, NumberFormat::FORMAT_CURRENCY_EUR], ['CUSTOM1', 1234.56, '0.000'], ['CUSTOM2', 1234.56, '"$"#,##0.00_);[Red]\("$"#,##0.00\)'], ]; $row = 0; $helper->log('Populate spreadsheet'); foreach ($array as $cells) { ++$row; $sheet->getCell("A$row")->setValue($cells[0]); $sheet->getCell("B$row")->setValue($cells[1]); if (!str_starts_with($cells[0], 'DATE')) { $sheet->getCell("C$row")->setValue(-$cells[1]); } $sheet->getStyle("B$row:C$row") ->getNumberFormat() ->setFormatCode($cells[2]); } $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); $sheet->getColumnDimension('C')->setAutoSize(true); $sheet->setSelectedCells('A1'); function threeDecimalPlaces(Style $obj, string $name): void { $writer = $obj->getWriter(); $writer->startElement('number:number-style'); $writer->writeAttribute('style:name', $name); $writer->startElement('number:number'); $writer->writeAttribute('number:decimal-places', '3'); $writer->writeAttribute('number:min-decimal-places', '3'); $writer->writeAttribute('number:min-integer-digits', '1'); $writer->endElement(); // number:number $writer->endElement(); // number:number-style } function redBrackets(Style $obj, string $name): void { $writer = $obj->getWriter(); $writer->startElement('number:currency-style'); $writer->writeAttribute('style:name', $name . 'P0'); $writer->writeElement('number:currency-symbol', '$'); $writer->startElement('number:number'); $writer->writeAttribute('number:decimal-places', '2'); $writer->writeAttribute('number:min-decimal-places', '2'); $writer->writeAttribute('number:min-integer-digits', '1'); $writer->writeAttribute('number:grouping', 'true'); $writer->endElement(); // number:number $writer->writeElement('number:text', ' '); $writer->endElement(); // number:currency-style $writer->startElement('number:currency-style'); $writer->writeAttribute('style:name', $name); $writer->startElement('style:text-properties'); $writer->writeAttribute('fo:color', '#FF0000'); $writer->endElement(); // style:text-properties $writer->writeElement('number:text', '($'); $writer->startElement('number:number'); $writer->writeAttribute('number:decimal-places', '2'); $writer->writeAttribute('number:min-decimal-places', '2'); $writer->writeAttribute('number:min-integer-digits', '1'); $writer->writeAttribute('number:grouping', 'true'); $writer->endElement(); // number:number $writer->writeElement('number:text', ')'); $writer->startElement('style:map'); $writer->writeAttribute('style:condition', 'value()>=0'); $writer->writeAttribute('style:apply-style-name', $name . 'P0'); $writer->endElement(); // style:map $writer->endElement(); // number:currency-style } function writeAdditional(BaseWriter $writer): void { if (method_exists($writer, 'useAdditionalNumberFormats')) { $array = [ '0.000' => threeDecimalPlaces(...), '"$"#,##0.00_);[Red]\("$"#,##0.00\)' => redBrackets(...), ]; $writer->useAdditionalNumberFormats($array); } } $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Ods'], writerCallback: writeAdditional(...)); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Basic5/56_OdsToISO8601.php ================================================ open($infile) !== true) { throw new Exception("unable to open zip $infile"); } $files = ['content.xml', 'styles.xml']; $modified = false; foreach ($files as $file) { $data = $zip->getFromName($file); if ($data === false) { throw new Exception("unable to read member $file"); } $newData = str_replace('', '', $data); $newData = preg_replace( '~' . '()' . '[/-]' . '()' . '[/-]' . '()' . '~', '$3-$2' . '-$1', $newData ) ?? $newData; $newData = preg_replace( '~' . '()' . '[/-]' . '()' . '[/-]' . '()' . '~', '$3-$1' . '-$2', $newData ) ?? $newData; $newData = preg_replace( '~' . '(]*)' . ' number:automatic-order="true"' . '~', '$1', $newData ) ?? $newData; if ($data === $newData) { $helper->log("no changes needed for $file"); } else { $zip->deleteName($file); $zip->addFromString($file, $newData); $helper->log("modified $file"); $modified = true; } } $zip->close(); if ($modified) { $helper->log("Modified $infile"); } else { $helper->log("No modifications to $infile"); } } $infileBase = '56_MixedDateFormats.ods'; $infileBase1 = __DIR__ . '/../templates/' . $infileBase; $infile = realpath($infileBase1); if ($infile === false) { throw new Exception("Unable to locate $infileBase1"); } /** @var Sample $helper */ $helper->log("Infile is $infile"); $outDirectory = $helper->getTemporaryFolder(); $helper->log("outDirectory is $outDirectory"); $outfile = $outDirectory . '/56_OdsToISO8601.ods'; $helper->log("Outfile is $outfile"); $helper->log('Attempting copy'); if (!copy($infile, $outfile)) { throw new Exception('Copy failed'); } $helper->log('Update date formatting xml'); datesToIso8601($outfile, $helper); $helper->addDownloadLink($outfile); ================================================ FILE: samples/Bitwise/BITAND.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [1, 5], [3, 5], [1, 6], [9, 6], [13, 25], [23, 10], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=TEXT(DEC2BIN(A' . $row . '), "00000")'); $worksheet->setCellValue('D' . $row, '=TEXT(DEC2BIN(B' . $row . '), "00000")'); $worksheet->setCellValue('E' . $row, '=BITAND(A' . $row . ',B' . $row . ')'); $worksheet->setCellValue('F' . $row, '=TEXT(DEC2BIN(E' . $row . '), "00000")'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): Bitwise AND of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ') and ' . $worksheet->getCell('B' . $row)->getValueString() . '(' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ') is ' . $worksheet->getCell('E' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('F' . $row)->getCalculatedValueString() . ')' ); } ================================================ FILE: samples/Bitwise/BITLSHIFT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [1], [3], [9], [15], [26], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=DEC2BIN(A' . $row . ')'); $worksheet->setCellValue('C' . $row, '=BITLSHIFT(A' . $row . ',1)'); $worksheet->setCellValue('D' . $row, '=DEC2BIN(C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=BITLSHIFT(A' . $row . ',2)'); $worksheet->setCellValue('F' . $row, '=DEC2BIN(E' . $row . ')'); $worksheet->setCellValue('G' . $row, '=BITLSHIFT(A' . $row . ',3)'); $worksheet->setCellValue('H' . $row, '=DEC2BIN(G' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): Bitwise Left Shift of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ') by 1 bit is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ')' ); $helper->log( "(E$row): Bitwise Left Shift of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ') by 2 bits is ' . $worksheet->getCell('E' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('F' . $row)->getCalculatedValueString() . ')' ); $helper->log( "(E$row): Bitwise Left Shift of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ') by 3 bits is ' . $worksheet->getCell('G' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('H' . $row)->getCalculatedValueString() . ')' ); } ================================================ FILE: samples/Bitwise/BITOR.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [1, 5], [3, 5], [1, 6], [9, 6], [13, 25], [23, 10], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=TEXT(DEC2BIN(A' . $row . '), "00000")'); $worksheet->setCellValue('D' . $row, '=TEXT(DEC2BIN(B' . $row . '), "00000")'); $worksheet->setCellValue('E' . $row, '=BITOR(A' . $row . ',B' . $row . ')'); $worksheet->setCellValue('F' . $row, '=TEXT(DEC2BIN(E' . $row . '), "00000")'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): Bitwise OR of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ') and ' . $worksheet->getCell('B' . $row)->getValueString() . '(' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ') is ' . $worksheet->getCell('E' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('F' . $row)->getCalculatedValueString() . ')' ); } ================================================ FILE: samples/Bitwise/BITRSHIFT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [9], [15], [26], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=DEC2BIN(A' . $row . ')'); $worksheet->setCellValue('C' . $row, '=BITRSHIFT(A' . $row . ',1)'); $worksheet->setCellValue('D' . $row, '=DEC2BIN(C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=BITRSHIFT(A' . $row . ',2)'); $worksheet->setCellValue('F' . $row, '=DEC2BIN(E' . $row . ')'); $worksheet->setCellValue('G' . $row, '=BITRSHIFT(A' . $row . ',3)'); $worksheet->setCellValue('H' . $row, '=DEC2BIN(G' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): Bitwise Right Shift of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ') by 1 bit is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ')' ); $helper->log( "(E$row): Bitwise Right Shift of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ') by 2 bits is ' . $worksheet->getCell('E' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('F' . $row)->getCalculatedValueString() . ')' ); $helper->log( "(E$row): Bitwise Right Shift of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ') by 3 bits is ' . $worksheet->getCell('G' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('H' . $row)->getCalculatedValueString() . ')' ); } ================================================ FILE: samples/Bitwise/BITXOR.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [1, 5], [3, 5], [1, 6], [9, 6], [13, 25], [23, 10], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=TEXT(DEC2BIN(A' . $row . '), "00000")'); $worksheet->setCellValue('D' . $row, '=TEXT(DEC2BIN(B' . $row . '), "00000")'); $worksheet->setCellValue('E' . $row, '=BITXOR(A' . $row . ',B' . $row . ')'); $worksheet->setCellValue('F' . $row, '=TEXT(DEC2BIN(E' . $row . '), "00000")'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): Bitwise XOR of " . $worksheet->getCell('A' . $row)->getValueString() . ' (' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ') and ' . $worksheet->getCell('B' . $row)->getValueString() . '(' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ') is ' . $worksheet->getCell('E' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('F' . $row)->getCalculatedValueString() . ')' ); } ================================================ FILE: samples/Bootstrap.php ================================================ 1)) { $inputFileNames = []; for ($i = 1; $i < $argc; ++$i) { $inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i]; } } else { $inputFileNames = glob($inputFileNames) ?: []; } foreach ($inputFileNames as $inputFileName) { $inputFileNameShort = basename($inputFileName); if (!file_exists($inputFileName)) { $helper->log('File ' . $inputFileNameShort . ' does not exist'); continue; } $reader = IOFactory::createReader($inputFileType); $reader->setIncludeCharts(true); $callStartTime = microtime(true); $spreadsheet = $reader->load($inputFileName); $helper->logRead($inputFileType, $inputFileName, $callStartTime); $helper->log('Iterate worksheets looking at the charts'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetName = $worksheet->getTitle(); $helper->log('Worksheet: ' . $sheetName); $chartNames = $worksheet->getChartNames(); if (empty($chartNames)) { $helper->log(' There are no charts in this worksheet'); } else { natsort($chartNames); foreach ($chartNames as $i => $chartName) { $chart = $worksheet->getChartByNameOrThrow($chartName); if ($chart->getTitle() !== null) { $caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"'; } else { $caption = 'Untitled'; } $helper->log(' ' . $chartName . ' - ' . $caption); $indentation = str_repeat(' ', strlen($chartName) + 3); $groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount(); if ($groupCount == 1) { $chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType(); $helper->log($indentation . ' ' . $chartType); $helper->renderChart($chart, __FILE__); } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { $chartType = 'Multiple Plot ' . array_pop($chartTypes); $helper->log($indentation . ' ' . $chartType); $helper->renderChart($chart, __FILE__); } elseif (count($chartTypes) == 0) { $helper->log($indentation . ' *** Type not yet implemented'); } else { $helper->log($indentation . ' Combination Chart'); $helper->renderChart($chart, __FILE__); } } } } } $outputFileName = $helper->getFilename($inputFileName); $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->setIncludeCharts(true); $callStartTime = microtime(true); $writer->save($outputFileName); $helper->logWrite($writer, $outputFileName, $callStartTime); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); } ================================================ FILE: samples/Chart/32_Chart_read_write_HTML.php ================================================ 1)) { $inputFileNames = []; for ($i = 1; $i < $argc; ++$i) { $inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i]; } } else { $inputFileNames = glob($inputFileNames) ?: []; } foreach ($inputFileNames as $inputFileName) { $inputFileNameShort = basename($inputFileName); if (!file_exists($inputFileName)) { $helper->log('File ' . $inputFileNameShort . ' does not exist'); continue; } $helper->log("Load Test from $inputFileType file " . $inputFileNameShort); $reader = IOFactory::createReader($inputFileType); $reader->setIncludeCharts(true); $spreadsheet = $reader->load($inputFileName); $helper->log('Iterate worksheets looking at the charts'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetName = $worksheet->getTitle(); $helper->log('Worksheet: ' . $sheetName); $chartNames = $worksheet->getChartNames(); if (empty($chartNames)) { $helper->log(' There are no charts in this worksheet'); } else { natsort($chartNames); foreach ($chartNames as $i => $chartName) { $chart = $worksheet->getChartByNameOrThrow($chartName); if ($chart->getTitle() !== null) { $caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"'; } else { $caption = 'Untitled'; } $helper->log(' ' . $chartName . ' - ' . $caption); $helper->log(str_repeat(' ', strlen($chartName) + 3)); $groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount(); if ($groupCount == 1) { $chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType(); $helper->log(' ' . $chartType); } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { $chartType = 'Multiple Plot ' . array_pop($chartTypes); $helper->log(' ' . $chartType); } elseif (count($chartTypes) == 0) { $helper->log(' *** Type not yet implemented'); } else { $helper->log(' Combination Chart'); } } } } } // Save $filename = $helper->getFilename($inputFileName, 'html'); $helper->write($spreadsheet, $filename, ['Html'], true); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); } ================================================ FILE: samples/Chart/32_Chart_read_write_PDF.php ================================================ 1)) { $inputFileNames = []; for ($i = 1; $i < $argc; ++$i) { $inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i]; } } else { $inputFileNames = glob($inputFileNames) ?: []; } foreach ($inputFileNames as $inputFileName) { $inputFileNameShort = basename($inputFileName); if (!file_exists($inputFileName)) { $helper->log('File ' . $inputFileNameShort . ' does not exist'); continue; } $helper->log("Load Test from $inputFileType file " . $inputFileNameShort); $reader = IOFactory::createReader($inputFileType); $reader->setIncludeCharts(true); $spreadsheet = $reader->load($inputFileName); $helper->log('Merge chart cells (needed only for Pdf)'); $spreadsheet->mergeChartCellsForPdf(); $helper->log('Iterate worksheets looking at the charts'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetName = $worksheet->getTitle(); $helper->log('Worksheet: ' . $sheetName); $chartNames = $worksheet->getChartNames(); if (empty($chartNames)) { $helper->log(' There are no charts in this worksheet'); } else { natsort($chartNames); foreach ($chartNames as $i => $chartName) { $chart = $worksheet->getChartByNameOrThrow($chartName); if ($chart->getTitle() !== null) { $caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"'; } else { $caption = 'Untitled'; } $helper->log(' ' . $chartName . ' - ' . $caption); $helper->log(str_repeat(' ', strlen($chartName) + 3)); $groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount(); if ($groupCount == 1) { $chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType(); $helper->log(' ' . $chartType); } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { $chartType = 'Multiple Plot ' . array_pop($chartTypes); $helper->log(' ' . $chartType); } elseif (count($chartTypes) == 0) { $helper->log(' *** Type not yet implemented'); } else { $helper->log(' Combination Chart'); } } } } } // Save $filename = $helper->getFilename($inputFileName, 'pdf'); $helper->write($spreadsheet, $filename, ['Pdf'], true); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); } ================================================ FILE: samples/Chart/34_Chart_update.php ================================================ getTemporaryFilename(); $writer = new XlsxWriter($sampleSpreadsheet); $writer->setIncludeCharts(true); $writer->save($filename); $helper->log('Load from Xlsx file'); $reader = new XlsxReader(); $reader->setIncludeCharts(true); $spreadsheet = $reader->load($filename); unlink($filename); $helper->log('Update cell data values that are displayed in the chart'); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->fromArray( [ [50 - 12, 50 - 15, 50 - 21], [50 - 56, 50 - 73, 50 - 86], [50 - 52, 50 - 61, 50 - 69], [50 - 30, 50 - 32, 50], ], null, 'B2' ); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart/35_Chart_render.php ================================================ 1)) { $inputFileNames = []; for ($i = 1; $i < $argc; ++$i) { $inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i]; } } else { $inputFileNames = glob($inputFileNames) ?: []; } if (count($inputFileNames) === 1) { /** @var string[] */ $unresolvedErrors = []; } else { /** @var string[] */ $unresolvedErrors = [ // The following spreadsheet was created by 3rd party software, // and doesn't include the data that usually accompanies a chart. // That is good enough for Excel, but not for JpGraph. '32readwriteBubbleChart2.xlsx', ]; } foreach ($inputFileNames as $inputFileName) { $inputFileNameShort = basename($inputFileName); if (!file_exists($inputFileName)) { $helper->log('File ' . $inputFileNameShort . ' does not exist'); continue; } if (in_array($inputFileNameShort, $unresolvedErrors, true)) { $helper->log('*****'); $helper->log('***** File ' . $inputFileNameShort . ' does not yet work with this script'); $helper->log('*****'); continue; } $helper->log("Load Test from $inputFileType file " . $inputFileNameShort); $reader = IOFactory::createReader($inputFileType); $reader->setIncludeCharts(true); $spreadsheet = $reader->load($inputFileName); $helper->log('Iterate worksheets looking at the charts'); $renderedCharts = 0; foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetName = $worksheet->getTitle(); $helper->log('Worksheet: ' . $sheetName); $chartNames = $worksheet->getChartNames(); if (empty($chartNames)) { $helper->log(' There are no charts in this worksheet'); } else { natsort($chartNames); foreach ($chartNames as $j => $chartName) { $i = $renderedCharts + $j; $chart = $worksheet->getChartByNameOrThrow($chartName); if ($chart->getTitle() !== null) { $caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"'; } else { $caption = 'Untitled'; } $helper->log(' ' . $chartName . ' - ' . $caption); $pngFile = $helper->getFilename('35-' . $inputFileNameShort, 'png'); if ($i !== 0) { $pngFile = substr($pngFile, 0, -3) . "$i.png"; } if (file_exists($pngFile)) { unlink($pngFile); } try { $chart->render($pngFile); $helper->log('Rendered image: ' . $pngFile); } catch (Exception $e) { $helper->log('Error rendering chart: ' . $e->getMessage()); } ++$renderedCharts; } } } $spreadsheet->disconnectWorksheets(); unset($spreadsheet); gc_collect_cycles(); } $helper->log('Done rendering charts as images'); ================================================ FILE: samples/Chart/35_Chart_render33.php ================================================ getTemporaryFolder() . '/33_Chart_create_*.xlsx'; if ((isset($argc)) && ($argc > 1)) { $inputFileNames = []; for ($i = 1; $i < $argc; ++$i) { $inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i]; } } else { $inputFileNames = glob($inputFileNamesString) ?: []; } if (count($inputFileNames) === 1) { /** @var string[] */ $unresolvedErrors = []; } else { /** @var string[] */ $unresolvedErrors = [ //'33_Chart_create_bar_stacked.xlsx', // fixed with mitoteam/jpgraph 10.3 ]; } foreach ($inputFileNames as $inputFileName) { $inputFileNameShort = basename($inputFileName); if (!file_exists($inputFileName)) { $helper->log('File ' . $inputFileNameShort . ' does not exist'); continue; } if (in_array($inputFileNameShort, $unresolvedErrors, true)) { $helper->log('*****'); $helper->log('***** File ' . $inputFileNameShort . ' does not yet work with this script'); $helper->log('*****'); continue; } $helper->log("Load Test from $inputFileType file " . $inputFileNameShort); $reader = IOFactory::createReader($inputFileType); $reader->setIncludeCharts(true); $spreadsheet = $reader->load($inputFileName); $helper->log('Iterate worksheets looking at the charts'); $renderedCharts = 0; foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetName = $worksheet->getTitle(); $helper->log('Worksheet: ' . $sheetName); $chartNames = $worksheet->getChartNames(); if (empty($chartNames)) { $helper->log(' There are no charts in this worksheet'); } else { natsort($chartNames); foreach ($chartNames as $j => $chartName) { $i = $renderedCharts + $j; $chart = $worksheet->getChartByNameOrThrow($chartName); if ($chart->getTitle() !== null) { $caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"'; } else { $caption = 'Untitled'; } $helper->log(' ' . $chartName . ' - ' . $caption); $pngFile = $helper->getFilename('35-' . $inputFileNameShort, 'png'); if ($i !== 0) { $pngFile = substr($pngFile, 0, -3) . "$i.png"; } if (file_exists($pngFile)) { unlink($pngFile); } try { $chart->render($pngFile); $helper->log('Rendered image: ' . $pngFile); } catch (Exception $e) { $helper->log('Error rendering chart: ' . $e->getMessage()); } ++$renderedCharts; } } } $spreadsheet->disconnectWorksheets(); unset($spreadsheet); gc_collect_cycles(); } $helper->log('Done rendering charts as images'); ================================================ FILE: samples/Chart/37_Chart_dynamic_title.php ================================================ log('File ' . $inputFileNameShort . ' does not exist'); continue; } $reader = IOFactory::createReader($inputFileType); $reader->setIncludeCharts(true); $callStartTime = microtime(true); $spreadsheet = $reader->load($inputFileName); $helper->logRead($inputFileType, $inputFileName, $callStartTime); $helper->log('Iterate worksheets looking at the charts'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetName = $worksheet->getTitle(); $worksheet->getCell('A1')->setValue('Changed Title'); $helper->log('Worksheet: ' . $sheetName); $chartNames = $worksheet->getChartNames(); if (empty($chartNames)) { $helper->log(' There are no charts in this worksheet'); } else { natsort($chartNames); foreach ($chartNames as $i => $chartName) { $chart = $worksheet->getChartByNameOrThrow($chartName); if ($chart->getTitle() !== null) { $caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"'; } else { $caption = 'Untitled'; } $helper->log(' ' . $chartName . ' - ' . $caption); $indentation = str_repeat(' ', strlen($chartName) + 3); $groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount(); if ($groupCount == 1) { $chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType(); $helper->log($indentation . ' ' . $chartType); $helper->renderChart($chart, __FILE__, $spreadsheet); } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { $chartType = 'Multiple Plot ' . array_pop($chartTypes); $helper->log($indentation . ' ' . $chartType); $helper->renderChart($chart, __FILE__); } elseif (count($chartTypes) == 0) { $helper->log($indentation . ' *** Type not yet implemented'); } else { $helper->log($indentation . ' Combination Chart'); $helper->renderChart($chart, __FILE__); } } } } } $callStartTime = microtime(true); $helper->write($spreadsheet, $inputFileName, ['Xlsx'], true); Settings::setChartRenderer(PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class); $callStartTime = microtime(true); $helper->write($spreadsheet, $inputFileName, ['Html'], true); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); } ================================================ FILE: samples/Chart33a/33_Chart_create_area.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_AREACHART, // plotType DataSeries::GROUPING_PERCENT_STACKED, // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test %age-Stacked Area Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); $chart->setNoBorder(true); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_area_2.php ================================================ getTheme()->setThemeColorName(SpreadsheetTheme::COLOR_SCHEME_2013_2022_NAME); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_AREACHART, // plotType DataSeries::GROUPING_PERCENT_STACKED, // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test %age-Stacked Area Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_bar.php ================================================ write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_bar_custom_colors.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Custom colors for dataSeries (gray, blue, red, orange) $colors = [ 'cccccc', '00abb8', 'b8292f', 'eb8500', ]; // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Custom colors $dataSeriesValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4, [], null, $colors), ]; // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_BARCHART, // plotType null, // plotGrouping (Pie charts don't have any grouping) range(0, count($dataSeriesValues1) - 1), // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues1, // plotCategory $dataSeriesValues1 // plotValues ); // Set up a layout object for the Pie chart $layout1 = new Layout(); $layout1->setShowVal(true); $layout1->setShowPercent(true); // Set the series in the plot area $plotArea1 = new PlotArea($layout1, [$series1]); // Set the chart legend $legend1 = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title1 = new Title('Test Bar Chart'); // Create the chart $chart1 = new Chart( 'chart1', // name $title1, // title $legend1, // legend $plotArea1, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Pie charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart1); $helper->renderChart($chart1, __FILE__); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Custom colors $dataSeriesValues2 = [ $dataSeriesValues2Element = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), ]; $dataSeriesValues2Element->setFillColor($colors); // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_DONUTCHART, // plotType null, // plotGrouping (Donut charts don't have any grouping) range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels2, // plotLabel $xAxisTickValues2, // plotCategory $dataSeriesValues2 // plotValues ); // Set up a layout object for the Pie chart $layout2 = new Layout(); $layout2->setShowVal(true); $layout2->setShowCatName(true); // Set the series in the plot area $plotArea2 = new PlotArea($layout2, [$series2]); $title2 = new Title('Test Donut Chart'); // Create the chart $chart2 = new Chart( 'chart2', // name $title2, // title null, // legend $plotArea2, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Like Pie charts, Donut charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('I7'); $chart2->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart2); $helper->renderChart($chart2, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_bar_labels_lines.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Custom colors for dataSeries (gray, blue, red, orange) $colors = [ 'cccccc', '00abb8', 'b8292f', 'eb8500', ]; // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Custom colors $dataSeriesValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4, [], null, $colors), ]; $labelLayout = new Layout(); $labelLayout ->setShowVal(true) ->setLabelFontColor(new ChartColor('FFFF00')) ->setLabelFillColor(new ChartColor('accent2', null, 'schemeClr')); $dataSeriesValues1[0]->setLabelLayout($labelLayout); // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_BARCHART, // plotType null, // plotGrouping (Pie charts don't have any grouping) range(0, count($dataSeriesValues1) - 1), // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues1, // plotCategory $dataSeriesValues1 // plotValues ); // Set up a layout object for the Pie chart $layout1 = new Layout(); $layout1->setShowVal(true); $layout1->setShowPercent(true); // Set the series in the plot area $plotArea1 = new PlotArea($layout1, [$series1]); // Set the chart legend $legend1 = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title1 = new Title('Test Bar Chart'); // Create the chart $chart1 = new Chart( 'chart1', // name $title1, // title $legend1, // legend $plotArea1, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Pie charts don't have a Y-Axis ); $majorGridlinesY = new GridLines(); $majorGridlinesY->setLineColorProperties('FF0000'); $minorGridlinesY = new GridLines(); $minorGridlinesY->setLineStyleProperty('dash', Properties::LINE_STYLE_DASH_ROUND_DOT); $chart1 ->getChartAxisY() ->setMajorGridlines($majorGridlinesY) ->setMinorGridlines($minorGridlinesY); $majorGridlinesX = new GridLines(); $majorGridlinesX->setLineColorProperties('FF00FF'); $minorGridlinesX = new GridLines(); $minorGridlinesX->activateObject(); $chart1 ->getChartAxisX() ->setMajorGridlines($majorGridlinesX) ->setMinorGridlines($minorGridlinesX); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart1); $helper->renderChart($chart1, __FILE__); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Custom colors $dataSeriesValues2 = [ $dataSeriesValues2Element = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), ]; $dataSeriesValues2Element->setFillColor($colors); // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_DONUTCHART, // plotType null, // plotGrouping (Donut charts don't have any grouping) range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels2, // plotLabel $xAxisTickValues2, // plotCategory $dataSeriesValues2 // plotValues ); // Set up a layout object for the Pie chart $layout2 = new Layout(); $layout2->setShowVal(true); $layout2->setShowCatName(true); $layout2->setLabelFillColor(new ChartColor('FFFF00')); // Set the series in the plot area $plotArea2 = new PlotArea($layout2, [$series2]); $title2 = new Title('Test Donut Chart'); // Create the chart $chart2 = new Chart( 'chart2', // name $title2, // title null, // legend $plotArea2, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Like Pie charts, Donut charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('I7'); $chart2->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart2); $helper->renderChart($chart2, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_bar_stacked.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_BARCHART, // plotType DataSeries::GROUPING_STACKED, // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set additional dataseries parameters // Make it a horizontal bar rather than a vertical column graph $series->setPlotDirection(DataSeries::DIRECTION_BAR); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title = new Title('Test Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_bubble.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['Number of Products', 'Sales in USD', 'Market share'], [14, 12200, 15], [20, 60000, 33], [18, 24400, 10], [22, 32000, 42], [], [12, 8200, 18], [15, 50000, 30], [19, 22400, 15], [25, 25000, 50], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, null, null, 1, ['2013']), // 2013 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, null, null, 1, ['2014']), // 2014 ]; // Set the X-Axis values // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesCategories = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$7:$A$10', null, 4), ]; // Set the Y-Axis values // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$7:$B$10', null, 4), ]; // Set the Z-Axis values (bubble size) // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesBubbles = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$7:$C$10', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_BUBBLECHART, // plotType null, // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $dataSeriesCategories, // plotCategory $dataSeriesValues // plotValues ); $series->setPlotBubbleSizes($dataSeriesBubbles); // Set the series in the plot area $plotArea = new PlotArea(); $plotArea->setPlotSeries([$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); // Create the chart $chart = new Chart( 'chart1', // name null, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('E1'); $chart->setBottomRightPosition('M15'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); $worksheet->getColumnDimension('A')->setAutoSize(true); $worksheet->getColumnDimension('B')->setAutoSize(true); $worksheet->getColumnDimension('C')->setAutoSize(true); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_column.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_BARCHART, // plotType DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set additional dataseries parameters // Make it a vertical column rather than a horizontal bar graph $series->setPlotDirection(DataSeries::DIRECTION_COL); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title = new Title('Test Column Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_column_2.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', '', 'Budget', 'Forecast', 'Actual'], ['2010', 'Q1', 47, 44, 43], ['', 'Q2', 56, 53, 50], ['', 'Q3', 52, 46, 45], ['', 'Q4', 45, 40, 40], ['2011', 'Q1', 51, 42, 46], ['', 'Q2', 53, 58, 56], ['', 'Q3', 64, 66, 69], ['', 'Q4', 54, 55, 56], ['2012', 'Q1', 49, 52, 58], ['', 'Q2', 68, 73, 86], ['', 'Q3', 72, 78, 0], ['', 'Q4', 50, 60, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 'Budget' new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 'Forecast' new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$E$1', null, 1), // 'Actual' ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$B$13', null, 12), // Q1 to Q4 for 2010 to 2012 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$13', null, 12), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$13', null, 12), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$E$2:$E$13', null, 12), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_BARCHART, // plotType DataSeries::GROUPING_CLUSTERED, // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set additional dataseries parameters // Make it a vertical column rather than a horizontal bar graph $series->setPlotDirection(DataSeries::DIRECTION_COL); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_BOTTOM, null, false); $title = new Title('Test Grouped Column Chart'); $xAxisLabel = new Title('Financial Period'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs $xAxisLabel, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('G2'); $chart->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_composite.alternate.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 'Rainfall (mm)', 'Temperature (°F)', 'Humidity (%)'], ['Jan', 78, 52, 61], ['Feb', 64, 54, 62], ['Mar', 62, 57, 63], ['Apr', 21, 62, 59], ['May', 11, 75, 60], ['Jun', 1, 75, 57], ['Jul', 1, 79, 56], ['Aug', 1, 79, 59], ['Sep', 10, 75, 60], ['Oct', 40, 68, 63], ['Nov', 69, 62, 64], ['Dec', 89, 57, 66], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // Temperature ]; $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // Rainfall ]; $dataSeriesLabels3 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // Humidity ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$13', null, 12), // Jan to Dec ]; $order = 0; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues1 = [ $order => new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$13', null, 12), ]; // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_BARCHART, // plotType DataSeries::GROUPING_CLUSTERED, // plotGrouping [$order => $order], // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues1 // plotValues ); // Set additional dataseries parameters // Make it a vertical column rather than a horizontal bar graph $series1->setPlotDirection(DataSeries::DIRECTION_COL); $order = 1; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues2 = [ $order => new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$13', null, 12), ]; // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_LINECHART, // plotType DataSeries::GROUPING_STANDARD, // plotGrouping [$order => $order], // plotOrder $dataSeriesLabels2, // plotLabel [], // plotCategory $dataSeriesValues2 // plotValues ); $order = 2; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues3 = [ $order => new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$13', null, 12), ]; // Build the dataseries $series3 = new DataSeries( DataSeries::TYPE_AREACHART, // plotType DataSeries::GROUPING_STANDARD, // plotGrouping [$order => $order], // plotOrder $dataSeriesLabels3, // plotLabel [], // plotCategory $dataSeriesValues3 // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series1, $series2, $series3]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title = new Title('Average Weather Chart for Crete'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('F2'); $chart->setBottomRightPosition('O16'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_composite.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 'Rainfall (mm)', 'Temperature (°F)', 'Humidity (%)'], ['Jan', 78, 52, 61], ['Feb', 64, 54, 62], ['Mar', 62, 57, 63], ['Apr', 21, 62, 59], ['May', 11, 75, 60], ['Jun', 1, 75, 57], ['Jul', 1, 79, 56], ['Aug', 1, 79, 59], ['Sep', 10, 75, 60], ['Oct', 40, 68, 63], ['Nov', 69, 62, 64], ['Dec', 89, 57, 66], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // Temperature ]; $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // Rainfall ]; $dataSeriesLabels3 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // Humidity ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$13', null, 12), // Jan to Dec ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$13', null, 12), ]; // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_BARCHART, // plotType DataSeries::GROUPING_CLUSTERED, // plotGrouping range(0, count($dataSeriesValues1) - 1), // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues1 // plotValues ); // Set additional dataseries parameters // Make it a vertical column rather than a horizontal bar graph $series1->setPlotDirection(DataSeries::DIRECTION_COL); // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$13', null, 12), ]; // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_LINECHART, // plotType DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels2, // plotLabel [], // plotCategory $dataSeriesValues2 // plotValues ); // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues3 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$13', null, 12), ]; // Build the dataseries $series3 = new DataSeries( DataSeries::TYPE_AREACHART, // plotType DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels3, // plotLabel [], // plotCategory $dataSeriesValues3 // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series1, $series2, $series3]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title = new Title('Average Weather Chart for Crete'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('F2'); $chart->setBottomRightPosition('O16'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_line.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; $dataSeriesLabels[0]->setFillColor('FF0000'); // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; $dataSeriesValues[2]->setLineWidth(60000 / Properties::POINTS_WIDTH_MULTIPLIER); // Build the dataseries $series = new DataSeries( DataSeries::TYPE_LINECHART, // plotType null, // plotGrouping, was DataSeries::GROUPING_STACKED, not a usual choice for line chart range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Line Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33a/33_Chart_create_line_dateaxis.php ================================================ getActiveSheet(); $dataSheet->setTitle('Data'); // changed data to simulate a trend chart - Xaxis are dates; Yaxis are 3 meausurements from each date // Dates changed not to fall on exact quarter start $dataSheet->fromArray( [ ['', 'date', 'metric1', 'metric2', 'metric3'], ['=DATEVALUE(B2)', '2021-01-10', 12.1, 15.1, 21.1], ['=DATEVALUE(B3)', '2021-04-21', 56.2, 73.2, 86.2], ['=DATEVALUE(B4)', '2021-07-31', 52.2, 61.2, 69.2], ['=DATEVALUE(B5)', '2021-10-11', 30.2, 22.2, 0.2], ['=DATEVALUE(B6)', '2022-01-21', 40.1, 38.1, 65.1], ['=DATEVALUE(B7)', '2022-04-11', 45.2, 44.2, 96.2], ['=DATEVALUE(B8)', '2022-07-01', 52.2, 51.2, 55.2], ['=DATEVALUE(B9)', '2022-10-31', 41.2, 72.2, 56.2], ] ); $dataSheet->getStyle('A2:A9')->getNumberFormat()->setFormatCode(Properties::FORMAT_CODE_DATE_ISO8601); $dataSheet->getColumnDimension('A')->setAutoSize(true); $dataSheet->getColumnDimension('B')->setAutoSize(true); $dataSheet->setSelectedCells('A1'); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$C$1', null, 1), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$D$1', null, 1), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$E$1', null, 1), ]; // Set the X-Axis Labels // NUMBER, not STRING // added x-axis values for each of the 3 metrics // added FORMATE_CODE_NUMBER // Number of datapoints in series $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Data Marker Color fill/[fill,Border] // Data Marker size // Color(s) added // added FORMAT_CODE_NUMBER $dataSeriesValues = [ new DataSeriesValues( DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$C$2:$C$9', Properties::FORMAT_CODE_NUMBER, 8, null, 'diamond', null, 5 ), new DataSeriesValues( DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$D$2:$D$9', Properties::FORMAT_CODE_NUMBER, 8, null, 'square', '*accent1', 6 ), new DataSeriesValues( DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$E$2:$E$9', Properties::FORMAT_CODE_NUMBER, 8, null, null, null, 7 ), // let Excel choose marker shape ]; // series 1 - metric1 // marker details $dataSeriesValues[0] ->getMarkerFillColor() ->setColorProperties('0070C0', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[0] ->getMarkerBorderColor() ->setColorProperties('002060', null, ChartColor::EXCEL_COLOR_TYPE_RGB); // line details - dashed, smooth line (Bezier) with arrows, 40% transparent $dataSeriesValues[0] ->setSmoothLine(true) ->setScatterLines(true) ->setLineColorProperties('accent1', 40, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // value, alpha, type $dataSeriesValues[0]->setLineStyleProperties( 2.5, // width in points Properties::LINE_STYLE_COMPOUND_TRIPLE, // compound Properties::LINE_STYLE_DASH_SQUARE_DOT, // dash Properties::LINE_STYLE_CAP_SQUARE, // cap Properties::LINE_STYLE_JOIN_MITER, // join Properties::LINE_STYLE_ARROW_TYPE_OPEN, // head type Properties::LINE_STYLE_ARROW_SIZE_4, // head size preset index Properties::LINE_STYLE_ARROW_TYPE_ARROW, // end type Properties::LINE_STYLE_ARROW_SIZE_6 // end size preset index ); // series 2 - metric2, straight line - no special effects, connected $dataSeriesValues[1] // square marker border color ->getMarkerBorderColor() ->setColorProperties('accent6', 3, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[1] // square marker fill color ->getMarkerFillColor() ->setColorProperties('0FFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1] ->setScatterLines(true) ->setSmoothLine(false) ->setLineColorProperties('FF0000', 80, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1]->setLineWidth(2.0); // series 3 - metric3, markers, no line $dataSeriesValues[2] // triangle? fill //->setPointMarker('triangle') // let Excel choose shape, which is predicted to be a triangle ->getMarkerFillColor() ->setColorProperties('FFFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[2] // triangle border ->getMarkerBorderColor() ->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[2]->setScatterLines(false); // points not connected // Added so that Xaxis shows dates instead of Excel-equivalent-year1900-numbers $xAxis = new Axis(); $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601); // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_SMOOTHMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Chart'); $yAxisLabel = new Title('Value ($k)'); $yAxis = new Axis(); $yAxis->setMajorGridlines(new GridLines()); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis $yAxis, // yAxis ); // Set the position of the chart in the chart sheet $chart->setTopLeftPosition('A1'); $chart->setBottomRightPosition('P12'); // create a 'Chart' worksheet, add $chart to it $spreadsheet->createSheet(); $chartSheet = $spreadsheet->getSheet(1); $chartSheet->setTitle('Scatter+Line Chart'); $chartSheet = $spreadsheet->getSheetByNameOrThrow('Scatter+Line Chart'); // Add the chart to the worksheet $chartSheet->addChart($chart); // ------- Demonstrate Date Xaxis in Line Chart, not possible using Scatter Chart ------------ // Set the Labels (Column header) for each data series we want to plot $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$E$1', null, 1), ]; // Set the X-Axis Labels - dates, N.B. 01/10/2021 === Jan 10, NOT Oct 1 !! // x-axis values are the Excel numeric representation of the date - so set // formatCode=General for the xAxis VALUES, but we want the labels to be // DISPLAYED as 'yyyy-mm-dd' That is, read a number, display a date. $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), ]; // X axis (date) settings $xAxisLabel = new Title('Date'); $xAxis = new Axis(); $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601); // yyyy-mm-dd // Set the Data values for each data series we want to plot $dataSeriesValues = [ new DataSeriesValues( DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$E$2:$E$9', Properties::FORMAT_CODE_NUMBER, 8, null, 'triangle', null, 7 ), ]; // series - metric3, markers, no line $dataSeriesValues[0] ->setScatterlines(false); // disable connecting lines $dataSeriesValues[0] ->getMarkerFillColor() ->setColorProperties('FFFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[0] ->getMarkerBorderColor() ->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // Build the dataseries // must now use LineChart instead of ScatterChart, since ScatterChart does not // support "dateAx" axis type. $series = new DataSeries( DataSeries::TYPE_LINECHART, // plotType 'standard', // plotGrouping range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_LINEMARKER // plotStyle // DataSeries::STYLE_SMOOTHMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title = new Title('Test Line-Chart with Date Axis - metric3 values'); // X axis (date) settings $xAxisLabel = new Title('Game Date'); $xAxis = new Axis(); // date axis values are Excel numbers, not yyyy-mm-dd Date strings $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601); $xAxis->setAxisType('dateAx'); // dateAx available ONLY for LINECHART, not SCATTERCHART // measure the time span in Quarters, of data. $dateMinMax = dateRange(8, $spreadsheet); // array 'min'=>earliest date of first Q, 'max'=>latest date of final Q // change xAxis tick marks to match Qtr boundaries $nQtrs = sprintf('%3.2f', (($dateMinMax['max'] - $dateMinMax['min']) / 30.5) / 4); $tickMarkInterval = ($nQtrs > 20) ? '6' : '3'; // tick marks every ? months $xAxis->setAxisOptionsProperties( Properties::AXIS_LABELS_NEXT_TO, // axis_label pos null, // horizontalCrossesValue null, // horizontalCrosses null, // axisOrientation 'in', // major_tick_mark null, // minor_tick_mark $dateMinMax['min'], // minimum calculate this from the earliest data: 'Data!$A$2' $dateMinMax['max'], // maximum calculate this from the last data: 'Data!$A$'.($nrows+1) $tickMarkInterval, // majorUnit determines tickmarks & Gridlines ? null, // minorUnit null, // textRotation null, // hidden 'days', // baseTimeUnit 'months', // majorTimeUnit, 'months', // minorTimeUnit ); $yAxisLabel = new Title('Value ($k)'); $yAxis = new Axis(); $yAxis->setMajorGridlines(new GridLines()); $xAxis->setMajorGridlines(new GridLines()); $minorGridLines = new GridLines(); $minorGridLines->activateObject(); $xAxis->setMinorGridlines($minorGridLines); // Create the chart $chart = new Chart( 'chart2', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis $yAxis, // yAxis ); // Set the position of the chart in the chart sheet below the first chart $chart->setTopLeftPosition('A13'); $chart->setBottomRightPosition('P25'); $chart->setRoundedCorners(true); // Rounded corners in Chart Outline // Add the chart to the worksheet $chartSheet $chartSheet->addChart($chart); $helper->renderChart($chart, __FILE__); $spreadsheet->setActiveSheetIndex(1); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true, resetActiveSheet: false); $spreadsheet->disconnectWorksheets(); /** @return array{'min': float|int, 'max': float|int} */ function dateRange(int $nrows, Spreadsheet $wrkbk): array { $dataSheet = $wrkbk->getSheetByNameOrThrow('Data'); // start the xaxis at the beginning of the quarter of the first date /** @var string */ $startDateStr = $dataSheet->getCell('B2')->getValue(); // yyyy-mm-dd date string $startDate = DateTime::createFromFormat('Y-m-d', $startDateStr); // php date obj if ($startDate === false) { throw new Exception("invalid start date $startDateStr on spreadsheet"); } // get date of first day of the quarter of the start date $startMonth = (int) $startDate->format('n'); // suppress leading zero $startYr = (int) $startDate->format('Y'); $qtr = intdiv($startMonth, 3) + (($startMonth % 3 > 0) ? 1 : 0); $qtrStartMonth = sprintf('%02d', 1 + (($qtr - 1) * 3)); $qtrStartStr = "$startYr-$qtrStartMonth-01"; $ExcelQtrStartDateVal = SharedDate::convertIsoDate($qtrStartStr); // end the xaxis at the end of the quarter of the last date /** @var string */ $lastDateStr = $dataSheet->getCell([2, $nrows + 1])->getValue(); $lastDate = DateTime::createFromFormat('Y-m-d', $lastDateStr); if ($lastDate === false) { throw new Exception("invalid last date $lastDateStr on spreadsheet"); } $lastMonth = (int) $lastDate->format('n'); $lastYr = (int) $lastDate->format('Y'); $qtr = intdiv($lastMonth, 3) + (($lastMonth % 3 > 0) ? 1 : 0); $qtrEndMonth = 3 + (($qtr - 1) * 3); $qtrEndMonth = sprintf('%02d', $qtrEndMonth); $lastDOMDate = DateTime::createFromFormat('Y-m-d', "$lastYr-$qtrEndMonth-01"); if ($lastDOMDate === false) { throw new Exception("invalid last dom date $lastYr-$qtrEndMonth-01 on spreadsheet"); } $lastDOM = $lastDOMDate->format('t'); $qtrEndStr = "$lastYr-$qtrEndMonth-$lastDOM"; $ExcelQtrEndDateVal = SharedDate::convertIsoDate($qtrEndStr); $minMaxDates = ['min' => $ExcelQtrStartDateVal, 'max' => $ExcelQtrEndDateVal]; return $minMaxDates; } ================================================ FILE: samples/Chart33b/33_Chart_create_multiple_charts.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_AREACHART, // plotType DataSeries::GROUPING_PERCENT_STACKED, // plotGrouping range(0, count($dataSeriesValues1) - 1), // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues1, // plotCategory $dataSeriesValues1 // plotValues ); // Set the series in the plot area $plotArea1 = new PlotArea(null, [$series1]); // Set the chart legend $legend1 = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title1 = new Title('Test %age-Stacked Area Chart'); $yAxisLabel1 = new Title('Value ($k)'); // Create the chart $chart1 = new Chart( 'chart1', // name $title1, // title $legend1, // legend $plotArea1, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel1 // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart1); $helper->renderChart($chart1, __FILE__); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_BARCHART, // plotType DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels2, // plotLabel $xAxisTickValues2, // plotCategory $dataSeriesValues2 // plotValues ); // Set additional dataseries parameters // Make it a vertical column rather than a horizontal bar graph $series2->setPlotDirection(DataSeries::DIRECTION_COL); // Set the series in the plot area $plotArea2 = new PlotArea(null, [$series2]); // Set the chart legend $legend2 = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title2 = new Title('Test Column Chart'); $yAxisLabel2 = new Title('Value ($k)'); // Create the chart $chart2 = new Chart( 'chart2', // name $title2, // title $legend2, // legend $plotArea2, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel2 // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('I7'); $chart2->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart2); $helper->renderChart($chart2, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_pie.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), ]; // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_PIECHART, // plotType null, // plotGrouping (Pie charts don't have any grouping) range(0, count($dataSeriesValues1) - 1), // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues1, // plotCategory $dataSeriesValues1 // plotValues ); // Set up a layout object for the Pie chart $layout1 = new Layout(); $layout1->setShowVal(true); $layout1->setShowPercent(true); // Set the series in the plot area $plotArea1 = new PlotArea($layout1, [$series1]); // Set the chart legend $legend1 = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title1 = new Title('Test Pie Chart'); // Create the chart $chart1 = new Chart( 'chart1', // name $title1, // title $legend1, // legend $plotArea1, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Pie charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart1); $helper->renderChart($chart1, __FILE__); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), ]; // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_DONUTCHART, // plotType null, // plotGrouping (Donut charts don't have any grouping) range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels2, // plotLabel $xAxisTickValues2, // plotCategory $dataSeriesValues2 // plotValues ); // Set up a layout object for the Pie chart $layout2 = new Layout(); $layout2->setShowVal(true); $layout2->setShowCatName(true); // Set the series in the plot area $plotArea2 = new PlotArea($layout2, [$series2]); $title2 = new Title('Test Donut Chart'); // Create the chart $chart2 = new Chart( 'chart2', // name $title2, // title null, // legend $plotArea2, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Like Pie charts, Donut charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('I7'); $chart2->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart2); $helper->renderChart($chart2, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_pie_custom_colors.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Custom colors for dataSeries (gray, blue, red, orange) $colors = [ 'cccccc', '00abb8', 'b8292f', 'eb8500', ]; // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Custom colors $dataSeriesValues1 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4, [], null, $colors), ]; // Build the dataseries $series1 = new DataSeries( DataSeries::TYPE_PIECHART, // plotType null, // plotGrouping (Pie charts don't have any grouping) range(0, count($dataSeriesValues1) - 1), // plotOrder $dataSeriesLabels1, // plotLabel $xAxisTickValues1, // plotCategory $dataSeriesValues1 // plotValues ); // Set up a layout object for the Pie chart $layout1 = new Layout(); $layout1->setShowVal(true); $layout1->setShowPercent(true); // Set the series in the plot area $plotArea1 = new PlotArea($layout1, [$series1]); // Set the chart legend $legend1 = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title1 = new Title('Test Pie Chart'); // Create the chart $chart1 = new Chart( 'chart1', // name $title1, // title $legend1, // legend $plotArea1, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Pie charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart1); $helper->renderChart($chart1, __FILE__); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues2 = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Custom colors $dataSeriesValues2 = [ $dataSeriesValues2Element = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), ]; $dataSeriesValues2Element->setFillColor($colors); // Build the dataseries $series2 = new DataSeries( DataSeries::TYPE_DONUTCHART, // plotType null, // plotGrouping (Donut charts don't have any grouping) range(0, count($dataSeriesValues2) - 1), // plotOrder $dataSeriesLabels2, // plotLabel $xAxisTickValues2, // plotCategory $dataSeriesValues2 // plotValues ); // Set up a layout object for the Pie chart $layout2 = new Layout(); $layout2->setShowVal(true); $layout2->setShowCatName(true); // Set the series in the plot area $plotArea2 = new PlotArea($layout2, [$series2]); $title2 = new Title('Test Donut Chart'); // Create the chart $chart2 = new Chart( 'chart2', // name $title2, // title null, // legend $plotArea2, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Like Pie charts, Donut charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('I7'); $chart2->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart2); $helper->renderChart($chart2, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_radar.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Jan', 47, 45, 71], ['Feb', 56, 73, 86], ['Mar', 52, 61, 69], ['Apr', 40, 52, 60], ['May', 42, 55, 71], ['Jun', 58, 63, 76], ['Jul', 53, 61, 89], ['Aug', 46, 69, 85], ['Sep', 62, 75, 81], ['Oct', 51, 70, 96], ['Nov', 55, 66, 89], ['Dec', 68, 62, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$13', null, 12), // Jan to Dec new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$13', null, 12), // Jan to Dec ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$13', null, 12), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$13', null, 12), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_RADARCHART, // plotType null, // plotGrouping (Radar charts don't have any grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_MARKER // plotStyle ); // Set up a layout object for the Pie chart $layout = new Layout(); // Set the series in the plot area $plotArea = new PlotArea($layout, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $title = new Title('Test Radar Chart'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null // yAxisLabel - Radar charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('F2'); $chart->setBottomRightPosition('M15'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have any grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_LINEMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter2.php ================================================ getActiveSheet(); // changed data to simulate a trend chart - Xaxis are dates; Yaxis are 3 meausurements from each date $worksheet->fromArray( [ ['', 'metric1', 'metric2', 'metric3'], ['=DATEVALUE("2021-01-01")', 12.1, 15.1, 21.1], ['=DATEVALUE("2021-01-04")', 56.2, 73.2, 86.2], ['=DATEVALUE("2021-01-07")', 52.2, 61.2, 69.2], ['=DATEVALUE("2021-01-10")', 30.2, 32.2, 0.2], ] ); $worksheet->getStyle('A2:A5')->getNumberFormat()->setFormatCode(Properties::FORMAT_CODE_DATE_ISO8601); $worksheet->getColumnDimension('A')->setAutoSize(true); $worksheet->setSelectedCells('A1'); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // was 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // was 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // was 2012 ]; // Set the X-Axis Labels // changed from STRING to NUMBER // added 2 additional x-axis values associated with each of the 3 metrics // added FORMATE_CODE_NUMBER $xAxisTickValues = [ //new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', Properties::FORMAT_CODE_DATE, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', Properties::FORMAT_CODE_DATE, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', Properties::FORMAT_CODE_DATE, 4), ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // added FORMAT_CODE_NUMBER $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', Properties::FORMAT_CODE_NUMBER, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', Properties::FORMAT_CODE_NUMBER, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', Properties::FORMAT_CODE_NUMBER, 4), ]; // series 1 // marker details $dataSeriesValues[0] ->setPointMarker('diamond') ->setPointSize(5) ->getMarkerFillColor() ->setColorProperties('0070C0', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[0] ->getMarkerBorderColor() ->setColorProperties('002060', null, ChartColor::EXCEL_COLOR_TYPE_RGB); // line details - smooth line, connected $dataSeriesValues[0] ->setScatterLines(true) ->setSmoothLine(true) ->setLineColorProperties('accent1', 40, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // value, alpha, type $dataSeriesValues[0]->setLineStyleProperties( 2.5, // width in points Properties::LINE_STYLE_COMPOUND_TRIPLE, // compound Properties::LINE_STYLE_DASH_SQUARE_DOT, // dash Properties::LINE_STYLE_CAP_SQUARE, // cap Properties::LINE_STYLE_JOIN_MITER, // join Properties::LINE_STYLE_ARROW_TYPE_OPEN, // head type Properties::LINE_STYLE_ARROW_SIZE_4, // head size preset index Properties::LINE_STYLE_ARROW_TYPE_ARROW, // end type Properties::LINE_STYLE_ARROW_SIZE_6 // end size preset index ); // series 2 - straight line - no special effects, connected, straight line $dataSeriesValues[1] // square fill ->setPointMarker('square') ->setPointSize(6) ->getMarkerBorderColor() ->setColorProperties('accent6', 3, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[1] // square border ->getMarkerFillColor() ->setColorProperties('0FFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1] ->setScatterLines(true) ->setSmoothLine(false) ->setLineColorProperties('FF0000', 80, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1]->setLineWidth(2.0); // series 3 - markers, no line $dataSeriesValues[2] // triangle fill //->setPointMarker('triangle') // let Excel choose shape ->setPointSize(7) ->getMarkerFillColor() ->setColorProperties('FFFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[2] // triangle border ->getMarkerBorderColor() ->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[2]->setScatterLines(false); // points not connected // Added so that Xaxis shows dates instead of Excel-equivalent-year1900-numbers $xAxis = new ChartAxis(); //$xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE ); $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601, true); //$xAxis->setAxisOption('textRotation', '45'); $xAxisText = new AxisText(); $xAxisText->setRotation(45)->getFillColorObject()->setValue('00FF00')->setType(ChartColor::EXCEL_COLOR_TYPE_RGB); $xAxis->setAxisText($xAxisText); $yAxis = new ChartAxis(); $yAxis->setLineStyleProperties( 2.5, // width in points Properties::LINE_STYLE_COMPOUND_SIMPLE, Properties::LINE_STYLE_DASH_DASH_DOT, Properties::LINE_STYLE_CAP_FLAT, Properties::LINE_STYLE_JOIN_BEVEL ); $yAxis->setLineColorProperties('ffc000', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $yAxisText = new AxisText(); $yAxisText->setGlowProperties(20.0, 'accent1', 20, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $yAxis->setAxisText($yAxisText); // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have any grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_SMOOTHMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Trend Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis $yAxis, // yAxis ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter3.php ================================================ getActiveSheet(); // changed data to simulate a trend chart - Xaxis are dates; Yaxis are 3 meausurements from each date $worksheet->fromArray( [ ['', 'metric1', 'metric2', 'metric3'], ['=DATEVALUE("2021-01-01")', 12.1, 15.1, 21.1], ['=DATEVALUE("2021-01-04")', 56.2, 73.2, 86.2], ['=DATEVALUE("2021-01-07")', 52.2, 61.2, 69.2], ['=DATEVALUE("2021-01-10")', 30.2, 32.2, 0.2], ] ); $worksheet->getStyle('A2:A5')->getNumberFormat()->setFormatCode(Properties::FORMAT_CODE_DATE_ISO8601); $worksheet->getColumnDimension('A')->setAutoSize(true); $worksheet->setSelectedCells('A1'); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // was 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // was 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // was 2012 ]; // Set the X-Axis Labels // changed from STRING to NUMBER // added 2 additional x-axis values associated with each of the 3 metrics // added FORMATE_CODE_NUMBER $xAxisTickValues = [ //new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', Properties::FORMAT_CODE_DATE, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', Properties::FORMAT_CODE_DATE, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', Properties::FORMAT_CODE_DATE, 4), ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // added FORMAT_CODE_NUMBER $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', Properties::FORMAT_CODE_NUMBER, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', Properties::FORMAT_CODE_NUMBER, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', Properties::FORMAT_CODE_NUMBER, 4), ]; // series 1 // marker details $dataSeriesValues[0] ->setPointMarker('diamond') ->setPointSize(5) ->getMarkerFillColor() ->setColorProperties('0070C0', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[0] ->getMarkerBorderColor() ->setColorProperties('002060', null, ChartColor::EXCEL_COLOR_TYPE_RGB); // line details - smooth line, connected $dataSeriesValues[0] ->setScatterLines(true) ->setSmoothLine(true) ->setLineColorProperties('accent1', 40, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // value, alpha, type $dataSeriesValues[0]->setLineStyleProperties( 2.5, // width in points Properties::LINE_STYLE_COMPOUND_TRIPLE, // compound Properties::LINE_STYLE_DASH_SQUARE_DOT, // dash Properties::LINE_STYLE_CAP_SQUARE, // cap Properties::LINE_STYLE_JOIN_MITER, // join Properties::LINE_STYLE_ARROW_TYPE_OPEN, // head type Properties::LINE_STYLE_ARROW_SIZE_4, // head size preset index Properties::LINE_STYLE_ARROW_TYPE_ARROW, // end type Properties::LINE_STYLE_ARROW_SIZE_6 // end size preset index ); // series 2 - straight line - no special effects, connected, straight line $dataSeriesValues[1] // square fill ->setPointMarker('square') ->setPointSize(6) ->getMarkerBorderColor() ->setColorProperties('accent6', 3, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[1] // square border ->getMarkerFillColor() ->setColorProperties('0FFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1] ->setScatterLines(true) ->setSmoothLine(false) ->setLineColorProperties('FF0000', 80, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1]->setLineWidth(2.0); // series 3 - markers, no line $dataSeriesValues[2] // triangle fill //->setPointMarker('triangle') // let Excel choose shape ->setPointSize(7) ->getMarkerFillColor() ->setColorProperties('FFFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[2] // triangle border ->getMarkerBorderColor() ->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[2]->setScatterLines(false); // points not connected // Added so that Xaxis shows dates instead of Excel-equivalent-year1900-numbers $xAxis = new ChartAxis(); //$xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE ); $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601, true); $xAxis->setAxisOption('textRotation', '45'); $xAxis->setAxisOption('hidden', '1'); $yAxis = new ChartAxis(); $yAxis->setLineStyleProperties( 2.5, // width in points Properties::LINE_STYLE_COMPOUND_SIMPLE, Properties::LINE_STYLE_DASH_DASH_DOT, Properties::LINE_STYLE_CAP_FLAT, Properties::LINE_STYLE_JOIN_BEVEL ); $yAxis->setLineColorProperties('ffc000', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $yAxis->setAxisOption('hidden', '1'); // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have any grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_SMOOTHMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); $plotArea->setNoFill(true); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Trend Chart'); //$yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null, //$yAxisLabel, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis $yAxis, // yAxis ); $chart->setNoFill(true); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('P20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter4.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ] ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have any grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_LINEMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); $pos1 = 0; // pos = 0% (extreme low side or lower left corner) $brightness1 = 0; // 0% $gsColor1 = new ChartColor(); $gsColor1->setColorProperties('FF0000', 75, 'srgbClr', $brightness1); // red $gradientStop1 = [$pos1, $gsColor1]; $pos2 = 0.5; // pos = 50% (middle) $brightness2 = 0.5; // 50% $gsColor2 = new ChartColor(); $gsColor2->setColorProperties('FFFF00', 50, 'srgbClr', $brightness2); // yellow $gradientStop2 = [$pos2, $gsColor2]; $pos3 = 1.0; // pos = 100% (extreme high side or upper right corner) $brightness3 = 0.5; // 50% $gsColor3 = new ChartColor(); $gsColor3->setColorProperties('00B050', 50, 'srgbClr', $brightness3); // green $gradientStop3 = [$pos3, $gsColor3]; $gradientFillStops = [ $gradientStop1, $gradientStop2, $gradientStop3, ]; $gradientFillAngle = 315.0; // 45deg above horiz $plotArea->setGradientFillProperties($gradientFillStops, $gradientFillAngle); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter5_trendlines.php ================================================ getActiveSheet(); $dataSheet->setTitle('Data'); // changed data to simulate a trend chart - Xaxis are dates; Yaxis are 3 meausurements from each date $dataSheet->fromArray( [ ['', 'metric1', 'metric2', 'metric3'], ['=DATEVALUE("2021-01-01")', 12.1, 15.1, 21.1], ['=DATEVALUE("2021-04-01")', 56.2, 73.2, 86.2], ['=DATEVALUE("2021-07-01")', 52.2, 61.2, 69.2], ['=DATEVALUE("2021-10-01")', 30.2, 22.2, 0.2], ['=DATEVALUE("2022-01-01")', 40.1, 38.1, 65.1], ['=DATEVALUE("2022-04-01")', 45.2, 44.2, 96.2], ['=DATEVALUE("2022-07-01")', 52.2, 51.2, 55.2], ['=DATEVALUE("2022-10-01")', 41.2, 72.2, 56.2], ] ); $dataSheet->getStyle('A2:A9')->getNumberFormat()->setFormatCode(Properties::FORMAT_CODE_DATE_ISO8601); $dataSheet->getColumnDimension('A')->setAutoSize(true); $dataSheet->setSelectedCells('A1'); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$B$1', null, 1), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$C$1', null, 1), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$D$1', null, 1), ]; // Set the X-Axis Labels // NUMBER, not STRING // added x-axis values for each of the 3 metrics // added FORMATE_CODE_NUMBER // Number of datapoints in series $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker // Data Marker Color fill/[fill,Border] // Data Marker size // Color(s) added // added FORMAT_CODE_NUMBER $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$B$2:$B$9', Properties::FORMAT_CODE_NUMBER, 8, null, 'diamond', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$C$2:$C$9', Properties::FORMAT_CODE_NUMBER, 8, null, 'square', '*accent1', 6), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$D$2:$D$9', Properties::FORMAT_CODE_NUMBER, 8, null, null, null, 7), // let Excel choose marker shape ]; // series 1 - metric1 // marker details $dataSeriesValues[0] ->getMarkerFillColor() ->setColorProperties('0070C0', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[0] ->getMarkerBorderColor() ->setColorProperties('002060', null, ChartColor::EXCEL_COLOR_TYPE_RGB); // line details - dashed, smooth line (Bezier) with arrows, 40% transparent $dataSeriesValues[0] ->setSmoothLine(true) ->setScatterLines(true) ->setLineColorProperties('accent1', 40, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // value, alpha, type $dataSeriesValues[0]->setLineStyleProperties( 2.5, // width in points Properties::LINE_STYLE_COMPOUND_TRIPLE, // compound Properties::LINE_STYLE_DASH_SQUARE_DOT, // dash Properties::LINE_STYLE_CAP_SQUARE, // cap Properties::LINE_STYLE_JOIN_MITER, // join Properties::LINE_STYLE_ARROW_TYPE_OPEN, // head type Properties::LINE_STYLE_ARROW_SIZE_4, // head size preset index Properties::LINE_STYLE_ARROW_TYPE_ARROW, // end type Properties::LINE_STYLE_ARROW_SIZE_6 // end size preset index ); // series 2 - metric2, straight line - no special effects, connected $dataSeriesValues[1] // square marker border color ->getMarkerBorderColor() ->setColorProperties('accent6', 3, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[1] // square marker fill color ->getMarkerFillColor() ->setColorProperties('0FFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1] ->setScatterLines(true) ->setSmoothLine(false) ->setLineColorProperties('FF0000', 80, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[1]->setLineWidth(2.0); // series 3 - metric3, markers, no line $dataSeriesValues[2] // triangle? fill //->setPointMarker('triangle') // let Excel choose shape, which is predicted to be a triangle ->getMarkerFillColor() ->setColorProperties('FFFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[2] // triangle border ->getMarkerBorderColor() ->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[2]->setScatterLines(false); // points not connected // Added so that Xaxis shows dates instead of Excel-equivalent-year1900-numbers $xAxis = new ChartAxis(); $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601, true); // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_SMOOTHMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Chart'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart1', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis // $yAxis, // yAxis ); // Set the position of the chart in the chart sheet $chart->setTopLeftPosition('A1'); $chart->setBottomRightPosition('P12'); // create a 'Chart' worksheet, add $chart to it $spreadsheet->createSheet(); $chartSheet = $spreadsheet->getSheet(1); $chartSheet->setTitle('Scatter Chart'); $chartSheet = $spreadsheet->getSheetByNameOrThrow('Scatter Chart'); // Add the chart to the worksheet $chartSheet->addChart($chart); /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->renderChart($chart, __FILE__); // ------------ Demonstrate Trendlines for metric3 values in a new chart ------------ $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$D$1', null, 1), ]; $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$9', Properties::FORMAT_CODE_DATE_ISO8601, 8), ]; $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$D$2:$D$9', Properties::FORMAT_CODE_NUMBER, 4, null, 'triangle', null, 7), ]; // add 3 trendlines: // 1- linear, double-ended arrow, w=0.5, same color as marker fill; nodispRSqr, nodispEq // 2- polynomial (order=3) no-arrow trendline, w=1.25, same color as marker fill; dispRSqr, dispEq // 3- moving Avg (period=2) single-arrow trendline, w=1.5, same color as marker fill; no dispRSqr, no dispEq $trendLines = [ new TrendLine(TrendLine::TRENDLINE_LINEAR, null, null, false, false), new TrendLine(TrendLine::TRENDLINE_POLYNOMIAL, 3, null, true, true, 20.0, 28.0, 44104.5, 'metric3 polynomial fit'), new TrendLine(TrendLine::TRENDLINE_MOVING_AVG, null, 2, true), ]; $dataSeriesValues[0]->setTrendLines($trendLines); // Suppress connecting lines; instead, add different Trendline algorithms to // determine how well the data fits the algorithm (Rsquared="goodness of fit") // Display RSqr plus the eqn just because we can. $dataSeriesValues[0]->setScatterLines(false); // points not connected $dataSeriesValues[0]->getMarkerFillColor() ->setColorProperties('FFFF00', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $dataSeriesValues[0]->getMarkerBorderColor() ->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // add properties to the trendLines - give each a different color $dataSeriesValues[0]->getTrendLines()[0]->getLineColor()->setColorProperties('accent4', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[0]->getTrendLines()[0]->setLineStyleProperties(0.5, null, null, null, null, Properties::LINE_STYLE_ARROW_TYPE_STEALTH, 5, Properties::LINE_STYLE_ARROW_TYPE_OPEN, 8); $dataSeriesValues[0]->getTrendLines()[1]->getLineColor()->setColorProperties('accent3', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[0]->getTrendLines()[1]->setLineStyleProperties(1.25); $dataSeriesValues[0]->getTrendLines()[2]->getLineColor()->setColorProperties('accent2', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); $dataSeriesValues[0]->getTrendLines()[2]->setLineStyleProperties(1.5, null, null, null, null, null, 0, Properties::LINE_STYLE_ARROW_TYPE_OPEN, 8); $xAxis = new ChartAxis(); $xAxis->setAxisNumberProperties(Properties::FORMAT_CODE_DATE_ISO8601); // m/d/yyyy // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_SMOOTHMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title('Test Scatter Chart - trendlines for metric3 values'); $yAxisLabel = new Title('Value ($k)'); // Create the chart $chart = new Chart( 'chart2', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis // $yAxis, // yAxis ); // Set the position of the chart in the chart sheet below the first chart $chart->setTopLeftPosition('A13'); $chart->setBottomRightPosition('P25'); // Add the chart to the worksheet $chartSheet $chartSheet->addChart($chart); $helper->renderChart($chart, __FILE__); $spreadsheet->setActiveSheetIndex(1); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true, resetActiveSheet: false); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter6_value_xaxis.php ================================================ getActiveSheet(); $dataSheet->setTitle('Data'); $results = [ ['Station 1', 'Score'], [13.25, 3], [16.25, 4], [18.5, 4], [15.5, 3], [15.75, 5], [17.25, 4], [10.5, 2], ]; $dataSheet->fromArray($results); $spreadsheet->createSheet(); $chartSheet = $spreadsheet->getSheet(1); $chartSheet->setTitle('Appendix'); $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Data!$A$1', null, 1), ]; $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$A$2:$A$' . count($results), Properties::FORMAT_CODE_NUMBER, 4, null, 'diamond', null, 7), ]; $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Data!$B$2:$B$' . count($results), Properties::FORMAT_CODE_NUMBER, 8), ]; $dataSeriesValues[0]->setScatterLines(false); // Points not connected $dataSeriesValues[0]->getMarkerFillColor() ->setColorProperties('accent1', null, ChartColor::EXCEL_COLOR_TYPE_SCHEME); // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_LINEMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title = new Title($results[0][0]); $xAxis = new ChartAxis(); $xAxis->setAxisOptionsProperties( Properties::AXIS_LABELS_NEXT_TO, null, // horizontalCrossesValue null, // horizontalCrosses null, // axisOrientation null, // majorTmt Properties::TICK_MARK_OUTSIDE, // minorTmt '0', // minimum '6', // maximum null, // majorUnit '1', // minorUnit ); $xAxis->setAxisType(ChartAxis::AXIS_TYPE_VALUE); $yAxis = new ChartAxis(); $yAxis->setAxisOptionsProperties( Properties::AXIS_LABELS_NEXT_TO, null, // horizontalCrossesValue null, // horizontalCrosses null, // axisOrientation null, // majorTmt Properties::TICK_MARK_OUTSIDE, // minorTmt '0', // minimum '25', // 30 // maximum null, // majorUnit '5', // minorUnit ); // Create the chart $chart = new Chart( 'chart2', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel null, // yAxisLabel // added xAxis for correct date display $xAxis, // xAxis $yAxis, // yAxis ); // Set the position of the chart in the chart sheet below the first chart $chart->setTopLeftPosition('B2'); $chart->setBottomRightPosition('K22'); // Add the chart to the worksheet $chartSheet $chartSheet->addChart($chart); $helper->renderChart($chart, __FILE__); $spreadsheet->setActiveSheetIndex(1); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true, resetActiveSheet: false); ================================================ FILE: samples/Chart33b/33_Chart_create_scatter7_blanks.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['', 2010, 2011, 2012], ['Q1', 12, 15, 21], ['Q2', 56, null, 86], ['Q3', 52, 61, 69], ['Q4', 30, 32, 0], ], strictNullComparison: true ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), // 2010 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), // 2011 new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), // 2012 ]; // Set the X-Axis Labels $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$5', null, 4), // Q1 to Q4 ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$5', null, 4), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_SCATTERCHART, // plotType null, // plotGrouping (Scatter charts don't have any grouping) range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues, // plotValues null, // plotDirection false, // smooth line DataSeries::STYLE_LINEMARKER // plotStyle ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_TOPRIGHT, null, false); $title1 = new Title('Test Scatter Chart Gap'); $yAxisLabel1 = new Title('Value ($k)'); // Create the chart $chart1 = new Chart( 'chart1', // name $title1, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs null, // xAxisLabel $yAxisLabel1 // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart1); $helper->renderChart($chart1, __FILE__); $title2 = new Title('Test Scatter Chart Zero'); $yAxisLabel2 = new Title('Value ($k)'); // Create the chart $chart2 = new Chart( 'chart2', // name $title2, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_ZERO, // displayBlanksAs null, // xAxisLabel $yAxisLabel2 // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('A22'); $chart2->setBottomRightPosition('H35'); // Add the chart to the worksheet $worksheet->addChart($chart2); $helper->renderChart($chart2, __FILE__); $title3 = new Title('Test Scatter Chart Span'); $yAxisLabel3 = new Title('Value ($k)'); // Create the chart $chart3 = new Chart( 'chart3', // name $title3, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_SPAN, // displayBlanksAs null, // xAxisLabel $yAxisLabel3 // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart3->setTopLeftPosition('A37'); $chart3->setBottomRightPosition('H50'); // Add the chart to the worksheet $worksheet->addChart($chart3); $helper->renderChart($chart3, __FILE__); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_stock.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['Counts', 'Max', 'Min', 'Min Threshold', 'Max Threshold'], [10, 10, 5, 0, 50], [30, 20, 10, 0, 50], [20, 30, 15, 0, 50], [40, 10, 0, 0, 50], [100, 40, 5, 0, 50], ], null, 'A1', true ); $worksheet->getStyle('B2:E6')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER_00); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), //Max / Open new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), //Min / Close new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), //Min Threshold / Min new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$E$1', null, 1), //Max Threshold / Max ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$6', null, 5), // Counts ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$6', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$6', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$6', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$E$2:$E$6', null, 5), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_STOCKCHART, // plotType null, // plotGrouping - if we set this to not null, then xlsx throws error range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $legend->getBorderLines()->setLineColorProperties('ffc000', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $legend->getFillColor()->setColorProperties('cccccc'); $legendText = new AxisText(); $legendText->getFillColorObject()->setValue('008080')->setType(ChartColor::EXCEL_COLOR_TYPE_RGB); $legendText->setShadowProperties(1); $legend->setLegendText($legendText); $title = new Title('Test Stock Chart'); $xAxisLabel = new Title('Counts'); $yAxisLabel = new Title('Values'); // Create the chart $chart = new Chart( 'stock-chart', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs $xAxisLabel, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); $worksheet->setSelectedCells('G2'); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/Chart33b/33_Chart_create_stock2.php ================================================ getActiveSheet(); $worksheet->fromArray( [ ['Counts', 'Max', 'Min', 'Min Threshold', 'Max Threshold'], [10, 10, 5, 0, 50], [30, 20, 10, 0, 50], [20, 30, 15, 0, 50], [40, 10, 0, 0, 50], [100, 40, 5, 0, 50], ], null, 'A1', true ); $worksheet->getStyle('B2:E6')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER_00); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesLabels = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', null, 1), //Max / Open new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', null, 1), //Min / Close new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$D$1', null, 1), //Min Threshold / Min new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$E$1', null, 1), //Max Threshold / Max ]; // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$6', null, 5), // Counts ]; // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues = [ new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$6', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$6', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$D$2:$D$6', null, 5), new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$E$2:$E$6', null, 5), ]; // Build the dataseries $series = new DataSeries( DataSeries::TYPE_STOCKCHART, // plotType null, // plotGrouping - if we set this to not null, then xlsx throws error range(0, count($dataSeriesValues) - 1), // plotOrder $dataSeriesLabels, // plotLabel $xAxisTickValues, // plotCategory $dataSeriesValues // plotValues ); // Set the series in the plot area $plotArea = new PlotArea(null, [$series]); // Set the chart legend $legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false); $legend->getBorderLines()->setLineColorProperties('ffc000', null, ChartColor::EXCEL_COLOR_TYPE_RGB); $legend->getFillColor()->setColorProperties('cccccc'); $legendText = new AxisText(); $legendText->getFillColorObject()->setValue('008080')->setType(ChartColor::EXCEL_COLOR_TYPE_RGB); $legendText->setShadowProperties(1); $legend->setLegendText($legendText); $title = new Title('Test Stock Chart'); $xAxisLabel = new Title('Counts'); $yAxisLabel = new Title('Values'); // 3 stmts below are only difference from 33_chart_create_stock.php $plotArea->setGapWidth(300); $plotArea->setUseUpBars(true); $plotArea->setUseDownBars(true); // Create the chart $chart = new Chart( 'stock-chart', // name $title, // title $legend, // legend $plotArea, // plotArea true, // plotVisibleOnly DataSeries::EMPTY_AS_GAP, // displayBlanksAs $xAxisLabel, // xAxisLabel $yAxisLabel // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('A7'); $chart->setBottomRightPosition('H20'); // Add the chart to the worksheet $worksheet->addChart($chart); $helper->renderChart($chart, __FILE__); $worksheet->setSelectedCells('G2'); // Save Excel 2007 file $helper->write($spreadsheet, __FILE__, ['Xlsx'], true); ================================================ FILE: samples/ComplexNumbers1/COMPLEX.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [3, 4], [3, 4, '"j"'], [3.5, 4.75], [0, 1], [1, 0], [0, -1], [0, 2], [2, 0], ]; $testDataCount = count($testData); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('A' . $row, '=COMPLEX(' . implode(',', $testData[$row - 1]) . ')'); } for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(A$row): Formula " . $worksheet->getCell('A' . $row)->getValueString() . ' result is ' . $worksheet->getCell('A' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers1/IMABS.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMABS(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The absolute value of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers1/IMAGINARY.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMAGINARY(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The imaginary component of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers1/IMARGUMENT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMARGUMENT(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Theta Argument of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() . ' radians' ); } ================================================ FILE: samples/ComplexNumbers1/IMCONJUGATE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMCONJUGATE(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Conjugate value of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers1/IMREAL.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMREAL(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The real component of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMCOS.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMCOS(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Cosine of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMCOSH.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMCOSH(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Hyperbolic Cosine of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMCOT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMCOT(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Cotangent of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMCSC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMCSC(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Cosecant of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMCSCH.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMCSCH(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Hyperbolic Cosecant of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMDIV.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i', '5-3i'], ['3+4i', '5+3i'], ['-238+240i', '10+24i'], ['1+2i', 30], ['1+2i', '2i'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=IMDIV(A' . $row . ', B' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Quotient of " . $worksheet->getCell('A' . $row)->getValueString() . ' and ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMEXP.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMEXP(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Exponential of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMLN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMLN(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Natural Logarithm of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMLOG10.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMLOG10(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Base-10 Logarithm of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers2/IMLOG2.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMLOG2(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Base-2 Logarithm of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMPOWER.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i', 2], ['5-12i', 2], ['3.25+7.5i', 3], ['3.25-12.5i', 2], ['-3.25+7.5i', 3], ['-3.25-7.5i', 4], ['0-j', 5], ['0-2.5j', 3], ['0+j', 2.5], ['0+1.25j', 2], [4, 3], [-2.5, 2], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=IMPOWER(A' . $row . ', B' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): " . $worksheet->getCell('A' . $row)->getValueString() . ' raised to the power of ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMPRODUCT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i', '5-3i'], ['3+4i', '5+3i'], ['-238+240i', '10+24i'], ['1+2i', 30], ['1+2i', '2i'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=IMPRODUCT(A' . $row . ', B' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Product of " . $worksheet->getCell('A' . $row)->getValueString() . ' and ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSEC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMSEC(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Secant of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSECH.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMSECH(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Hyperbolic Ssecant of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSIN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMSIN(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Sine of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSINH.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMSINH(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Hyperbolic Sine of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSQRT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMSQRT(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Square Root of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSUB.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i', '5-3i'], ['3+4i', '5+3i'], ['-238+240i', '10+24i'], ['1+2i', 30], ['1+2i', '2i'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=IMSUB(A' . $row . ', B' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Difference between " . $worksheet->getCell('A' . $row)->getValueString() . ' and ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMSUM.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i', '5-3i'], ['3+4i', '5+3i'], ['-238+240i', '10+24i'], ['1+2i', 30], ['1+2i', '2i'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=IMSUM(A' . $row . ', B' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Sum of " . $worksheet->getCell('A' . $row)->getValueString() . ' and ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ComplexNumbers3/IMTAN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['3+4i'], ['5-12i'], ['3.25+7.5i'], ['3.25-12.5i'], ['-3.25+7.5i'], ['-3.25-7.5i'], ['0-j'], ['0-2.5j'], ['0+j'], ['0+1.25j'], [4], [-2.5], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=IMTAN(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): The Tangent of " . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('B' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/ConditionalFormatting/01_Basic_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Literal Value Comparison') ->setCellValue('A9', 'Value Comparison with Absolute Cell Reference $H$9') ->setCellValue('A17', 'Value Comparison with Relative Cell References') ->setCellValue('A23', 'Value Comparison with Formula based on AVERAGE() ± STDEV()') ->setCellValue('A30', 'Literal String Value Comparison'); $dataArray = [ [-2, -1, 0, 1, 2], [-1, 0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], ]; $betweenDataArray = [ [2, 7, 6], [9, 5, 1], [4, 3, 8], ]; $stringArray = [ ['I'], ['Love'], ['PHP'], ]; $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, 'A2', true) ->fromArray($dataArray, null, 'A10', true) ->fromArray($betweenDataArray, null, 'A18', true) ->fromArray($dataArray, null, 'A24', true) ->fromArray($stringArray, null, 'A31', true) ->setCellValue('H9', 1); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:E1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A9:E9')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A17:E17')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A23:E23')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A30:E30')->getFont()->setBold(true); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $yellowStyle = new Style(false, true); $yellowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_YELLOW); $yellowStyle->getFont()->setColor(new Color(Color::COLOR_BLUE)); $greenStyle = new Style(false, true); $greenStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_GREEN); $greenStyle->getFont()->setColor(new Color(Color::COLOR_DARKRED)); $redStyle = new Style(false, true); $redStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_RED); $redStyle->getFont()->setColor(new Color(Color::COLOR_GREEN)); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); // Set rules for Literal Value Comparison $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); // Set rules for Value Comparison with Absolute Cell Reference $H$9 $cellRange = 'A10:E13'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->equals('$H$9', Wizard::VALUE_TYPE_CELL) ->setStyle($yellowStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->greaterThan('$H$9', Wizard::VALUE_TYPE_CELL) ->setStyle($greenStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->lessThan('$H$9', Wizard::VALUE_TYPE_CELL) ->setStyle($redStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Value Comparison with Relative Cell References $cellRange = 'A18:A20'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->between('$B1', Wizard::VALUE_TYPE_CELL) ->and('$C1', Wizard::VALUE_TYPE_CELL) ->setStyle($greenStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Value Comparison with Formula $cellRange = 'A24:E27'; // accommodation for phpstan $absoluteCoordinate = fn (mixed $cell): string => is_string($cell) ? Coordinate::absoluteCoordinate($cell) : ''; $formulaRange = implode( ':', array_map( $absoluteCoordinate, Coordinate::splitRange($cellRange)[0] ) ); $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->between('AVERAGE(' . $formulaRange . ')-STDEV(' . $formulaRange . ')', Wizard::VALUE_TYPE_FORMULA) ->and('AVERAGE(' . $formulaRange . ')+STDEV(' . $formulaRange . ')', Wizard::VALUE_TYPE_FORMULA) ->setStyle($yellowStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->greaterThan('AVERAGE(' . $formulaRange . ')+STDEV(' . $formulaRange . ')', Wizard::VALUE_TYPE_FORMULA) ->setStyle($greenStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->lessThan('AVERAGE(' . $formulaRange . ')-STDEV(' . $formulaRange . ')', Wizard::VALUE_TYPE_FORMULA) ->setStyle($redStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Value Comparison with String Literal $cellRange = 'A31:A33'; $formulaRange = implode( ':', array_map( $absoluteCoordinate, Coordinate::splitRange($cellRange)[0] ) ); $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->equals('LOVE') ->setStyle($redStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->equals('PHP') ->setStyle($greenStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/02_Text_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Value Begins With Literal') ->setCellValue('A7', 'Value Ends With Literal') ->setCellValue('A13', 'Value Contains Literal') ->setCellValue('A19', "Value Doesn't Contain Literal") ->setCellValue('E1', 'Value Begins With using Cell Reference') ->setCellValue('E7', 'Value Ends With using Cell Reference') ->setCellValue('E13', 'Value Contains using Cell Reference') ->setCellValue('E19', "Value Doesn't Contain using Cell Reference") ->setCellValue('A25', 'Simple Comparison using Concatenation Formula'); $dataArray = [ ['HELLO', 'WORLD'], ['MELLOW', 'YELLOW'], ['SLEEPY', 'HOLLOW'], ]; $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, 'A2', true) ->fromArray($dataArray, null, 'A8', true) ->fromArray($dataArray, null, 'A14', true) ->fromArray($dataArray, null, 'A20', true) ->fromArray($dataArray, null, 'E2', true) ->fromArray($dataArray, null, 'E8', true) ->fromArray($dataArray, null, 'E14', true) ->fromArray($dataArray, null, 'E20', true) ->fromArray($dataArray, null, 'A26', true) ->setCellValue('D1', 'H') ->setCellValue('D7', 'OW') ->setCellValue('D13', 'LL') ->setCellValue('D19', 'EL') ->setCellValue('C26', 'HELLO WORLD') ->setCellValue('C27', 'SOYLENT GREEN') ->setCellValue('C28', 'SLEEPY HOLLOW'); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:G1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A7:G7')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A13:G13')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A19:G19')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A25:C25')->getFont()->setBold(true); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $yellowStyle = new Style(false, true); $yellowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_YELLOW); $yellowStyle->getFont()->setColor(new Color(Color::COLOR_BLUE)); $greenStyle = new Style(false, true); $greenStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_GREEN); $greenStyle->getFont()->setColor(new Color(Color::COLOR_DARKRED)); $redStyle = new Style(false, true); $redStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_RED); $redStyle->getFont()->setColor(new Color(Color::COLOR_GREEN)); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); // Set rules for Literal Value Begins With $cellRange = 'A2:B4'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->beginsWith('H') ->setStyle($yellowStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Value Begins With using Cell Reference $cellRange = 'E2:F4'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->beginsWith('$D$1', Wizard::VALUE_TYPE_CELL) ->setStyle($yellowStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Literal Value Ends With $cellRange = 'A8:B10'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->endsWith('OW') ->setStyle($yellowStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Value Ends With using Cell Reference $cellRange = 'E8:F10'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->endsWith('$D$7', Wizard::VALUE_TYPE_CELL) ->setStyle($yellowStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Literal Value Contains $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); // Set rules for Value Contains using Cell Reference $cellRange = 'E14:F16'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->contains('$D$13', Wizard::VALUE_TYPE_CELL) ->setStyle($greenStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Literal Value Does Not Contain $cellRange = 'A20:B22'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->doesNotContain('EL') ->setStyle($redStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Value Contains using Cell Reference $cellRange = 'E20:F22'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->doesNotContain('$D$19', Wizard::VALUE_TYPE_CELL) ->setStyle($redStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Simple Comparison using Concatenation Formula $cellRange = 'C26:C28'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->equals('CONCATENATE($A1," ",$B1)', Wizard::VALUE_TYPE_FORMULA) ->setStyle($yellowStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/03_Blank_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Blank Comparison'); $dataArray = [ ['HELLO', null], [null, 'WORLD'], ]; $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, 'A2', true); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $greenStyle = new Style(false, true); $greenStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_GREEN); $greenStyle->getFont()->setColor(new Color(Color::COLOR_DARKRED)); $redStyle = new Style(false, true); $redStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_RED); $redStyle->getFont()->setColor(new Color(Color::COLOR_GREEN)); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); // Set rules for Blank Comparison $cellRange = 'A2:B3'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Blanks $blanksWizard */ $blanksWizard = $wizardFactory->newRule(Wizard::BLANKS); $blanksWizard->setStyle($redStyle); $conditionalStyles[] = $blanksWizard->getConditional(); $blanksWizard->notBlank() ->setStyle($greenStyle); $conditionalStyles[] = $blanksWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($blanksWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/04_Error_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Error Comparison'); $dataArray = [ [5, -2, '=A2/B2'], [5, -1, '=A3/B3'], [5, 0, '=A4/B4'], [5, 1, '=A5/B5'], [5, 2, '=A6/B6'], ]; $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, 'A2', true); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $greenStyle = new Style(false, true); $greenStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_GREEN); $greenStyle->getFont()->setColor(new Color(Color::COLOR_DARKRED)); $redStyle = new Style(false, true); $redStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_RED); $redStyle->getFont()->setColor(new Color(Color::COLOR_GREEN)); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); // Set rules for Blank Comparison $cellRange = 'C2:C6'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Errors $errorsWizard */ $errorsWizard = $wizardFactory->newRule(Wizard::ERRORS); $errorsWizard->setStyle($redStyle); $conditionalStyles[] = $errorsWizard->getConditional(); $errorsWizard->notError() ->setStyle($greenStyle); $conditionalStyles[] = $errorsWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($errorsWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/05_Date_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('B1', 'yesterday()') ->setCellValue('C1', 'today()') ->setCellValue('D1', 'tomorrow()') ->setCellValue('E1', 'last7Days()') ->setCellValue('F1', 'lastWeek()') ->setCellValue('G1', 'thisWeek()') ->setCellValue('H1', 'nextWeek()') ->setCellValue('I1', 'lastMonth()') ->setCellValue('J1', 'thisMonth()') ->setCellValue('K1', 'nextMonth()'); $dateFunctionArray = [ 'yesterday()', 'today()', 'tomorrow()', 'last7Days()', 'lastWeek()', 'thisWeek()', 'nextWeek()', 'lastMonth()', 'thisMonth()', 'nextMonth()', ]; $dateTitleArray = [ ['First day of last month'], ['Last day of last month'], ['Last Monday'], ['Last Friday'], ['Monday last week'], ['Wednesday last week'], ['Friday last week'], ['Yesterday'], ['Today'], ['Tomorrow'], ['Monday this week'], ['Wednesday this week'], ['Friday this week'], ['Monday next week'], ['Wednesday next week'], ['Friday next week'], ['First day of next month'], ['Last day of next month'], ]; $dataArray = [ ['=EOMONTH(TODAY(),-2)+1'], ['=EOMONTH(TODAY(),-1)'], ['=TODAY()-WEEKDAY(TODAY(),3)'], ['=TODAY()-WEEKDAY(TODAY())-1'], ['=2-WEEKDAY(TODAY())+TODAY()-7'], ['=4-WEEKDAY(TODAY())+TODAY()-7'], ['=6-WEEKDAY(TODAY())+TODAY()-7'], ['=TODAY()-1'], ['=TODAY()'], ['=TODAY()+1'], ['=2-WEEKDAY(TODAY())+TODAY()'], ['=4-WEEKDAY(TODAY())+TODAY()'], ['=6-WEEKDAY(TODAY())+TODAY()'], ['=2-WEEKDAY(TODAY())+TODAY()+7'], ['=4-WEEKDAY(TODAY())+TODAY()+7'], ['=6-WEEKDAY(TODAY())+TODAY()+7'], ['=EOMONTH(TODAY(),0)+1'], ['=EOMONTH(TODAY(),1)'], ]; $spreadsheet->getActiveSheet() ->fromArray($dateFunctionArray, null, 'B1', true); $spreadsheet->getActiveSheet() ->fromArray($dateTitleArray, null, 'A2', true); for ($column = 'B'; $column !== 'L'; StringHelper::stringIncrement($column)) { $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, "{$column}2", true); } // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('B1:K1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('B1:K1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $yellowStyle = new Style(false, true); $yellowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_YELLOW); $yellowStyle->getFont()->setColor(new Color(Color::COLOR_BLUE)); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); for ($column = 'B'; $column !== 'L'; StringHelper::stringIncrement($column)) { $wizardFactory = new Wizard("{$column}2:{$column}19"); /** @var Wizard\DateValue $dateWizard */ $dateWizard = $wizardFactory->newRule(Wizard::DATES_OCCURRING); $conditionalStyles = []; /** @var string */ $cellContents = $spreadsheet->getActiveSheet()->getCell("{$column}1")->getValue(); $methodName = trim($cellContents, '()'); /** @var Wizard\DateValue */ $targetStyle = $dateWizard->$methodName(); $targetStyle->setStyle($yellowStyle); $conditionalStyles[] = $dateWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($dateWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); } // Set conditional formatting rules and styles $helper->log('Set some additional styling for date formats'); $spreadsheet->getActiveSheet()->getStyle('B:B')->getNumberFormat()->setFormatCode('ddd dd-mmm-yyyy'); for ($column = 'A'; $column !== 'L'; StringHelper::stringIncrement($column)) { if ($column !== 'A') { $spreadsheet->getActiveSheet()->getStyle("{$column}:{$column}") ->getNumberFormat()->setFormatCode('ddd dd-mmm-yyyy'); } $spreadsheet->getActiveSheet()->getColumnDimension($column) ->setAutoSize(true); } $spreadsheet->getActiveSheet()->getStyle('A:A')->getFont()->setBold(true); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/06_Duplicate_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Duplicates Comparison'); $dataArray = [ [1, 0, 3], [2, 1, 1], [3, 1, 4], [4, 2, 1], [5, 3, 5], [6, 5, 9], [7, 8, 2], [8, 13, 6], [9, 21, 5], [10, 34, 3], [11, 55, 5], ]; $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, 'A2', true); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $yellowStyle = new Style(false, true); $yellowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_YELLOW); $yellowStyle->getFont()->setColor(new Color(Color::COLOR_BLUE)); $greenStyle = new Style(false, true); $greenStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_GREEN); $greenStyle->getFont()->setColor(new Color(Color::COLOR_DARKRED)); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); // Set rules for Duplicates Comparison $cellRange = 'A2:C12'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Duplicates $duplicatesWizard */ $duplicatesWizard = $wizardFactory->newRule(Wizard::DUPLICATES); $duplicatesWizard->setStyle($yellowStyle); $conditionalStyles[] = $duplicatesWizard->getConditional(); $duplicatesWizard->unique() ->setStyle($greenStyle); $conditionalStyles[] = $duplicatesWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($duplicatesWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/07_Expression_Comparisons.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Mark Baker') ->setLastModifiedBy('Mark Baker') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet() ->setCellValue('A1', 'Odd/Even Expression Comparison') ->setCellValue('A4', 'Note that these functions are not available for Xls files') ->setCellValue('A15', 'Sales Grid Expression Comparison') ->setCellValue('A25', 'Sales Grid Multiple Expression Comparison'); $dataArray = [ [1, 0, 3], [2, 1, 1], [3, 1, 4], [4, 2, 1], [5, 3, 5], [6, 5, 9], [7, 8, 2], [8, 13, 6], [9, 21, 5], [10, 34, 4], ]; $salesGrid = [ ['Name', 'Sales', 'Country', 'Quarter'], ['Smith', 16753, 'UK', 'Q3'], ['Johnson', 14808, 'USA', 'Q4'], ['Williams', 10644, 'UK', 'Q2'], ['Jones', 1390, 'USA', 'Q3'], ['Brown', 4865, 'USA', 'Q4'], ['Williams', 12438, 'UK', 'Q2'], ]; $spreadsheet->getActiveSheet() ->fromArray($dataArray, null, 'A2', true); $spreadsheet->getActiveSheet() ->fromArray($salesGrid, null, 'A16', true); $spreadsheet->getActiveSheet() ->fromArray($salesGrid, null, 'A26', true); // Set title row bold $helper->log('Set title row bold'); $spreadsheet->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A15:D16')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A25:D26')->getFont()->setBold(true); // Define some styles for our Conditionals $helper->log('Define some styles for our Conditionals'); $yellowStyle = new Style(false, true); $yellowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_YELLOW); $yellowStyle->getFont()->setColor(new Color(Color::COLOR_BLUE)); $greenStyle = new Style(false, true); $greenStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB(Color::COLOR_GREEN); $greenStyle->getFont()->setColor(new Color(Color::COLOR_DARKRED)); $greenStyleMoney = clone $greenStyle; $greenStyleMoney->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_ACCOUNTING_USD); // Set conditional formatting rules and styles $helper->log('Define conditional formatting and set styles'); // Set rules for Odd/Even Expression Comparison $cellRange = 'A2:C11'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Expression $expressionWizard */ $expressionWizard = $wizardFactory->newRule(Wizard::EXPRESSION); $expressionWizard->expression('ISODD(A1)') ->setStyle($greenStyle); $conditionalStyles[] = $expressionWizard->getConditional(); $expressionWizard->expression('ISEVEN(A1)') ->setStyle($yellowStyle); $conditionalStyles[] = $expressionWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($expressionWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Sales Grid Row match against Country Comparison $cellRange = 'A17:D22'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Expression $expressionWizard */ $expressionWizard = $wizardFactory->newRule(Wizard::EXPRESSION); $expressionWizard->expression('$C1="USA"') ->setStyle($greenStyleMoney); $conditionalStyles[] = $expressionWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($expressionWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set rules for Sales Grid Row match against Country and Quarter Comparison $cellRange = 'A27:D32'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\Expression $expressionWizard */ $expressionWizard = $wizardFactory->newRule(Wizard::EXPRESSION); $expressionWizard->expression('AND($C1="USA",$D1="Q4")') ->setStyle($greenStyleMoney); $conditionalStyles[] = $expressionWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($expressionWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); // Set conditional formatting rules and styles $helper->log('Set some additional styling for money formats'); $spreadsheet->getActiveSheet()->getStyle('B17:B22') ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_ACCOUNTING_USD); $spreadsheet->getActiveSheet()->getStyle('B27:B32') ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_ACCOUNTING_USD); $spreadsheet->getActiveSheet()->getColumnDimension('B') ->setAutoSize(true); // Save $helper->write($spreadsheet, __FILE__); ================================================ FILE: samples/ConditionalFormatting/cond08_colorscale.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('Owen Leibman') ->setLastModifiedBy('Owen Leibman') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); $sheet ->setCellValue('A1', 1) ->setCellValue('A2', 2) ->setCellValue('A3', 8) ->setCellValue('A4', 4) ->setCellValue('A5', 5) ->setCellValue('A6', 6) ->setCellValue('A7', 7) ->setCellValue('A8', 3) ->setCellValue('A9', 9) ->setCellValue('A10', 10); // Set conditional formatting rules and styles $helper->log('Define conditional formatting using Color Scales'); $cellRange = 'A1:A10'; $condition1 = new Conditional(); $condition1->setConditionType(Conditional::CONDITION_COLORSCALE); $colorScale = new ConditionalColorScale(); $condition1->setColorScale($colorScale); $colorScale ->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject('min')) ->setMidpointConditionalFormatValueObject(new ConditionalFormatValueObject('percentile', '40')) ->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject('max')) ->setMinimumColor(new Color('FFF8696B')) ->setMidpointColor(new Color('FFFFEB84')) ->setMaximumColor(new Color('FF63BE7B')); $conditionalStyles = [$condition1]; $sheet ->getStyle($cellRange) ->setConditionalStyles($conditionalStyles); $sheet->setSelectedCells('B1'); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/ConditionalFormatting/cond09_iconset.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('issakujitsuk') ->setLastModifiedBy('issakujitsuk') ->setTitle('PhpSpreadsheet Test Document') ->setSubject('PhpSpreadsheet Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Test result file'); // Create the worksheet $helper->log('Add data'); foreach (['A', 'B', 'C'] as $columnIndex) { $sheet ->setCellValue("{$columnIndex}1", 1) ->setCellValue("{$columnIndex}2", 2) ->setCellValue("{$columnIndex}3", 8) ->setCellValue("{$columnIndex}4", 4) ->setCellValue("{$columnIndex}5", 5) ->setCellValue("{$columnIndex}6", 6) ->setCellValue("{$columnIndex}7", 7) ->setCellValue("{$columnIndex}8", 3) ->setCellValue("{$columnIndex}9", 9) ->setCellValue("{$columnIndex}10", 10); } // Set conditional formatting rules and styles $helper->log('Define conditional formatting using Icon Set'); // 3 icons $sheet->getStyle('A1:A10') ->setConditionalStyles([ makeConditionalIconSet( IconSetValues::ThreeSymbols, [ new ConditionalFormatValueObject('percent', 0), new ConditionalFormatValueObject('percent', 33), new ConditionalFormatValueObject('percent', 67), ] ), ]); // 4 icons $sheet->getStyle('B1:B10') ->setConditionalStyles([ makeConditionalIconSet( IconSetValues::FourArrows, [ new ConditionalFormatValueObject('percent', 0), new ConditionalFormatValueObject('percent', 25), new ConditionalFormatValueObject('percent', 50), new ConditionalFormatValueObject('percent', 75), ] ), ]); // 5 icons $sheet->getStyle('C1:C10') ->setConditionalStyles([ makeConditionalIconSet( IconSetValues::FiveQuarters, [ new ConditionalFormatValueObject('percent', 0), new ConditionalFormatValueObject('percent', 20), new ConditionalFormatValueObject('percent', 40), new ConditionalFormatValueObject('percent', 60), new ConditionalFormatValueObject('percent', 80), ] ), ]); // Save $sheet->setSelectedCells('A1'); $helper->write($spreadsheet, __FILE__, ['Xlsx']); /** * Helper function to create a Conditional object with an IconSet. * * @param IconSetValues $type The type of icon set * @param ConditionalFormatValueObject[] $cfvos The conditional format value objects */ function makeConditionalIconSet( IconSetValues $type, array $cfvos, ): Conditional { $condition = new Conditional(); $condition->setConditionType(Conditional::CONDITION_ICONSET); $iconSet = new ConditionalIconSet(); $condition->setIconSet($iconSet); $iconSet->setIconSetType($type) ->setCfvos($cfvos); return $condition; } ================================================ FILE: samples/Database/DAVERAGE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The Average yield of Apple trees over 10\' in height'); $worksheet->setCellValue('B12', '=DAVERAGE(A4:E10,"Yield",A1:B2)'); $worksheet->setCellValue('A13', 'The Average age of all Apple and Pear trees in the orchard'); $worksheet->setCellValue('B13', '=DAVERAGE(A4:E10,3,A1:A3)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:B2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DCOUNT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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, 'N/A', 10, 75.00], ['Pear', 9, 8, 8, 77.00], ['Apple', 12, 11, 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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The Number of Apple trees between 10\' and 16\' in height whose age is known'); $worksheet->setCellValue('B12', '=DCOUNT(A4:E10,"Age",A1:F2)'); $worksheet->setCellValue('A13', 'The Number of Apple and Pear trees in the orchard with a numeric value in column 3 ("Age")'); $worksheet->setCellValue('B13', '=DCOUNT(A4:E10,3,A1:A3)'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:F2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DCOUNTA.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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, 'N/A', 10, 75.00], ['Pear', 9, 8, 8, 77.00], ['Apple', 12, 11, 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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The Number of Apple trees between 10\' and 16\' in height'); $worksheet->setCellValue('B12', '=DCOUNTA(A4:E10,"Age",A1:F2)'); $worksheet->setCellValue('A13', 'The Number of Apple and Pear trees in the orchard'); $worksheet->setCellValue('B13', '=DCOUNTA(A4:E10,3,A1:A3)'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:F2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DGET.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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"', '>12', null, null, null, null], ]; $worksheet->fromArray($criteria, null, 'A1'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The height of the Apple tree between 10\' and 16\' tall'); $worksheet->setCellValue('B12', '=DGET(A4:E10,"Height",A1:F2)'); $worksheet->setCellValue('A13', 'The height of the Apple tree (will return an Excel error, because there is more than one apple tree)'); $worksheet->setCellValue('B13', '=DGET(A4:E10,"Height",A1:A2)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:F2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DMAX.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The tallest tree in the orchard'); $worksheet->setCellValue('B12', '=DMAX(A4:E10,"Height",A4:E10)'); $worksheet->setCellValue('A13', 'The Oldest apple tree in the orchard'); $worksheet->setCellValue('B13', '=DMAX(A4:E10,3,A1:A2)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $helper->log('ALL'); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DMIN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The shortest tree in the orchard'); $worksheet->setCellValue('B12', '=DMIN(A4:E10,"Height",A4:E10)'); $worksheet->setCellValue('A13', 'The Youngest apple tree in the orchard'); $worksheet->setCellValue('B13', '=DMIN(A4:E10,3,A1:A2)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $helper->log('ALL'); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DPRODUCT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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, 77.00], ['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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The product of the yields of all Apple trees over 10\' in the orchard'); $worksheet->setCellValue('B12', '=DPRODUCT(A4:E10,"Yield",A1:B2)'); $worksheet->setCellValue('A13', 'The product of the yields of all Apple trees in the orchard'); $worksheet->setCellValue('B13', '=DPRODUCT(A4:E10,"Yield",A1:A2)'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:B2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DSTDEV.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The estimated standard deviation in the yield of Apple and Pear trees'); $worksheet->setCellValue('B12', '=DSTDEV(A4:E10,"Yield",A1:A3)'); $worksheet->setCellValue('A13', 'The estimated standard deviation in height of Apple and Pear trees'); $worksheet->setCellValue('B13', '=DSTDEV(A4:E10,2,A1:A3)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DSTDEVP.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The standard deviation in the yield of Apple and Pear trees'); $worksheet->setCellValue('B12', '=DSTDEVP(A4:E10,"Yield",A1:A3)'); $worksheet->setCellValue('A13', 'The standard deviation in height of Apple and Pear trees'); $worksheet->setCellValue('B13', '=DSTDEVP(A4:E10,2,A1:A3)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DSUM.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The total profit from apple trees'); $worksheet->setCellValue('B12', '=DSUM(A4:E10,"Profit",A1:A2)'); $worksheet->setCellValue('A13', 'Total profit from apple trees with a height between 10 and 16 feet, and all pear trees'); $worksheet->setCellValue('B13', '=DSUM(A4:E10,"Profit",A1:F3)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A2', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:F3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DVAR.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The estimated variance in the yield of Apple and Pear trees'); $worksheet->setCellValue('B12', '=DVAR(A4:E10,"Yield",A1:A3)'); $worksheet->setCellValue('A13', 'The estimated variance in height of Apple and Pear trees'); $worksheet->setCellValue('B13', '=DVAR(A4:E10,2,A1:A3)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/Database/DVARP.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $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'); $worksheet->fromArray($database, null, 'A4'); $worksheet->setCellValue('A12', 'The variance in the yield of Apple and Pear trees'); $worksheet->setCellValue('B12', '=DVARP(A4:E10,"Yield",A1:A3)'); $worksheet->setCellValue('A13', 'The variance in height of Apple and Pear trees'); $worksheet->setCellValue('B13', '=DVARP(A4:E10,2,A1:A3)'); $worksheet->getStyle('E5:E10')->getNumberFormat() ->setFormatCode('0.00'); $helper->log('Database'); $databaseData = $worksheet->rangeToArray('A4:E10', null, true, true, true); $helper->displayGrid($databaseData, true); // Test the formulae $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B12', 'A12'); $helper->log('Criteria'); $criteriaData = $worksheet->rangeToArray('A1:A3', null, true, true, true); $helper->displayGrid($criteriaData); $helper->logCalculationResult($worksheet, $functionName, 'B13', 'A13'); ================================================ FILE: samples/DateTime/DATE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [[2012, 3, 26], [2012, 2, 29], [2012, 4, 1], [2012, 12, 25], [2012, 10, 31], [2012, 11, 5], [2012, 1, 1], [2012, 3, 17], [2011, 2, 29], [7, 5, 3], [2012, 13, 1], [2012, 11, 45], [2012, 0, 0], [2012, 1, 0], [2012, 0, 1], [2012, -2, 2], [2012, 2, -2], [2012, -2, -2], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log("(A{$row}) Year: " . $worksheet->getCell('A' . $row)->getFormattedValue()); $helper->log("(B{$row}) Month: " . $worksheet->getCell('B' . $row)->getFormattedValue()); $helper->log("(C{$row}) Day: " . $worksheet->getCell('C' . $row)->getFormattedValue()); $helper->log('Formula: ' . $worksheet->getCell('D' . $row)->getValueString()); $helper->log('Excel DateStamp: ' . $worksheet->getCell('D' . $row)->getCalculatedValueString()); $helper->log('Formatted DateStamp: ' . $worksheet->getCell('E' . $row)->getFormattedValue()); $helper->log(''); } ================================================ FILE: samples/DateTime/DATEDIF.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 1, 1], [1936, 3, 17], [1960, 12, 19], [1999, 12, 31], [2000, 1, 1], [2019, 2, 14], [2020, 7, 4], [2020, 2, 29], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=TODAY()'); $worksheet->setCellValue('G' . $row, '=DATEDIF(D' . $row . ', F' . $row . ', "Y")'); $worksheet->setCellValue('H' . $row, '=DATEDIF(D' . $row . ', F' . $row . ', "M")'); $worksheet->setCellValue('I' . $row, '=DATEDIF(D' . $row . ', F' . $row . ', "D")'); $worksheet->setCellValue('J' . $row, '=DATEDIF(D' . $row . ', F' . $row . ', "MD")'); $worksheet->setCellValue('K' . $row, '=DATEDIF(D' . $row . ', F' . $row . ', "YM")'); $worksheet->setCellValue('L' . $row, '=DATEDIF(D' . $row . ', F' . $row . ', "YD")'); } $worksheet->getStyle('E1:F' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf( 'Between: %s and %s', $worksheet->getCell('E' . $row)->getFormattedValue(), $worksheet->getCell('F' . $row)->getFormattedValue() )); $helper->log('In years ("Y"): ' . $worksheet->getCell('G' . $row)->getCalculatedValueString()); $helper->log('In months ("M"): ' . $worksheet->getCell('H' . $row)->getCalculatedValueString()); $helper->log('In days ("D"): ' . $worksheet->getCell('I' . $row)->getCalculatedValueString()); $helper->log('In days ignoring months and years ("MD"): ' . $worksheet->getCell('J' . $row)->getCalculatedValueString()); $helper->log('In months ignoring days and years ("YM"): ' . $worksheet->getCell('K' . $row)->getCalculatedValueString()); $helper->log('In days ignoring years ("YD"): ' . $worksheet->getCell('L' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime/DATEVALUE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = ['26 March 2012', '29 Feb 2012', 'April 1, 2012', '25/12/2012', '2012-Oct-31', '5th November', 'January 1st', 'April 2012', '17-03', '03-17', '03-2012', '29 Feb 2011', '03-05-07', '03-MAY-07', '03-13-07', '13-03-07', '03/13/07', '13/03/07', ]; $testDateCount = count($testDates); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('A' . $row, $testDates[$row - 1]); $worksheet->setCellValue('B' . $row, '=DATEVALUE(A' . $row . ')'); $worksheet->setCellValue('C' . $row, '=B' . $row); } $worksheet->getStyle('C1:C' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae $helper->log('Warning: The PhpSpreadsheet DATEVALUE() function accepts a wider range of date formats than MS Excel DATEFORMAT() function.'); for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log("(A{$row}) Date String: " . $worksheet->getCell('A' . $row)->getFormattedValue()); $helper->log('Formula: ' . $worksheet->getCell('B' . $row)->getValueString()); $helper->log('Excel DateStamp: ' . $worksheet->getCell('B' . $row)->getCalculatedValueString()); $helper->log('Formatted DateStamp: ' . $worksheet->getCell('C' . $row)->getFormattedValue()); $helper->log(''); } ================================================ FILE: samples/DateTime/DAY.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 2, 14], [1936, 3, 17], [1964, 4, 29], [1999, 5, 18], [2000, 6, 21], [2019, 7, 4], [2020, 8, 31], [1956, 9, 10], [2010, 10, 10], [1982, 11, 30], [1960, 12, 19], ['=YEAR(TODAY())', '=MONTH(TODAY())', '=DAY(TODAY())'], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=DAY(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('Day is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime/DAYS.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 1, 1], [1936, 3, 17], [1960, 12, 19], [1999, 12, 31], [2000, 1, 1], [2019, 2, 14], [2020, 7, 4], [2020, 2, 29], [2029, 12, 31], [2525, 1, 1], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=TODAY()'); $worksheet->setCellValue('G' . $row, '=DAYS(D' . $row . ', F' . $row . ')'); } $worksheet->getStyle('E1:F' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf( 'Between: %s and %s', $worksheet->getCell('E' . $row)->getFormattedValue(), $worksheet->getCell('F' . $row)->getFormattedValue() )); $helper->log('Days: ' . $worksheet->getCell('G' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime/DAYS360.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 1, 1], [1936, 3, 17], [1960, 12, 19], [1999, 12, 31], [2000, 1, 1], [2019, 2, 14], [2020, 7, 4], [2029, 12, 31], [2525, 1, 1], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=DATE(2022,12,31)'); $worksheet->setCellValue('G' . $row, '=DAYS360(D' . $row . ', F' . $row . ', FALSE)'); $worksheet->setCellValue('H' . $row, '=DAYS360(D' . $row . ', F' . $row . ', TRUE)'); } $worksheet->getStyle('E1:F' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf( 'Between: %s and %s', $worksheet->getCell('E' . $row)->getFormattedValue(), $worksheet->getCell('F' . $row)->getFormattedValue() )); $helper->log( 'Days: ' . $worksheet->getCell('G' . $row)->getCalculatedValueString() . ' (US) ' . $worksheet->getCell('H' . $row)->getCalculatedValueString() . ' (European)' ); } ================================================ FILE: samples/DateTime/EDATE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $months = range(-12, 12); $testDateCount = count($months); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('A' . $row, '=DATE(2020,12,31)'); $worksheet->setCellValue('B' . $row, '=A' . $row); $worksheet->setCellValue('C' . $row, $months[$row - 1]); $worksheet->setCellValue('D' . $row, '=EDATE(B' . $row . ', C' . $row . ')'); } $worksheet->getStyle('B1:B' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); $worksheet->getStyle('D1:D' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { /** @var null|bool|float|int|string */ $calc = $worksheet->getCell('D' . $row)->getCalculatedValue(); $helper->log( $worksheet->getCell('B' . $row)->getFormattedValue() . ' and ' . $worksheet->getCell('C' . $row)->getFormattedValue() . ' months is ' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('D' . $row)->getFormattedValue() . ')' ); } ================================================ FILE: samples/DateTime/EOMONTH.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $months = range(-12, 12); $testDateCount = count($months); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('A' . $row, '=DATE(2020,1,1)'); $worksheet->setCellValue('B' . $row, '=A' . $row); $worksheet->setCellValue('C' . $row, $months[$row - 1]); $worksheet->setCellValue('D' . $row, '=EOMONTH(B' . $row . ', C' . $row . ')'); } $worksheet->getStyle('B1:B' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); $worksheet->getStyle('D1:D' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log( $worksheet->getCell('B' . $row)->getFormattedValue() . ' and ' . $worksheet->getCell('C' . $row)->getFormattedValue() . ' months is ' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ' (' . $worksheet->getCell('D' . $row)->getFormattedValue() . ')' ); } ================================================ FILE: samples/DateTime/HOUR.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testTimes = [ [0, 6, 0], [1, 12, 15], [3, 30, 12], [5, 17, 31], [8, 15, 45], [12, 45, 11], [14, 0, 30], [17, 55, 50], [19, 21, 8], [21, 10, 10], [23, 59, 59], ]; $testTimeCount = count($testTimes); $worksheet->fromArray($testTimes, null, 'A1', true); for ($row = 1; $row <= $testTimeCount; ++$row) { $worksheet->setCellValue('D' . $row, '=TIME(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=HOUR(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testTimeCount) ->getNumberFormat() ->setFormatCode('hh:mm:ss'); // Test the formulae for ($row = 1; $row <= $testTimeCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('Hour is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime/ISOWEEKNUM.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 2, 14], [1936, 3, 17], [1964, 4, 29], [1999, 5, 18], [2000, 6, 21], [2019, 7, 4], [2020, 8, 31], [1956, 9, 10], [2010, 10, 10], [1982, 11, 30], [1960, 12, 19], ['=YEAR(TODAY())', '=MONTH(TODAY())', '=DAY(TODAY())'], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=ISOWEEKNUM(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('ISO Week number is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime/MINUTE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testTimes = [ [0, 6, 0], [1, 12, 15], [3, 30, 12], [5, 17, 31], [8, 15, 45], [12, 45, 11], [14, 0, 30], [17, 55, 50], [19, 21, 8], [21, 10, 10], [23, 59, 59], ]; $testTimeCount = count($testTimes); $worksheet->fromArray($testTimes, null, 'A1', true); for ($row = 1; $row <= $testTimeCount; ++$row) { $worksheet->setCellValue('D' . $row, '=TIME(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=MINUTE(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testTimeCount) ->getNumberFormat() ->setFormatCode('hh:mm:ss'); // Test the formulae for ($row = 1; $row <= $testTimeCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('Minute is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime/MONTH.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 2, 14], [1936, 3, 17], [1964, 4, 29], [1999, 5, 18], [2000, 6, 21], [2019, 7, 4], [2020, 8, 31], [1956, 9, 10], [2010, 10, 10], [1982, 11, 30], [1960, 12, 19], ['=YEAR(TODAY())', '=MONTH(TODAY())', '=DAY(TODAY())'], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=MONTH(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('Month is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime2/NETWORKDAYS.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $publicHolidays = [ [2022, 1, 3, '=DATE(G1, H1, I1)', 'New Year'], [2022, 4, 15, '=DATE(G2, H2, I2)', 'Good Friday'], [2022, 4, 18, '=DATE(G3, H3, I3)', 'Easter Monday'], [2022, 5, 2, '=DATE(G4, H4, I4)', 'Early May Bank Holiday'], [2022, 6, 2, '=DATE(G5, H5, I5)', 'Spring Bank Holiday'], [2022, 6, 3, '=DATE(G6, H6, I6)', 'Platinum Jubilee Bank Holiday'], [2022, 8, 29, '=DATE(G7, H7, I7)', 'Summer Bank Holiday'], [2022, 12, 26, '=DATE(G8, H8, I8)', 'Boxing Day'], [2022, 12, 27, '=DATE(G9, H9, I9)', 'Christmas Day'], ]; $holidayCount = count($publicHolidays); $worksheet->fromArray($publicHolidays, null, 'G1', true); $worksheet->getStyle('J1:J' . $holidayCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); $worksheet->setCellValue('A1', '=DATE(2022,1,1)'); for ($numberOfMonths = 0; $numberOfMonths < 12; ++$numberOfMonths) { $worksheet->setCellValue('B' . ($numberOfMonths + 1), '=EOMONTH(A1, ' . $numberOfMonths . ')'); $worksheet->setCellValue('C' . ($numberOfMonths + 1), '=NETWORKDAYS(A1, B' . ($numberOfMonths + 1) . ')'); $worksheet->setCellValue('D' . ($numberOfMonths + 1), '=NETWORKDAYS(A1, B' . ($numberOfMonths + 1) . ', J1:J' . $holidayCount . ')'); } $worksheet->getStyle('A1') ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); $worksheet->getStyle('B1:B12') ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae $helper->log('UK Public Holidays'); $holidayData = $worksheet->rangeToArray('J1:K' . $holidayCount, null, true, true, true); $helper->displayGrid($holidayData); for ($row = 1; $row <= 12; ++$row) { $helper->log( 'Between ' . $worksheet->getCell('A1')->getFormattedValue() . ' and ' . $worksheet->getCell('B' . $row)->getFormattedValue() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ' working days; ' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ' excluding public holidays' ); } ================================================ FILE: samples/DateTime2/NOW.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->setCellValue('A1', '=NOW()'); $worksheet->getStyle('A1') ->getNumberFormat() ->setFormatCode('yyyy-mm-dd hh:mm:ss'); // Test the formulae $helper->log( 'Today is ' . $worksheet->getCell('A1')->getCalculatedValueString() . ' (' . $worksheet->getCell('A1')->getFormattedValue() . ')' ); ================================================ FILE: samples/DateTime2/SECOND.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testTimes = [ [0, 6, 0], [1, 12, 15], [3, 30, 12], [5, 17, 31], [8, 15, 45], [12, 45, 11], [14, 0, 30], [17, 55, 50], [19, 21, 8], [21, 10, 10], [23, 59, 59], ]; $testTimeCount = count($testTimes); $worksheet->fromArray($testTimes, null, 'A1', true); for ($row = 1; $row <= $testTimeCount; ++$row) { $worksheet->setCellValue('D' . $row, '=TIME(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=SECOND(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testTimeCount) ->getNumberFormat() ->setFormatCode('hh:mm:ss'); // Test the formulae for ($row = 1; $row <= $testTimeCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('Second is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime2/TIME.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [[3, 15], [13, 15], [15, 15, 15], [3, 15, 30], [15, 15, 15], [5], [9, 15, 0], [9, 15, -1], [13, -14, -15], [0, 0, -1], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=TIME(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('hh:mm:ss'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log("(A{$row}) Hour: " . $worksheet->getCell('A' . $row)->getFormattedValue()); $helper->log("(B{$row}) Minute: " . $worksheet->getCell('B' . $row)->getFormattedValue()); $helper->log("(C{$row}) Second: " . $worksheet->getCell('C' . $row)->getFormattedValue()); $helper->log('Formula: ' . $worksheet->getCell('D' . $row)->getValueString()); $helper->log('Excel TimeStamp: ' . $worksheet->getCell('D' . $row)->getCalculatedValueString()); $helper->log('Formatted TimeStamp: ' . $worksheet->getCell('E' . $row)->getFormattedValue()); $helper->log(''); } ================================================ FILE: samples/DateTime2/TIMEVALUE.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = ['3:15', '13:15', '15:15:15', '3:15 AM', '3:15 PM', '5PM', '9:15AM', '13:15AM', ]; $testDateCount = count($testDates); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('A' . $row, $testDates[$row - 1]); $worksheet->setCellValue('B' . $row, '=TIMEVALUE(A' . $row . ')'); $worksheet->setCellValue('C' . $row, '=B' . $row); } $worksheet->getStyle('C1:C' . $testDateCount) ->getNumberFormat() ->setFormatCode('hh:mm:ss'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log("(A{$row}) Time String: " . $worksheet->getCell('A' . $row)->getFormattedValue()); $helper->log('Formula: ' . $worksheet->getCell('B' . $row)->getValueString()); $helper->log('Excel TimeStamp: ' . $worksheet->getCell('B' . $row)->getFormattedValue()); $helper->log('Formatted TimeStamp: ' . $worksheet->getCell('C' . $row)->getFormattedValue()); $helper->log(''); } ================================================ FILE: samples/DateTime2/TODAY.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->setCellValue('A1', '=TODAY()'); $worksheet->getStyle('A1') ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae $helper->log( 'Today is ' . $worksheet->getCell('A1')->getCalculatedValueString() . ' (' . $worksheet->getCell('A1')->getFormattedValue() . ')' ); ================================================ FILE: samples/DateTime2/WEEKDAY.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 2, 14], [1936, 3, 17], [1964, 4, 29], [1999, 5, 18], [2000, 6, 21], [2019, 7, 4], [2020, 8, 31], [1956, 9, 10], [2010, 10, 10], [1982, 11, 30], [1960, 12, 19], ['=YEAR(TODAY())', '=MONTH(TODAY())', '=DAY(TODAY())'], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=WEEKDAY(D' . $row . ')'); $worksheet->setCellValue('G' . $row, '=WEEKDAY(D' . $row . ', 2)'); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log( 'Weekday is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString() . ' (1-7 = Sun-Sat)' ); $helper->log( 'Weekday is: ' . $worksheet->getCell('G' . $row)->getCalculatedValueString() . ' (1-7 = Mon-Sun)' ); } ================================================ FILE: samples/DateTime2/WEEKNUM.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 2, 14], [1936, 3, 17], [1964, 4, 29], [1999, 5, 18], [2000, 6, 21], [2019, 7, 4], [2020, 8, 31], [1956, 9, 10], [2010, 10, 10], [1982, 11, 30], [1960, 12, 19], ['=YEAR(TODAY())', '=MONTH(TODAY())', '=DAY(TODAY())'], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=WEEKNUM(D' . $row . ')'); $worksheet->setCellValue('G' . $row, '=WEEKNUM(D' . $row . ', 21)'); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('System 1 Week number is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); $helper->log('System 2 (ISO-8601) Week number is: ' . $worksheet->getCell('G' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime2/WORKDAY.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $publicHolidays = [ [2022, 1, 3, '=DATE(G1, H1, I1)', 'New Year'], [2022, 4, 15, '=DATE(G2, H2, I2)', 'Good Friday'], [2022, 4, 18, '=DATE(G3, H3, I3)', 'Easter Monday'], [2022, 5, 2, '=DATE(G4, H4, I4)', 'Early May Bank Holiday'], [2022, 6, 2, '=DATE(G5, H5, I5)', 'Spring Bank Holiday'], [2022, 6, 3, '=DATE(G6, H6, I6)', 'Platinum Jubilee Bank Holiday'], [2022, 8, 29, '=DATE(G7, H7, I7)', 'Summer Bank Holiday'], [2022, 12, 26, '=DATE(G8, H8, I8)', 'Boxing Day'], [2022, 12, 27, '=DATE(G9, H9, I9)', 'Christmas Day'], ]; $holidayCount = count($publicHolidays); $worksheet->fromArray($publicHolidays, null, 'G1', true); $worksheet->getStyle('J1:J' . $holidayCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); $worksheet->setCellValue('A1', '=DATE(2022,1,1)'); $workdayStep = 10; for ($days = $workdayStep; $days <= 366; $days += $workdayStep) { $worksheet->setCellValue('B' . ((int) $days / $workdayStep + 1), $days); $worksheet->setCellValue('C' . ((int) $days / $workdayStep + 1), '=WORKDAY(A1, B' . ((int) $days / $workdayStep + 1) . ')'); $worksheet->setCellValue('D' . ((int) $days / $workdayStep + 1), '=WORKDAY(A1, B' . ((int) $days / $workdayStep + 1) . ', J1:J' . $holidayCount . ')'); } $worksheet->getStyle('A1') ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); $worksheet->getStyle('C1:D50') ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae $helper->log('UK Public Holidays'); $holidayData = $worksheet->rangeToArray('J1:K' . $holidayCount, null, true, true, true); $helper->displayGrid($holidayData); for ($days = $workdayStep; $days <= 366; $days += $workdayStep) { $helper->log(sprintf( '%d workdays from %s is %s; %s with public holidays', $worksheet->getCell('B' . ((int) $days / $workdayStep + 1))->getFormattedValue(), $worksheet->getCell('A1')->getFormattedValue(), $worksheet->getCell('C' . ((int) $days / $workdayStep + 1))->getFormattedValue(), $worksheet->getCell('D' . ((int) $days / $workdayStep + 1))->getFormattedValue() )); } ================================================ FILE: samples/DateTime2/YEAR.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 2, 14], [1936, 3, 17], [1964, 4, 29], [1999, 5, 18], [2000, 6, 21], [2019, 7, 4], [2020, 8, 31], [1956, 9, 10], [2010, 10, 10], [1982, 11, 30], [1960, 12, 19], ['=YEAR(TODAY())', '=MONTH(TODAY())', '=DAY(TODAY())'], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=YEAR(D' . $row . ')'); } $worksheet->getStyle('E1:E' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf('(E%d): %s', $row, $worksheet->getCell('E' . $row)->getFormattedValue())); $helper->log('Year is: ' . $worksheet->getCell('F' . $row)->getCalculatedValueString()); } ================================================ FILE: samples/DateTime2/YEARFRAC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testDates = [ [1900, 1, 1], [1904, 1, 1], [1936, 3, 17], [1960, 12, 19], [1999, 12, 31], [2000, 1, 1], [2019, 2, 14], [2020, 7, 4], [2020, 2, 29], [2029, 12, 31], [2525, 1, 1], ]; $testDateCount = count($testDates); $worksheet->fromArray($testDates, null, 'A1', true); for ($row = 1; $row <= $testDateCount; ++$row) { $worksheet->setCellValue('D' . $row, '=DATE(A' . $row . ',B' . $row . ',C' . $row . ')'); $worksheet->setCellValue('E' . $row, '=D' . $row); $worksheet->setCellValue('F' . $row, '=DATE(2022,12,31)'); $worksheet->setCellValue('G' . $row, '=YEARFRAC(D' . $row . ', F' . $row . ')'); $worksheet->setCellValue('H' . $row, '=YEARFRAC(D' . $row . ', F' . $row . ', 1)'); $worksheet->setCellValue('I' . $row, '=YEARFRAC(D' . $row . ', F' . $row . ', 2)'); $worksheet->setCellValue('J' . $row, '=YEARFRAC(D' . $row . ', F' . $row . ', 3)'); $worksheet->setCellValue('K' . $row, '=YEARFRAC(D' . $row . ', F' . $row . ', 4)'); } $worksheet->getStyle('E1:F' . $testDateCount) ->getNumberFormat() ->setFormatCode('yyyy-mm-dd'); // Test the formulae for ($row = 1; $row <= $testDateCount; ++$row) { $helper->log(sprintf( 'Between: %s and %s', $worksheet->getCell('E' . $row)->getFormattedValue(), $worksheet->getCell('F' . $row)->getFormattedValue() )); $helper->log( 'Days: ' . $worksheet->getCell('G' . $row)->getCalculatedValueString() . ' - US (NASD) 30/360' ); $helper->log( 'Days: ' . $worksheet->getCell('H' . $row)->getCalculatedValueString() . ' - Actual' ); $helper->log( 'Days: ' . $worksheet->getCell('I' . $row)->getCalculatedValueString() . ' - Actual/360' ); $helper->log( 'Days: ' . $worksheet->getCell('J' . $row)->getCalculatedValueString() . ' - Actual/365' ); $helper->log( 'Days: ' . $worksheet->getCell('K' . $row)->getCalculatedValueString() . ' - European 30/360' ); } ================================================ FILE: samples/DefinedNames/AbsoluteNamedRange.php ================================================ setActiveSheetIndex(0); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named range using an absolute cell reference $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", "=B{$row}*CHARGE_RATE"); ++$row; } $endRow = $row - 1; ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(B{$startRow}:B{$endRow})") ->setCellValue("C{$row}", "=SUM(C{$startRow}:C{$endRow})"); /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B1')->getValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $calc1, $value, $calc2 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/CrossWorksheetNamedFormula.php ================================================ setActiveSheetIndex(0); setYearlyData($worksheet, '2019', $data2019); $worksheet = $spreadsheet->addSheet(new Worksheet($spreadsheet)); setYearlyData($worksheet, '2020', $data2020); $worksheet = $spreadsheet->addSheet(new Worksheet($spreadsheet)); setYearlyData($worksheet, '2020', [], 'GROWTH'); /** @param array> $yearlyData */ function setYearlyData(Worksheet $worksheet, string $year, array $yearlyData, ?string $title = null): void { // Set up some basic data $worksheetTitle = $title ?: $year; $worksheet ->setTitle($worksheetTitle) ->setCellValue('A1', 'Month') ->setCellValue('B1', $worksheetTitle === 'GROWTH' ? 'Growth' : 'Sales') ->setCellValue('C1', $worksheetTitle === 'GROWTH' ? 'Profit Growth' : 'Margin') ->setCellValue('A2', Date::stringToExcel("{$year}-01-01")); for ($row = 3; $row <= 13; ++$row) { $worksheet->setCellValue("A{$row}", '=NEXT_MONTH'); } if (!empty($yearlyData)) { $worksheet->fromArray($yearlyData, null, 'B2'); } else { for ($row = 2; $row <= 13; ++$row) { $worksheet->setCellValue("B{$row}", '=GROWTH'); $worksheet->setCellValue("C{$row}", '=PROFIT_GROWTH'); } } $worksheet->getStyle('A1:C1') ->getFont()->setBold(true); $worksheet->getStyle('A2:A13') ->getNumberFormat() ->setFormatCode('mmmm'); $worksheet->getStyle('B2:C13') ->getNumberFormat() ->setFormatCode($worksheetTitle === 'GROWTH' ? '0.00%' : '_-€* #,##0_-'); } // Add some Named Formulae // The first to store our tax rate $spreadsheet->addNamedFormula(new NamedFormula('NEXT_MONTH', $worksheet, '=EDATE(OFFSET($A1,-1,0),1)')); $spreadsheet->addNamedFormula(new NamedFormula('GROWTH', $worksheet, "=IF('2020'!\$B1=\"\",\"-\",(('2020'!\$B1/'2019'!\$B1)-1))")); $spreadsheet->addNamedFormula(new NamedFormula('PROFIT_GROWTH', $worksheet, "=IF('2020'!\$C1=\"\",\"-\",(('2020'!\$C1/'2019'!\$C1)-1))")); for ($row = 2; $row <= 7; ++$row) { $month = $worksheet->getCell("A{$row}")->getFormattedValue(); $growth = $worksheet->getCell("B{$row}")->getFormattedValue(); $profitGrowth = $worksheet->getCell("C{$row}")->getFormattedValue(); $helper->log("Growth for {$month} is {$growth}, with a Profit Growth of {$profitGrowth}"); } $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/NamedFormulaeAndRanges.php ================================================ setActiveSheetIndex(0); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); // Set up the formula for calculating the daily charge $spreadsheet->addNamedFormula(new NamedFormula('DAILY_CHARGE', null, '=HOURS_PER_DAY*CHARGE_RATE')); // Set up the formula for calculating the column totals $spreadsheet->addNamedFormula(new NamedFormula('COLUMN_TOTALS', null, '=SUM(COLUMN_DATA_VALUES)')); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=DAILY_CHARGE'); ++$row; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange(new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}")); ++$row; $worksheet ->setCellValue("B{$row}", '=COLUMN_TOTALS') ->setCellValue("C{$row}", '=COLUMN_TOTALS'); /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B1')->getValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $calc1, $value, $calc2 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/RelativeNamedRange.php ================================================ setActiveSheetIndex(0); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=HOURS_PER_DAY*CHARGE_RATE'); ++$row; } $endRow = $row - 1; ++$row; $worksheet ->setCellValue("B{$row}", "=SUM(B{$startRow}:B{$endRow})") ->setCellValue("C{$row}", "=SUM(C{$startRow}:C{$endRow})"); /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B1')->getValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $calc1, $value, $calc2 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/RelativeNamedRange2.php ================================================ setActiveSheetIndex(0); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=HOURS_PER_DAY*CHARGE_RATE'); ++$row; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange(new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}")); ++$row; $worksheet ->setCellValue("B{$row}", '=SUM(COLUMN_DATA_VALUES)') ->setCellValue("C{$row}", '=SUM(COLUMN_DATA_VALUES)'); /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B1')->getValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $calc1, $value, $calc2 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/RelativeNamedRangeAsFunction.php ================================================ setActiveSheetIndex(0); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=HOURS_PER_DAY*CHARGE_RATE'); ++$row; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used // To avoid including the current row,or having to hard-code the range itself (as we did in the previous example) // we wrap it in a named formula using the OFFSET() function $spreadsheet->addNamedFormula(new NamedFormula('COLUMN_DATA_VALUES', $worksheet, '=OFFSET(A$4:A1, -1, 0)')); ++$row; $worksheet ->setCellValue("B{$row}", '=SUM(COLUMN_DATA_VALUES)') ->setCellValue("C{$row}", '=SUM(COLUMN_DATA_VALUES)'); /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B1')->getValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $calc1, $value, $calc2 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/ScopedNamedRange.php ================================================ setActiveSheetIndex(0); $worksheet->setTitle('Base Data'); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50'); // Define a global named range on the first worksheet for our Charge Rate // CHARGE_RATE is an absolute cell reference that always points to cell B1 // Because it is defined globally, it will still be usable from any worksheet in the spreadsheet $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1')); // Create a second worksheet as our client timesheet $worksheet = $spreadsheet->addSheet(new PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Client Timesheet')); // Define named ranges // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1')); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Date') ->setCellValue('B1', 'Hours') ->setCellValue('C1', 'Charge'); $workHours = [ '2020-0-06' => 7.5, '2020-0-07' => 7.25, '2020-0-08' => 6.5, '2020-0-09' => 7.0, '2020-0-10' => 5.5, ]; // Populate the Timesheet $startRow = 2; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=HOURS_PER_DAY*CHARGE_RATE'); ++$row; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange(new NamedRange('COLUMN_DATA_VALUES', $worksheet, "=A\${$startRow}:A\${$endRow}")); ++$row; $worksheet ->setCellValue("B{$row}", '=SUM(COLUMN_DATA_VALUES)') ->setCellValue("C{$row}", '=SUM(COLUMN_DATA_VALUES)'); $range = $spreadsheet->getNamedRange('CHARGE_RATE'); if ($range === null || $range->getWorksheet() === null) { throw new Exception('expected named range not found'); } /** @var string */ $cellsInRange0 = $range->getCellsInRange()[0]; /** @var float */ $chargeRateCellValue = $spreadsheet ->getSheetByNameOrThrow($range->getWorksheet()->getTitle()) ->getCell($cellsInRange0)->getValue(); /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours at a rate of %.2f - Charge to the client is %.2f', $calc1, $chargeRateCellValue, $calc2 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/ScopedNamedRange2.php ================================================ setActiveSheetIndex(0); $clients = [ 'Client #1 - Full Hourly Rate' => [ '2020-0-06' => 2.5, '2020-0-07' => 2.25, '2020-0-08' => 6.0, '2020-0-09' => 3.0, '2020-0-10' => 2.25, ], 'Client #2 - Full Hourly Rate' => [ '2020-0-06' => 1.5, '2020-0-07' => 2.75, '2020-0-08' => 0.0, '2020-0-09' => 4.5, '2020-0-10' => 3.5, ], 'Client #3 - Reduced Hourly Rate' => [ '2020-0-06' => 3.5, '2020-0-07' => 2.5, '2020-0-08' => 1.5, '2020-0-09' => 0.0, '2020-0-10' => 1.25, ], ]; foreach ($clients as $clientName => $workHours) { $worksheet = $spreadsheet->addSheet(new PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, $clientName)); // Set up some basic data for a timesheet $worksheet ->setCellValue('A1', 'Charge Rate/hour:') ->setCellValue('B1', '7.50') ->setCellValue('A3', 'Date') ->setCellValue('B3', 'Hours') ->setCellValue('C3', 'Charge'); // Define named ranges // CHARGE_RATE is an absolute cell reference that always points to cell B1 $spreadsheet->addNamedRange(new NamedRange('CHARGE_RATE', $worksheet, '=$B$1', true)); // HOURS_PER_DAY is a relative cell reference that always points to column B, but to a cell in the row where it is used $spreadsheet->addNamedRange(new NamedRange('HOURS_PER_DAY', $worksheet, '=$B1', true)); // Populate the Timesheet $startRow = 4; $row = $startRow; foreach ($workHours as $date => $hours) { $worksheet ->setCellValue("A{$row}", $date) ->setCellValue("B{$row}", $hours) ->setCellValue("C{$row}", '=HOURS_PER_DAY*CHARGE_RATE'); ++$row; } $endRow = $row - 1; // COLUMN_TOTAL is another relative cell reference that always points to the same range of rows but to cell in the column where it is used $spreadsheet->addNamedRange(new NamedRange('COLUMN_TOTAL', $worksheet, "=A\${$startRow}:A\${$endRow}", true)); ++$row; $worksheet ->setCellValue("B{$row}", '=SUM(COLUMN_TOTAL)') ->setCellValue("C{$row}", '=SUM(COLUMN_TOTAL)'); } $spreadsheet->removeSheetByIndex(0); // Set the reduced charge rate for our special client $worksheet ->setCellValue('B1', 4.5); foreach ($spreadsheet->getAllSheets() as $worksheet) { /** @var float */ $calc1 = $worksheet->getCell("B{$row}")->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B1')->getValue(); /** @var float */ $calc2 = $worksheet->getCell("C{$row}")->getCalculatedValue(); $helper->log(sprintf( 'Worked %.2f hours for "%s" at a rate of %.2f - Charge to the client is %.2f', $calc1, $worksheet->getTitle(), $value, $calc2 )); } $worksheet = $spreadsheet->setActiveSheetIndex(0); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/SimpleNamedFormula.php ================================================ setActiveSheetIndex(0); // Add some Named Formulae // The first to store our tax rate $spreadsheet->addNamedFormula(new NamedFormula('TAX_RATE', $worksheet, '=19%')); // The second to calculate the Tax on a Price value (Note that `PRICE` is defined later as a Named Range) $spreadsheet->addNamedFormula(new NamedFormula('TAX', $worksheet, '=PRICE*TAX_RATE')); // Set up some basic data $worksheet ->setCellValue('A1', 'Tax Rate:') ->setCellValue('B1', '=TAX_RATE') ->setCellValue('A3', 'Net Price:') ->setCellValue('B3', 19.99) ->setCellValue('A4', 'Tax:') ->setCellValue('A5', 'Price including Tax:'); // Define a named range that we can use in our formulae $spreadsheet->addNamedRange(new NamedRange('PRICE', $worksheet, '=$B$3')); // Reference the defined formulae in worksheet formulae $worksheet ->setCellValue('B4', '=TAX') ->setCellValue('B5', '=PRICE+TAX'); /** @var float */ $calc1 = $worksheet->getCell('B1')->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B3')->getValue(); /** @var float */ $calc2 = $worksheet->getCell('B4')->getCalculatedValue(); /** @var float */ $calc3 = $worksheet->getCell('B5')->getCalculatedValue(); $helper->log(sprintf( 'With a Tax Rate of %.2f and a net price of %.2f, Tax is %.2f and the gross price is %.2f', $calc1, $value, $calc2, $calc3 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/DefinedNames/SimpleNamedRange.php ================================================ setActiveSheetIndex(0); // Set up some basic data $worksheet ->setCellValue('A1', 'Tax Rate:') ->setCellValue('B1', '=19%') ->setCellValue('A3', 'Net Price:') ->setCellValue('B3', 12.99) ->setCellValue('A4', 'Tax:') ->setCellValue('A5', 'Price including Tax:'); // Define named ranges $spreadsheet->addNamedRange(new NamedRange('TAX_RATE', $worksheet, '=$B$1')); $spreadsheet->addNamedRange(new NamedRange('PRICE', $worksheet, '=$B$3')); // Reference that defined name in a formula $worksheet ->setCellValue('B4', '=PRICE*TAX_RATE') ->setCellValue('B5', '=PRICE*(1+TAX_RATE)'); /** @var float */ $calc1 = $worksheet->getCell('B1')->getCalculatedValue(); /** @var float */ $value = $worksheet->getCell('B3')->getValue(); /** @var float */ $calc2 = $worksheet->getCell('B4')->getCalculatedValue(); /** @var float */ $calc3 = $worksheet->getCell('B5')->getCalculatedValue(); $helper->log(sprintf( 'With a Tax Rate of %.2f and a net price of %.2f, Tax is %.2f and the gross price is %.2f', $calc1, $value, $calc2, $calc3 )); $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Engineering/BESSELI.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); for ($n = 0; $n <= 5; ++$n) { for ($x = 0; $x <= 5; $x = $x + 0.25) { Calculation::getInstance($spreadsheet)->flushInstance(); $formula = "BESSELI({$x}, {$n})"; $worksheet->setCellValue('A1', "=$formula"); $helper->log("$formula = " . $worksheet->getCell('A1')->getCalculatedValueString()); } } ================================================ FILE: samples/Engineering/BESSELJ.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); for ($n = 0; $n <= 5; ++$n) { for ($x = 0; $x <= 5; $x = $x + 0.25) { Calculation::getInstance($spreadsheet)->flushInstance(); $formula = "BESSELJ({$x}, {$n})"; $worksheet->setCellValue('A1', "=$formula"); $helper->log("$formula = " . $worksheet->getCell('A1')->getCalculatedValueString()); } } ================================================ FILE: samples/Engineering/BESSELK.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); for ($n = 0; $n <= 5; ++$n) { for ($x = 0; $x <= 5; $x = $x + 0.25) { Calculation::getInstance($spreadsheet)->flushInstance(); $formula = "BESSELK({$x}, {$n})"; $worksheet->setCellValue('A1', "=$formula"); $helper->log("$formula = " . $worksheet->getCell('A1')->getCalculatedValueString()); } } ================================================ FILE: samples/Engineering/BESSELY.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); for ($n = 0; $n <= 5; ++$n) { for ($x = 0; $x <= 5; $x = $x + 0.25) { Calculation::getInstance($spreadsheet)->flushInstance(); $formula = "BESSELY({$x}, {$n})"; $worksheet->setCellValue('A1', "=$formula"); $helper->log("$formula = " . $worksheet->getCell('A1')->getCalculatedValueString()); } } ================================================ FILE: samples/Engineering/CONVERT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $conversions = [ [1, 'lbm', 'kg'], [1, 'gal', 'l'], [24, 'in', 'ft'], [100, 'yd', 'm'], [500, 'mi', 'km'], [7.5, 'min', 'sec'], [5, 'F', 'C'], [32, 'C', 'K'], [100, 'm2', 'ft2'], ]; $testDataCount = count($conversions); $worksheet->fromArray($conversions, null, 'A1'); for ($row = 1; $row <= $testDataCount; ++$row) { $data = $conversions[$row - 1]; $worksheet->setCellValue("D$row", "=CONVERT({$data[0]},\"{$data[1]}\",\"{$data[2]}\")"); } $worksheet->setCellValue('H1', '=CONVERT(CONVERT(100,"m","ft"),"m","ft")'); for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(A$row): Unit of Measure Conversion Formula " . $worksheet->getCell('D' . $row)->getValueString() . ' - ' . $worksheet->getCell('A' . $row)->getValueString() . ' ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('D' . $row)->getCalculatedValueString() . ' ' . $worksheet->getCell('C' . $row)->getValueString() ); } $helper->log('Old method for area conversions, before MS Excel introduced area Units of Measure'); $helper->log( "(A$row): Unit of Measure Conversion Formula " . $worksheet->getCell('H1')->getValueString() . ' result is ' . $worksheet->getCell('H1')->getCalculatedValueString() ); ================================================ FILE: samples/Engineering/Convert-Online.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } $post = []; foreach (['category', 'quantity', 'fromUnit', 'toUnit'] as $value) { if (isset($_POST[$value])) { $post[$value] = StringHelper::convertToString($_POST[$value]); } } $categories = ConvertUOM::getConversionCategories(); $defaultCategory = $post['category'] ?? $categories[0]; $units = []; foreach ($categories as $category) { $categoryUnits = ConvertUOM::getConversionCategoryUnitDetails($category)[$category]; $categoryUnits = array_unique( array_combine( array_column($categoryUnits, 'unit'), array_column($categoryUnits, 'description') ) ); $units[$category] = $categoryUnits; } ?>

log('Quantity is not numeric'); } elseif (isset($units[$post['category']][$fromUnit], $units[$post['category']][$toUnit])) { /** @var float|string */ $result = ConvertUOM::CONVERT($quantity, $fromUnit, $toUnit); $helper->log("{$quantity} {$units[$post['category']][$fromUnit]} is {$result} {$units[$post['category']][$toUnit]}"); } else { $helper->log('Please enter quantity and select From Unit and To Unit'); } } else { $helper->log('Please enter quantity and select From Unit and To Unit'); } ================================================ FILE: samples/Engineering/DELTA.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [4, 5], [3, 3], [0.5, 0], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=DELTA(A' . $row . ',B' . $row . ')'); } $comparison = [ 0 => 'The values are not equal', 1 => 'The values are equal', ]; // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): Compare values " . $worksheet->getCell('A' . $row)->getValueString() . ' and ' . $worksheet->getCell('B' . $row)->getValueString() . ' - Result is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() . ' - ' . $comparison[$worksheet->getCell('C' . $row)->getCalculatedValueString()] ); } ================================================ FILE: samples/Engineering/ERF.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData1 = [ [0.745], [1], [1.5], [-2], ]; $testData2 = [ [0, 1.5], [1, 2], [-2, 1], ]; $testDataCount1 = count($testData1); $testDataCount2 = count($testData2); $testData2StartRow = $testDataCount1 + 1; $worksheet->fromArray($testData1, null, 'A1', true); $worksheet->fromArray($testData2, null, "A{$testData2StartRow}", true); for ($row = 1; $row <= $testDataCount1; ++$row) { $worksheet->setCellValue('C' . $row, '=ERF(A' . $row . ')'); } for ($row = $testDataCount1 + 1; $row <= $testDataCount2 + $testDataCount1; ++$row) { $worksheet->setCellValue('C' . $row, '=ERF(A' . $row . ', B' . $row . ')'); } // Test the formulae $helper->log('ERF() With a single argument'); for ($row = 1; $row <= $testDataCount1; ++$row) { $helper->log( "(C$row): " . $worksheet->getCell('C' . $row)->getValueString() . ' The error function integrated between 0 and ' . $worksheet->getCell('A' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } $helper->log('ERF() With two arguments'); for ($row = $testDataCount1 + 1; $row <= $testDataCount2 + $testDataCount1; ++$row) { $helper->log( "(C$row): " . $worksheet->getCell('C' . $row)->getValueString() . ' The error function integrated between ' . $worksheet->getCell('A' . $row)->getValueString() . ' and ' . $worksheet->getCell('B' . $row)->getValueString() . ' is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/Engineering/ERFC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [0], [0.5], [1], [-1], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=ERFC(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(E$row): " . $worksheet->getCell('C' . $row)->getValueString() . ' The complementary error function integrated by ' . $worksheet->getCell('A' . $row)->getValueString() . ' and infinity is ' . $worksheet->getCell('C' . $row)->getCalculatedValueString() ); } ================================================ FILE: samples/Engineering/GESTEP.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [5, 4], [5, 5], [4, 5], [-4, -5], [-5, -4], [1], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('C' . $row, '=GESTEP(A' . $row . ',B' . $row . ')'); } $comparison = [ 0 => 'Value %d is less than step %d', 1 => 'Value %d is greater than or equal to step %d', ]; // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { /** @var int */ $aValue = $worksheet->getCell('A' . $row)->getValue(); /** @var int */ $bValue = $worksheet->getCell('B' . $row)->getValue(); /** @var int */ $cValue = $worksheet->getCell('C' . $row)->getCalculatedValue(); $helper->log(sprintf( '(E%d): Compare value %d and step %d - Result is %d - %s', $row, $aValue, $bValue, $cValue, sprintf( $comparison[$cValue], $aValue, $bValue, ) )); } ================================================ FILE: samples/Financial1/ACCRINT.php ================================================ log('Returns the accrued interest for a security that pays periodic interest.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Issue Date', DateHelper::getDateValue('01-Jan-2012')], ['First Interest Date', DateHelper::getDateValue('01-Apr-2012')], ['Settlement Date', DateHelper::getDateValue('31-Dec-2013')], ['Annual Coupon Rate', 0.08], ['Par Value', 10000], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B3')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B5')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $worksheet->setCellValue('B10', '=ACCRINT(B1, B2, B3, B4, B5, B6)'); $worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B10')->getValue()); $helper->log('ACCRINT() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); ================================================ FILE: samples/Financial1/ACCRINTM.php ================================================ log('Returns the accrued interest for a security that pays interest at maturity.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Issue Date', DateHelper::getDateValue('01-Jan-2012')], ['Settlement Date', DateHelper::getDateValue('31-Dec-2012')], ['Annual Coupon Rate', 0.08], ['Par Value', 10000], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $worksheet->setCellValue('B6', '=ACCRINTM(B1, B2, B3, B4)'); $worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('ACCRINTM() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/AMORDEGRC.php ================================================ log('Returns the prorated linear depreciation of an asset for a specified accounting period.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Cost', 150.00], ['Date Purchased', DateHelper::getDateValue('01-Jan-2015')], ['First Period Date', DateHelper::getDateValue('30-Sep-2015')], ['Salvage Value', 20.00], ['Number of Periods', 1], ['Depreciation Rate', 0.20], ['Basis', FinancialConstants::BASIS_DAYS_PER_YEAR_360_EUROPEAN], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('$#,##0.00'); $worksheet->getStyle('B2:B3')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('$#,##0.00'); $worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('0.00%'); // Now the formula $worksheet->setCellValue('B10', '=AMORDEGRC(B1, B2, B3, B4, B5, B6, B7)'); $worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B10')->getValue()); $helper->log('AMORDEGRC() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); ================================================ FILE: samples/Financial1/AMORLINC.php ================================================ log('Returns the prorated linear depreciation of an asset for a specified accounting period.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Cost', 150.00], ['Date Purchased', DateHelper::getDateValue('01-Jan-2015')], ['First Period Date', DateHelper::getDateValue('30-Sep-2015')], ['Salvage Value', 20.00], ['Period', 1], ['Depreciation Rate', 0.20], ['Basis', FinancialConstants::BASIS_DAYS_PER_YEAR_360_EUROPEAN], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('$#,##0.00'); $worksheet->getStyle('B2:B3')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('$#,##0.00'); $worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('0.00%'); // Now the formula $worksheet->setCellValue('B10', '=AMORLINC(B1, B2, B3, B4, B5, B6, B7)'); $worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B10')->getValue()); $helper->log('AMORLINC() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); ================================================ FILE: samples/Financial1/COUPDAYBS.php ================================================ log('Returns the number of days from the beginning of a coupon\'s period to the settlement date.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); // Now the formula $worksheet->setCellValue('B6', '=COUPDAYBS(B1, B2, B3)'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('COUPDAYBS() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/COUPDAYS.php ================================================ log('Returns the number of days in the coupon period that contains the settlement date.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); // Now the formula $worksheet->setCellValue('B6', '=COUPDAYS(B1, B2, B3)'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('COUPDAYS() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/COUPDAYSNC.php ================================================ log('Returns the number of days from the settlement date to the next coupon date.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); // Now the formula $worksheet->setCellValue('B6', '=COUPDAYSNC(B1, B2, B3)'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('COUPDAYSNC() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/COUPNCD.php ================================================ log('Returns the next coupon date, after the settlement date.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); // Now the formula $worksheet->setCellValue('B6', '=COUPNCD(B1, B2, B3)'); $worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('COUPNCD() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/COUPNUM.php ================================================ log('Returns the number of coupons payable, between a security\'s settlement date and maturity date,'); $helper->log('rounded up to the nearest whole coupon.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); // Now the formula $worksheet->setCellValue('B6', '=COUPNUM(B1, B2, B3)'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('COUPNUM() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/COUPPCD.php ================================================ log('Returns the previous coupon date, before the settlement date for a security.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], ['Frequency', 4], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); // Now the formula $worksheet->setCellValue('B6', '=COUPPCD(B1, B2, B3)'); $worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $helper->log($worksheet->getCell('B6')->getValue()); $helper->log('COUPPCD() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); ================================================ FILE: samples/Financial1/CUMIPMT.php ================================================ log('Returns the cumulative interest paid on a loan or investment, between two specified periods.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Interest Rate (per period)', 0.05 / 12], ['Number of Periods', 5 * 12], ['Present Value', 50000], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $baseRow = 5; for ($year = 1; $year <= 5; ++$year) { $row = (string) ($baseRow + $year); $yearStartPeriod = (int) $year * 12 - 11; $yearEndPeriod = (int) $year * 12; $worksheet->setCellValue("A{$row}", "Yr {$year}"); $worksheet->setCellValue("B{$row}", "=CUMIPMT(\$B\$1, \$B\$2, \$B\$3, {$yearStartPeriod}, {$yearEndPeriod}, 0)"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("CUMIPMT() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial1/CUMPRINC.php ================================================ log('Returns the cumulative payment on the principal of a loan or investment, between two specified periods.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Interest Rate (per period)', 0.05 / 12], ['Number of Periods', 5 * 12], ['Present Value', 50000], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $baseRow = 5; for ($year = 1; $year <= 5; ++$year) { $row = (string) ($baseRow + $year); $yearStartPeriod = (int) $year * 12 - 11; $yearEndPeriod = (int) $year * 12; $worksheet->setCellValue("A{$row}", "Yr {$year}"); $worksheet->setCellValue("B{$row}", "=CUMPRINC(\$B\$1, \$B\$2, \$B\$3, {$yearStartPeriod}, {$yearEndPeriod}, 0)"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("CUMPRINC() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial2/DB.php ================================================ log('Returns the depreciation of an asset, using the Fixed Declining Balance Method,'); $helper->log('for each period of the asset\'s lifetime.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Cost Value', 10000], ['Salvage', 1000], ['Life', 5, 'Years'], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $baseRow = 5; for ($year = 1; $year <= 5; ++$year) { $row = (string) ($baseRow + $year); $worksheet->setCellValue("A{$row}", "Depreciation after Yr {$year}"); $worksheet->setCellValue("B{$row}", "=DB(\$B\$1, \$B\$2, \$B\$3, {$year})"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("DB() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } $helper->log('And with depreciation only starting after 6 months.'); $baseRow = 12; for ($year = 1; $year <= 6; ++$year) { $row = (string) ($baseRow + $year); $worksheet->setCellValue("A{$row}", "Depreciation after Yr {$year}"); $worksheet->setCellValue("B{$row}", "=DB(\$B\$1, \$B\$2, \$B\$3, {$year}, 6)"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("DB() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial2/DDB.php ================================================ log('Returns the depreciation of an asset, using the Double Declining Balance Method,'); $helper->log('for each period of the asset\'s lifetime.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Cost Value', 10000], ['Salvage', 1000], ['Life', 5, 'Years'], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $baseRow = 5; for ($year = 1; $year <= 5; ++$year) { $row = (string) ($baseRow + $year); $worksheet->setCellValue("A{$row}", "Depreciation after Yr {$year}"); $worksheet->setCellValue("B{$row}", "=DDB(\$B\$1, \$B\$2, \$B\$3, {$year})"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("DDB() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial2/DISC.php ================================================ log('Returns the Discount Rate for a security.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Apr-2016')], ['Maturity Date', DateHelper::getDateValue('31-Mar-2021')], ['Par Value', 95.00], ['Redemption Value', 100.00], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $worksheet->getStyle('B3:B4')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $worksheet->setCellValue('B7', '=DISC(B1, B2, B3, B4)'); $worksheet->getStyle('B7')->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell('B7')->getValue()); $helper->log('DISC() Result is ' . $worksheet->getCell('B7')->getFormattedValue()); ================================================ FILE: samples/Financial2/DOLLARDE.php ================================================ log('Returns the dollar value in fractional notation, into a dollar value expressed as a decimal.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ [1.01, 16], [1.1, 16], [1.03, 32], [1.3, 32], [1.12, 32], ]; $worksheet->fromArray($arguments, null, 'A1'); // Now the formula for ($row = 1; $row <= 5; ++$row) { $worksheet->setCellValue("C{$row}", "=DOLLARDE(A{$row}, B{$row})"); $helper->log($worksheet->getCell("C{$row}")->getValue()); $helper->log('DOLLARDE() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial2/DOLLARFR.php ================================================ log('Returns the dollar value expressed as a decimal number, into a dollar price, expressed as a fraction.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ [1.0625, 16], [1.625, 16], [1.09375, 32], [1.9375, 32], [1.375, 32], ]; $worksheet->fromArray($arguments, null, 'A1'); // Now the formula for ($row = 1; $row <= 5; ++$row) { $worksheet->setCellValue("C{$row}", "=DOLLARFR(A{$row}, B{$row})"); $helper->log($worksheet->getCell("C{$row}")->getValue()); $helper->log('DOLLARFR() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial2/EFFECT.php ================================================ log('Returns the effective annual interest rate for a given nominal interest rate and number of'); $helper->log('compounding periods per year.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ [0.10, 4], [0.10, 2], [0.025, 2], ]; $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B3')->getNumberFormat()->setFormatCode('0.00%'); // Now the formula for ($row = 1; $row <= 3; ++$row) { $worksheet->setCellValue("C{$row}", "=EFFECT(A{$row}, B{$row})"); $worksheet->getStyle("C{$row}")->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell("C{$row}")->getValue()); $helper->log('EFFECT() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial2/FV.php ================================================ log('Returns the Future Value of an investment with periodic constant payments and a constant interest rate.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Interest Rate', 0.05, 0.10], ['Pament Frequency', 12, 4], ['Duration (Years)', 5, 4], ['Investment', -1000.00, -2000.00], ['Payment Type', 0, 1], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B4:C4')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $worksheet->setCellValue('B8', '=FV(B1/B2, B3*B2, B4)'); $worksheet->setCellValue('C8', '=FV(C1/C2, C3*C2, C4, null, C5)'); $worksheet->getStyle('B8:C8')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B8')->getValue()); $helper->log('FV() Result is ' . $worksheet->getCell('B8')->getFormattedValue()); $helper->log($worksheet->getCell('C8')->getValue()); $helper->log('FV() Result is ' . $worksheet->getCell('C8')->getFormattedValue()); ================================================ FILE: samples/Financial2/FVSCHEDULE.php ================================================ log('Returns the Future Value of an initial principal, after applying a series of compound interest rates.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Principal'], [10000.00], [null], ['Schedule'], [0.05], [0.05], [0.035], [0.035], [0.035], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('A2')->getNumberFormat()->setFormatCode('$#,##0.00'); $worksheet->getStyle('A5:A9')->getNumberFormat()->setFormatCode('0.00%'); // Now the formula $worksheet->setCellValue('B1', '=FVSCHEDULE(A2, A5:A9)'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B1')->getValue()); $helper->log('FVSCHEDULE() Result is ' . $worksheet->getCell('B1')->getFormattedValue()); ================================================ FILE: samples/Financial3/INTRATE.php ================================================ log('Returns the interest rate for a fully invested security.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Settlement Date', DateHelper::getDateValue('01-Apr-2005')], ['Maturity Date', DateHelper::getDateValue('31-Mar-2010')], ['Investment', 1000.00], ['Investment', 2125.00], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); $worksheet->getStyle('B3:B4')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $worksheet->setCellValue('B7', '=INTRATE(B1, B2, B3, B4)'); $worksheet->getStyle('B7')->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell('B7')->getValue()); $helper->log('INTRATE() Result is ' . $worksheet->getCell('B7')->getFormattedValue()); ================================================ FILE: samples/Financial3/IPMT.php ================================================ log('Returns the interest payment, during a specific period of a loan or investment that is paid in,'); $helper->log('constant periodic payments, with a constant interest rate.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Interest Rate', 0.05], ['Number of Years', 5], ['Present Value', 50000.00], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $baseRow = 6; for ($month = 1; $month <= 12; ++$month) { $row = (string) ($baseRow + $month); $worksheet->setCellValue("A{$row}", "Payment for Mth {$month}"); $worksheet->setCellValue("B{$row}", "=IPMT(\$B\$1/12, {$month}, \$B\$2*12, \$B\$3)"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("IPMT() Month {$month} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial3/IRR.php ================================================ log('Returns the Internal Rate of Return for a supplied series of periodic cash flows.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Initial Investment', -100.00], ['Year 1 Income', 20.00], ['Year 2 Income', 24.00, 'IRR after 3 Years'], ['Year 3 Income', 28.80], ['Year 4 Income', 34.56, 'IRR after 5 Years'], ['Year 5 Income', 41.47], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B6')->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); // Now the formula $worksheet->setCellValue('C4', '=IRR(B1:B4)'); $worksheet->getStyle('C4')->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell('C4')->getValue()); $helper->log('IRR() Result is ' . $worksheet->getCell('C4')->getFormattedValue()); $worksheet->setCellValue('C6', '=IRR(B1:B6)'); $worksheet->getStyle('C6')->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell('C6')->getValue()); $helper->log('IRR() Result is ' . $worksheet->getCell('C6')->getFormattedValue()); ================================================ FILE: samples/Financial3/ISPMT.php ================================================ log('Returns the interest paid during a specific period of a loan or investment.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Interest Rate', 0.05], ['Number of Years', 5], ['Present Value', 50000.00], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $baseRow = 6; for ($month = 1; $month <= 12; ++$month) { $row = (string) ($baseRow + $month); $worksheet->setCellValue("A{$row}", "Payment for Mth {$month}"); $worksheet->setCellValue("B{$row}", "=ISPMT(\$B\$1/12, {$month}, \$B\$2*12, \$B\$3)"); $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $helper->log($worksheet->getCell("B{$row}")->getValue()); $helper->log("ISPMT() Month {$month} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial3/MIRR.php ================================================ log('Returns the Modified Internal Rate of Return for a supplied series of periodic cash flows.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Initial Investment', -100.00], ['Year 1 Income', 18.00], ['Year 2 Income', 22.50, 'MIRR after 3 Years'], ['Year 3 Income', 28.00], ['Year 4 Income', 35.50, 'MIRR after 5 Years'], ['Year 5 Income', 45.00], [null], ['Finance Rate', 0.055], ['Re-invest Rate', 0.05], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B6')->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); $worksheet->getStyle('B8:B9')->getNumberFormat()->setFormatCode('0.00%'); // Now the formula $worksheet->setCellValue('C4', '=MIRR(B1:B4, B8, B9)'); $worksheet->getStyle('C4')->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell('C4')->getValue()); $helper->log('MIRR() Result is ' . $worksheet->getCell('C4')->getFormattedValue()); $worksheet->setCellValue('C6', '=MIRR(B1:B6, B8, B9)'); $worksheet->getStyle('C6')->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell('C6')->getValue()); $helper->log('MIRR() Result is ' . $worksheet->getCell('C6')->getFormattedValue()); ================================================ FILE: samples/Financial3/NOMINAL.php ================================================ log('Returns the nominal interest rate for a given effective interest rate and number of'); $helper->log('compounding periods per year.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ [0.10, 4], [0.10, 2], [0.025, 12], ]; $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:B3')->getNumberFormat()->setFormatCode('0.00%'); // Now the formula for ($row = 1; $row <= 3; ++$row) { $worksheet->setCellValue("C{$row}", "=NOMINAL(A{$row}, B{$row})"); $worksheet->getStyle("C{$row}")->getNumberFormat()->setFormatCode('0.00%'); $helper->log($worksheet->getCell("C{$row}")->getValue()); $helper->log('NOMINAL() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); } ================================================ FILE: samples/Financial3/NPER.php ================================================ log('Returns the number of periods required to pay off a loan, for a constant periodic payment'); $helper->log('and a constant interest rate.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Interest Rate', 0.04, 0.06], ['Payments per Year', 1, 4], ['Payment Amount', -6000.00, -2000], ['Present Value', 50000, 60000], ['Future Value', null, 30000], ['Payment Type', null, FinancialConstants::PAYMENT_BEGINNING_OF_PERIOD], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B3:C5')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula $worksheet->setCellValue('B8', '=NPER(B1/B2, B3, B4)'); $helper->log($worksheet->getCell('B8')->getValue()); $helper->log('NPER() Result is ' . $worksheet->getCell('B8')->getFormattedValue()); $worksheet->setCellValue('C8', '=NPER(C1/C2, C3, C4, C5, C6)'); $helper->log($worksheet->getCell('C8')->getValue()); $helper->log('NPER() Result is ' . $worksheet->getCell('C8')->getFormattedValue()); ================================================ FILE: samples/Financial3/NPV.php ================================================ log('Returns the Net Present Value of an investment, based on a supplied discount rate,'); $helper->log('and a series of future payments and income.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $arguments = [ ['Annual Discount Rate', 0.02, 0.05], ['Initial Investment Cost', -5000.00, -10000], ['Return from Year 1', 800.00, 2000.00], ['Return from Year 2', 950.00, 2400.00], ['Return from Year 3', 1080.00, 2900.00], ['Return from Year 4', 1220.00, 3500.00], ['Return from Year 5', 1500.00, 4100.00], ]; // Some basic formatting for the data $worksheet->fromArray($arguments, null, 'A1'); $worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%'); $worksheet->getStyle('B2:C7')->getNumberFormat()->setFormatCode('$#,##0.00'); // Now the formula // When initial investment is made at the end of the first period $worksheet->setCellValue('B10', '=NPV(B1, B2:B7)'); $worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('B10')->getValue()); $helper->log('NPV() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); // When initial investment is made at the start of the first period $worksheet->setCellValue('C10', '=NPV(C1, C3:C7) + C2'); $worksheet->getStyle('C10')->getNumberFormat()->setFormatCode('$#,##0.00'); $helper->log($worksheet->getCell('C10')->getValue()); $helper->log('NPV() Result is ' . $worksheet->getCell('C10')->getFormattedValue()); ================================================ FILE: samples/Header.php ================================================ isCli()) { return; } ?> <?php echo $helper->getPageTitle(); ?>
getPageHeading(); ================================================ FILE: samples/HexEtcConversions/BIN2DEC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [101], [110110], [1000000], [11111111], [100010101], [110001100], [111111111], [1111111111], [1100110011], [1000000000], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=BIN2DEC(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Binary ' . $worksheet->getCell("A$row")->getValueString() . ' is decimal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/BIN2HEX.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [101], [110110], [1000000], [11111111], [100010101], [110001100], [111111111], [1111111111], [1100110011], [1000000000], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=BIN2HEX(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Binary ' . $worksheet->getCell("A$row")->getValueString() . ' is hexadecimal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/BIN2OCT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [101], [110110], [1000000], [11111111], [100010101], [110001100], [111111111], [1111111111], [1100110011], [1000000000], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=BIN2OCT(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Binary ' . $worksheet->getCell("A$row")->getValueString() . ' is octal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/DEC2BIN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [-255], [-123], [-15], [-1], [5], [7], [19], [51], [121], [256], [511], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=DEC2BIN(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Decimal ' . $worksheet->getCell("A$row")->getValueString() . ' is binary ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/DEC2HEX.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [-255], [-123], [-15], [-1], [5], [7], [19], [51], [121], [256], [511], [12345678], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=DEC2HEX(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Decimal ' . $worksheet->getCell("A$row")->getValueString() . ' is hexadecimal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/DEC2OCT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [-255], [-123], [-15], [-1], [5], [7], [19], [51], [121], [256], [511], [12345678], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=DEC2OCT(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Decimal ' . $worksheet->getCell("A$row")->getValueString() . ' is octal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/HEX2BIN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [3], [8], [42], [99], ['A2'], ['F0'], ['100'], ['128'], ['1AB'], ['1FF'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=HEX2BIN(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Hexadecimal ' . $worksheet->getCell("A$row")->getValueString() . ' is binary ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/HEX2DEC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['08'], ['42'], ['A2'], ['400'], ['1000'], ['1234'], ['ABCD'], ['C3B0'], ['FFFFFFFFF'], ['FFFFFFFFFF'], ['FFFFFFF800'], ['FEDCBA9876'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=HEX2DEC(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Hexadecimal ' . $worksheet->getCell("A$row")->getValueString() . ' is decimal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/HEX2OCT.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ ['08'], ['42'], ['A2'], ['400'], ['100'], ['1234'], ['ABCD'], ['C3B0'], ['FFFFFFFFFF'], ['FFFFFFF800'], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=HEX2OCT(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Hexadecimal ' . $worksheet->getCell("A$row")->getValueString() . ' is octal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/OCT2BIN.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [3], [7], [42], [70], [72], [77], [100], [127], [177], [456], [567], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=OCT2BIN(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Octal ' . $worksheet->getCell("A$row")->getValueString() . ' is binary ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/OCT2DEC.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [3], [7], [42], [70], [72], [77], [100], [127], [177], [456], [4567], [7777700001], [7777776543], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=OCT2DEC(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Octal ' . $worksheet->getCell("A$row")->getValueString() . ' is decimal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/HexEtcConversions/OCT2HEX.php ================================================ titles($category, $functionName, $description); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Add some data $testData = [ [3], [12], [42], [70], [72], [77], [100], [127], [177], [456], [4567], [7777700001], [7777776543], ]; $testDataCount = count($testData); $worksheet->fromArray($testData, null, 'A1', true); for ($row = 1; $row <= $testDataCount; ++$row) { $worksheet->setCellValue('B' . $row, '=OCT2HEX(A' . $row . ')'); } // Test the formulae for ($row = 1; $row <= $testDataCount; ++$row) { $helper->log( "(B$row): " . 'Octal ' . $worksheet->getCell("A$row")->getValueString() . ' is hexadecimal ' . $worksheet->getCell("B$row")->getCalculatedValueString() ); } ================================================ FILE: samples/Html/html_01_Basic_Conditional_Formatting.php ================================================ isCli() ? ('samples/templates/' . $inputFileName) : ('' . 'samples/templates/' . $inputFileName . ''); $helper->log('Read ' . $codePath . ' with conditional formatting'); $reader = IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(false); $spreadsheet = $reader->load($inputFilePath); $helper->log('Enable conditional formatting output'); function writerCallback(HtmlWriter $writer): void { $writer->setPreCalculateFormulas(true); $writer->setConditionalFormatting(true); } // Save $helper->write($spreadsheet, __FILE__, ['Html'], false, writerCallback: writerCallback(...)); ================================================ FILE: samples/Html/html_02_More_Conditional_Formatting.php ================================================ isCli() ? ('samples/templates/' . $inputFileName) : ('' . 'samples/templates/' . $inputFileName . ''); $helper->log('Read ' . $codePath . ' with conditional formatting'); $reader = IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(false); $spreadsheet = $reader->load($inputFilePath); $helper->log('Enable conditional formatting output'); function writerCallback(HtmlWriter $writer): void { $writer->setPreCalculateFormulas(true); $writer->setConditionalFormatting(true); } // Save $helper->write($spreadsheet, __FILE__, ['Html'], false, writerCallback: writerCallback(...)); ================================================ FILE: samples/Html/html_03_Color_Scale.php ================================================ isCli() ? ('samples/templates/' . $inputFileName) : ('' . 'samples/templates/' . $inputFileName . ''); $helper->log('Read ' . $codePath . ' with color scale'); $reader = IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(false); $spreadsheet = $reader->load($inputFilePath); $helper->log('Enable conditional formatting output'); function writerCallback(HtmlWriter $writer): void { $writer->setPreCalculateFormulas(true); $writer->setConditionalFormatting(true); } // Save $helper->write($spreadsheet, __FILE__, ['Html'], false, writerCallback: writerCallback(...)); ================================================ FILE: samples/Html/html_04_Table_Format_without_Conditional.php ================================================ isCli() ? ('samples/templates/' . $inputFileName) : ('' . 'samples/templates/' . $inputFileName . ''); $helper->log('Read ' . $codePath); $reader = IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(false); $spreadsheet = $reader->load($inputFilePath); $helper->log('Enable table formatting output'); function writerCallback(HtmlWriter $writer): void { $writer->setPreCalculateFormulas(true); $writer->setTableFormats(true); } // Save $helper->write($spreadsheet, __FILE__, ['Html'], false, writerCallback: writerCallback(...)); ================================================ FILE: samples/Html/html_05_Table_Format_with_Conditional.php ================================================ isCli() ? ('samples/templates/' . $inputFileName) : ('' . 'samples/templates/' . $inputFileName . ''); $helper->log('Read ' . $codePath); $reader = IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(false); $spreadsheet = $reader->load($inputFilePath); $helper->log('Enable table formatting output'); $helper->log('Enable conditional formatting output'); function writerCallback(HtmlWriter $writer): void { $writer->setPreCalculateFormulas(true); $writer->setTableFormats(true); $writer->setConditionalFormatting(true); } // Save $helper->write($spreadsheet, __FILE__, ['Html'], false, writerCallback: writerCallback(...)); ================================================ FILE: samples/Html/html_06_Table_Cellspacing.php ================================================ log('Emulate table border, cellspacing, cellpadding attributes'); function addCellspacing(string $html): string { return str_replace( 'table { border-collapse:collapse }', 'table { border-collapse:separate; border-spacing: 5px; }' . "\ntable.sheet0 {border: 1px solid red}" . "\ntd, th {padding: 3px}", $html ); } function writerCallback(HtmlWriter $writer): void { $writer->setLineEnding("\n") ->writeAllSheets() ->setEditHtmlCallback(addCellspacing(...)); } $spreadsheet = new Spreadsheet(); $helper->log('Sheet1 will have no borders inside, red border outside from callback'); $sheet1 = $spreadsheet->getActiveSheet(); $sheet1->setTitle('Sheet1'); $sheet1->setShowGridlines(false); $sheet1->setPrintGridlines(false); $sheet1->fromArray([ [11, 12, 13], [14, 15, 16], ]); $helper->log('Sheet2 will have no borders (display), separate borders (print) from callback'); $sheet2 = $spreadsheet->createSheet(); $sheet2->setTitle('Sheet2'); $sheet2->setShowGridlines(false); $sheet2->setPrintGridlines(true); $sheet2->fromArray([ [21, 22, 23], [24, 25, 26], ]); $helper->log('Sheet3 will have no borders (print), separate borders (display) from callback'); $sheet3 = $spreadsheet->createSheet(); $sheet3->setTitle('Sheet3'); $sheet3->setShowGridlines(true); $sheet3->setPrintGridlines(false); $sheet3->fromArray([ [31, 32, 33], [34, 35, 36], ]); $helper->log('Sheet4 will have separate borders (print and display) from callback'); $sheet4 = $spreadsheet->createSheet(); $sheet4->setTitle('Sheet4'); $sheet4->setShowGridlines(true); $sheet4->setPrintGridlines(true); $sheet4->fromArray([ [41, 42, 43], [44, 45, 46], ]); $helper->log('Auto-size column dimensions'); foreach ([$sheet1, $sheet2, $sheet3, $sheet4] as $sheet) { $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); $sheet->getColumnDimension('C')->setAutoSize(true); } // Save $helper->write($spreadsheet, __FILE__, ['Html'], false, writerCallback: writerCallback(...)); ================================================ FILE: samples/LookupRef/ADDRESS.php ================================================ log('Returns a text reference to a single cell in a worksheet.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('=ADDRESS(2,3)'); $worksheet->getCell('A2')->setValue('=ADDRESS(2,3,2)'); $worksheet->getCell('A3')->setValue('=ADDRESS(2,3,2,FALSE)'); $worksheet->getCell('A4')->setValue('=ADDRESS(2,3,1,FALSE,"[Book1.xlsx]Sheet1")'); $worksheet->getCell('A5')->setValue('=ADDRESS(2,3,1,FALSE,"EXCEL SHEET")'); for ($row = 1; $row <= 5; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/COLUMN.php ================================================ log('Returns the column index of a cell.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $calculation = Calculation::getInstance($spreadsheet); $calculation->setInstanceArrayReturnType( Calculation::RETURN_ARRAY_AS_VALUE ); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('=COLUMN(C13)'); $worksheet->getCell('A2')->setValue('=COLUMN(E13:G15)'); $worksheet->getCell('F1')->setValue('=COLUMN()'); for ($row = 1; $row <= 2; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } $cell = $worksheet->getCell('F1'); $helper->log('F1: ' . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); ================================================ FILE: samples/LookupRef/COLUMNS.php ================================================ log('Returns the number of columns in an array or reference.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('=COLUMNS(C1:G4)'); $worksheet->getCell('A2')->setValue('=COLUMNS({1,2,3;4,5,6})'); $worksheet->getCell('A3')->setValue('=ROWS(C1:E4 D3:G5)'); $worksheet->getCell('A4')->setValue('=COLUMNS(1:1)'); for ($row = 1; $row <= 4; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/INDEX.php ================================================ log('Returns the row index of a cell.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $data1 = [ ['Apples', 'Lemons'], ['Bananas', 'Pears'], ]; $data2 = [ [4, 6], [5, 3], [6, 9], [7, 5], [8, 3], ]; $worksheet->fromArray($data1, null, 'A1'); $worksheet->fromArray($data2, null, 'C1'); $worksheet->getCell('A11')->setValue('=INDEX(A1:B2, 2, 2)'); $worksheet->getCell('A12')->setValue('=INDEX(A1:B2, 2, 1)'); $worksheet->getCell('A13')->setValue('=INDEX({1,2;3,4}, 0, 2)'); $worksheet->getCell('A14')->setValue('=INDEX(C1:C5, 5)'); $worksheet->getCell('A15')->setValue('=INDEX(C1:D5, 5, 2)'); $worksheet->getCell('A16')->setValue('=SUM(INDEX(C1:D5, 5, 0))'); for ($row = 11; $row <= 16; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/INDIRECT.php ================================================ log('Returns the cell specified by a text string.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $data = [ [8, 9, 0], [3, 4, 5], [9, 1, 3], [4, 6, 2], ]; $worksheet->fromArray($data, null, 'C1'); $spreadsheet->addNamedRange(new NamedRange('NAMED_RANGE_FOR_CELL_D4', $worksheet, '="$D$4"')); $worksheet->getCell('A1')->setValue('=INDIRECT("C1")'); $worksheet->getCell('A2')->setValue('=INDIRECT("D"&4)'); $worksheet->getCell('A3')->setValue('=INDIRECT("E"&ROW())'); $worksheet->getCell('A4')->setValue('=SUM(INDIRECT("$C$4:$E$4"))'); $worksheet->getCell('A5')->setValue('=INDIRECT(NAMED_RANGE_FOR_CELL_D4)'); for ($row = 1; $row <= 5; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/OFFSET.php ================================================ log('Returns a cell range that is a specified number of rows and columns from a cell or range of cells.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $data = [ [null, 'Week 1', 'Week 2', 'Week 3', 'Week 4'], ['Sunday', 4500, 2200, 3800, 1500], ['Monday', 5500, 6100, 5200, 4800], ['Tuesday', 7000, 6200, 5000, 7100], ['Wednesday', 8000, 4000, 3900, 7600], ['Thursday', 5900, 5500, 6900, 7100], ['Friday', 4900, 6300, 6900, 5200], ['Saturday', 3500, 3900, 5100, 4100], ]; $worksheet->fromArray($data, null, 'A3'); $worksheet->getCell('H1')->setValue('=OFFSET(A3, 3, 1)'); $worksheet->getCell('H2')->setValue('=SUM(OFFSET(A3, 3, 1, 1, 4))'); $worksheet->getCell('H3')->setValue('=SUM(OFFSET(B3:E3, 3, 0))'); $worksheet->getCell('H4')->setValue('=SUM(OFFSET(E3, 1, -3, 7))'); for ($row = 1; $row <= 4; ++$row) { $cell = $worksheet->getCell("H{$row}"); $helper->log("H{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/ROW.php ================================================ log('Returns the row index of a cell.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('=ROW(C13)'); $worksheet->getCell('A2')->setValue('=ROW(E19:G21)'); $worksheet->getCell('A3')->setValue('=ROW()'); for ($row = 1; $row <= 3; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/ROWS.php ================================================ log('Returns the row index of a cell.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('=ROWS(C1:E4)'); $worksheet->getCell('A2')->setValue('=ROWS({1,2,3;4,5,6})'); $worksheet->getCell('A3')->setValue('=ROWS(C1:E4 D3:G5)'); for ($row = 1; $row <= 3; ++$row) { $cell = $worksheet->getCell("A{$row}"); $helper->log("A{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } ================================================ FILE: samples/LookupRef/SortExcel.php ================================================ arrayCol] : $rowA; $b = is_array($rowB) ? $rowB[$this->arrayCol] : $rowB; if ($a instanceof Stringable) { $a = (string) $a; } if ($b instanceof Stringable) { $b = (string) $b; } if (is_array($a) || is_object($a) || is_resource($a) || is_array($b) || is_object($b) || is_resource($b)) { throw new Exception('Invalid datatype'); } // null sorts highest if ($a === null) { return ($b === null) ? 0 : $this->ascending; } if ($b === null) { return -$this->ascending; } // int|float sorts lowest $numericA = is_int($a) || is_float($a); $numericB = is_int($b) || is_float($b); if ($numericA && $numericB) { if ($a == $b) { return 0; } return ($a < $b) ? -$this->ascending : $this->ascending; } if ($numericA) { return -$this->ascending; } if ($numericB) { return $this->ascending; } // bool sorts higher than string if (is_bool($a)) { if (!is_bool($b)) { return $this->ascending; } if ($a) { return $b ? 0 : $this->ascending; } return $b ? -$this->ascending : 0; } if (is_bool($b)) { return -$this->ascending; } // special handling for numeric strings starting with - /** @var string $a */ $a2 = (string) preg_replace('/^-(\d)+$/', '$1', $a); /** @var string $b */ $b2 = (string) preg_replace('/^-(\d)+$/', '$1', $b); // strings sort case-insensitive return $this->ascending * strcasecmp($a2, $b2); } /** * @param mixed[] $array */ public function sortArray(array &$array, int $ascending = self::ASCENDING, int $arrayCol = 0): void { if ($ascending !== 1 && $ascending !== -1) { throw new Exception('ascending must be 1 or -1'); } $this->ascending = $ascending; $this->arrayCol = $arrayCol; usort($array, $this->cmp(...)); } } require __DIR__ . '/../Header.php'; /** @var Sample $helper */ $helper->log('Emulating how Excel sorts different DataTypes'); /** @param mixed[] $original */ function displaySorted(array $original, Sample $helper): void { $sorted = $original; $sortExcel = new SortExcel(); $sortExcel->sortArray($sorted); $outArray = [['Original', 'Sorted']]; $count = count($original); for ($i = 0; $i < $count; ++$i) { $outArray[] = [$original[$i], $sorted[$i]]; } $helper->displayGrid($outArray, TextGridRightAlign::floatOrInt); } $helper->log('First example'); $original = ['-3', '40', 'A', 'B', true, false, '+3', '1', '10', '2', '25', 1, 0, -1]; displaySorted($original, $helper); $helper->log('Second example'); $original = ['a', 'A', null, 'x', 'X', true, false, -3, 1]; displaySorted($original, $helper); ================================================ FILE: samples/LookupRef/SortExcelCols.php ================================================ arrayCol] : $rowA; $b = is_array($rowB) ? $rowB[$this->arrayCol] : $rowB; if ($a instanceof Stringable) { $a = (string) $a; } if ($b instanceof Stringable) { $b = (string) $b; } if (is_array($a) || is_object($a) || is_resource($a) || is_array($b) || is_object($b) || is_resource($b)) { throw new Exception('Invalid datatype'); } // null sorts highest if ($a === null) { return ($b === null) ? 0 : $this->ascending; } if ($b === null) { return -$this->ascending; } // int|float sorts lowest $numericA = is_int($a) || is_float($a); $numericB = is_int($b) || is_float($b); if ($numericA && $numericB) { if ($a == $b) { return 0; } return ($a < $b) ? -$this->ascending : $this->ascending; } if ($numericA) { return -$this->ascending; } if ($numericB) { return $this->ascending; } // bool sorts higher than string if (is_bool($a)) { if (!is_bool($b)) { return $this->ascending; } if ($a) { return $b ? 0 : $this->ascending; } return $b ? -$this->ascending : 0; } if (is_bool($b)) { return -$this->ascending; } // special handling for numeric strings starting with - /** @var string $a */ $a2 = (string) preg_replace('/^-(\d)+$/', '$1', $a); /** @var string $b */ $b2 = (string) preg_replace('/^-(\d)+$/', '$1', $b); // strings sort case-insensitive return $this->ascending * strcasecmp($a2, $b2); } /** * @param mixed[] $array */ public function sortArray(array &$array, int $ascending = self::ASCENDING, int $arrayCol = 0): void { if ($ascending !== 1 && $ascending !== -1) { throw new Exception('ascending must be 1 or -1'); } $this->ascending = $ascending; $this->arrayCol = $arrayCol; usort($array, $this->cmp(...)); } } require __DIR__ . '/../Header.php'; /** @var Sample $helper */ $helper->log('Emulating how Excel sorts different DataTypes by Column'); $array = [ ['a', 'a', 'a'], ['a', 'a', 'b'], ['a', null, 'c'], ['b', 'b', 1], ['b', 'c', 2], ['b', 'c', true], ['c', 1, false], ['c', 1, 'a'], ['c', 2, 'b'], [1, 2, 'c'], [1, true, 1], [1, true, 2], [2, false, true], [2, false, false], [2, 'a', false], [true, 'b', true], [true, 'c', 2], [true, 1, 1], [false, 2, 'a'], [false, true, 'b'], [false, false, 'c'], ]; /** @param array> $original */ function displaySortedCols(array $original, Sample $helper): void { $sorted = $original; $sortExcelCols = new SortExcelCols(); $helper->log('Sort by least significant column (descending)'); $sortExcelCols->sortArray($sorted, arrayCol: 2, ascending: -1); $helper->log('Sort by middle column (ascending)'); $sortExcelCols->sortArray($sorted, arrayCol: 1, ascending: 1); $helper->log('Sort by most significant column (descending)'); $sortExcelCols->sortArray($sorted, arrayCol: 0, ascending: -1); $outArray = [['Original', '', '', 'Sorted', '', '']]; $count = count($original); /** @var string[][] $sorted */ for ($i = 0; $i < $count; ++$i) { $outArray[] = [ $original[$i][0], $original[$i][1], $original[$i][2], $sorted[$i][0], $sorted[$i][1], $sorted[$i][2], ]; } $helper->displayGrid($outArray, TextGridRightAlign::floatOrInt); } displaySortedCols($array, $helper); ================================================ FILE: samples/LookupRef/VLOOKUP.php ================================================ log('Searches for a value in the top row of a table or an array of values, and then returns a value in the same column from a row you specify in the table or array.'); // Create new PhpSpreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $data = [ ['ID', 'First Name', 'Last Name', 'Salary'], [72, 'Emily', 'Smith', 64901], [66, 'James', 'Anderson', 70855], [14, 'Mia', 'Clark', 188657], [30, 'John', 'Lewis', 97566], [53, 'Jessica', 'Walker', 58339], [56, 'Mark', 'Reed', 125180], [79, 'Richard', 'Lopez', 91632], ]; $worksheet->fromArray($data, null, 'B2'); $lookupFields = [ ['ID', 53, 66, 56], ['Name'], ['Salary'], ]; $worksheet->fromArray($lookupFields, null, 'G3'); $worksheet->getCell('H4')->setValue('=VLOOKUP(H3, B3:E9, 2, FALSE) & " " & VLOOKUP(H3, B3:E9, 3, FALSE)'); $worksheet->getCell('I4')->setValue('=VLOOKUP(I3, B3:E9, 2, FALSE) & " " & VLOOKUP(I3, B3:E9, 3, FALSE)'); $worksheet->getCell('J4')->setValue('=VLOOKUP(J3, B3:E9, 2, FALSE) & " " & VLOOKUP(J3, B3:E9, 3, FALSE)'); $worksheet->getCell('H5')->setValue('=VLOOKUP(H3, B3:E9, 4, FALSE)'); $worksheet->getCell('I5')->setValue('=VLOOKUP(I3, B3:E9, 4, FALSE)'); $worksheet->getCell('J5')->setValue('=VLOOKUP(J3, B3:E9, 4, FALSE)'); for ($column = 'H'; $column !== 'K'; StringHelper::stringIncrement($column)) { for ($row = 4; $row <= 5; ++$row) { $cell = $worksheet->getCell("{$column}{$row}"); $helper->log("{$column}{$row}: " . $cell->getValueString() . ' => ' . $cell->getCalculatedValueString()); } } ================================================ FILE: samples/Pdf/21_Pdf_Domdf.php ================================================ log('Hide grid lines'); $spreadsheet->getActiveSheet()->setShowGridLines(false); $helper->log('Set orientation to landscape'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $className = PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf::class; $helper->log("Write to PDF format using {$className}"); IOFactory::registerWriter('Pdf', $className); // Save $helper->write($spreadsheet, __FILE__, ['Pdf']); ================================================ FILE: samples/Pdf/21_Pdf_TCPDF.php ================================================ log('Hide grid lines'); $spreadsheet->getActiveSheet()->setShowGridLines(false); $helper->log('Set orientation to landscape'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $className = PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf::class; $helper->log("Write to PDF format using {$className}"); IOFactory::registerWriter('Pdf', $className); // Save $helper->write($spreadsheet, __FILE__, ['Pdf']); ================================================ FILE: samples/Pdf/21_Pdf_mPDF.php ================================================ log('Hide grid lines'); $spreadsheet->getActiveSheet()->setShowGridLines(false); $helper->log('Set orientation to landscape'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $className = PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class; $helper->log("Write to PDF format using {$className}"); IOFactory::registerWriter('Pdf', $className); // Save $helper->write($spreadsheet, __FILE__, ['Pdf']); ================================================ FILE: samples/Pdf/21a_Pdf.php ================================================ log('Hide grid lines'); $spreadsheet->getActiveSheet()->setShowGridLines(false); $helper->log('Set orientation to landscape'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $spreadsheet->setActiveSheetIndex(0)->setPrintGridlines(true); // Issue 2299 - mpdf can't handle hide rows without kludge $spreadsheet->getActiveSheet()->getRowDimension(2)->setVisible(false); function changeGridlines(string $html): string { return str_replace('{border: 1px solid black;}', '{border: 2px dashed red;}', $html); } $helper->log('Write to Mpdf'); IOFactory::registerWriter('Pdf', Mpdf::class); $helper->write( $spreadsheet, __FILE__, ['Pdf'], false, function (Mpdf $writer): void { $writer->setEmbedImages(true); $writer->setEditHtmlCallback('changeGridlines'); } ); ================================================ FILE: samples/Pdf/21b_Pdf.php ================================================ .*~ms'; $bodyrepl = <<

Serif

$lorem

Sans-Serif

$lorem

Monospace

$lorem

EOF; return preg_replace($bodystring, $bodyrepl, $html) ?? throw new SpreadsheetException('preg failed'); } require __DIR__ . '/../Header.php'; /** @var PhpOffice\PhpSpreadsheet\Spreadsheet */ $spreadsheet = require __DIR__ . '/../templates/sampleSpreadsheet.php'; /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->log('Hide grid lines'); $spreadsheet->getActiveSheet()->setShowGridLines(false); $helper->log('Set orientation to landscape'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $helper->log('Write to Dompdf'); IOFactory::registerWriter('Pdf', Dompdf::class); $filename = str_replace('.php', '_dompdf.php', __FILE__); $helper->write( $spreadsheet, $filename, ['Pdf'], false, function (Dompdf $writer): void { $writer->setEditHtmlCallback('replaceBody'); } ); $helper->log('Write to Mpdf'); IOFactory::registerWriter('Pdf', Mpdf::class); $filename = str_replace('.php', '_mpdf.php', __FILE__); $helper->write( $spreadsheet, $filename, ['Pdf'], false, function (Mpdf $writer): void { $writer->setEditHtmlCallback('replaceBody'); } ); $helper->log('Write to Tcpdf'); IOFactory::registerWriter('Pdf', TcpdfClass::class); $filename = str_replace('.php', '_tcpdf.php', __FILE__); $helper->write( $spreadsheet, $filename, ['Pdf'], false, function (TcpdfClass $writer): void { $writer->setEditHtmlCallback('replaceBody'); } ); ================================================ FILE: samples/Pdf/21d_FitToHeightPdf.php ================================================ log('Read spreadsheet'); $filename = '21d_FitToHeightPdf.xlsx'; $fileWithPath = __DIR__ . "/../templates/$filename"; $reader = new Xlsx(); $spreadsheet = $reader->load($fileWithPath); $sheet = $spreadsheet->getActiveSheet(); $helper->log('Write to Mpdf'); IOFactory::registerWriter('Pdf', PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class); $helper->write($spreadsheet, __FILE__, ['Pdf']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/21e_UnusualFont_mpdf.php ================================================ getProperties() ->setCreator('PhpSpreadsheet') ->setTitle('Unusual Font'); $helper->log('Show print grid lines'); $sheet = $spreadsheet->getActiveSheet(); $sheet->setPrintGridLines(true); $sheet->getCell('A1')->setValue('First Cell'); $sheet->getCell('A2')->setValue('Second Cell'); $sheet->getCell('B1')->setValue('Third Cell'); $sheet->getCell('B2')->setValue('Fourth Cell'); $helper->log('Set style to unusual font'); $sheet->getStyle('A1:B2')->getFont()->setName('Shadows Into Light'); $helper->log('Write to Mpdf'); $writer = new Mpdf2($spreadsheet); $filename = $helper->getFileName(__FILE__, 'pdf'); $writer->save($filename); $helper->log("Saved $filename"); if (PHP_SAPI !== 'cli') { echo 'Download ' . basename($filename) . '
'; } $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/21f_Drawing.php ================================================ getActiveSheet(); $sheet->getCell('A1')->setValue('A1'); $sheet->getCell('B1')->setValue('B'); $sheet->getCell('C1')->setValue('C'); $sheet->getCell('D1')->setValue('D'); $sheet->getCell('E1')->setValue('E'); $sheet->getCell('F1')->setValue('F'); $sheet->getCell('G1')->setValue('G'); $sheet->getCell('A2')->setValue('A2'); $sheet->getCell('A3')->setValue('A3'); $sheet->getCell('A4')->setValue('A4'); $sheet->getCell('A5')->setValue('A5'); $sheet->getCell('A6')->setValue('A6'); $sheet->getCell('A7')->setValue('A7'); $sheet->getCell('A8')->setValue('A8'); $helper->log('Add drawing to worksheet'); $drawing = new Drawing(); $drawing->setName('Blue Square'); $path = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'images/blue_square.png'; $drawing->setPath($path); $drawing->setResizeProportional(false); $drawing->setWidth(320); $drawing->setCoordinates('B2'); $drawing->setCoordinates2('G6'); $drawing->setWorksheet($sheet, true); $helper->log('Merge drawing cells for Pdf'); $spreadsheet->mergeDrawingCellsForPdf(); $helper->log('Write to Mpdf'); $helper->write($spreadsheet, __FILE__, ['Mpdf']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/21g_Direction.php ================================================ getActiveSheet(); $sheet1 = $spreadsheet->getActiveSheet(); $sheet2 = $spreadsheet->createSheet(); $sheet3 = $spreadsheet->createSheet(); $cells = [ ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ]; $sheet1->fromArray($cells); $sheet1->setRightToLeft(true); $sheet2->fromArray($cells); $sheet3->fromArray($cells); $sheet3->setRightToLeft(true); $helper->log('Write to html, mpdf, tcpdf'); // Save $helper->write($spreadsheet, __FILE__, ['Html', 'Mpdf', 'Tcpdf']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/21h_DirectionMultiple.php ================================================ getActiveSheet(); $sheet1 = $spreadsheet->getActiveSheet(); $sheet2 = $spreadsheet->createSheet(); $sheet3 = $spreadsheet->createSheet(); $cells = [ ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ]; $sheet1->fromArray($cells); $sheet1->setRightToLeft(true); $sheet2->fromArray($cells); $sheet3->fromArray($cells); $sheet3->setRightToLeft(true); $helper->log('Write to html, mpdf'); // Save $helper->write( $spreadsheet, __FILE__, ['Html', 'Mpdf'], writerCallback: function (HtmlWriter $writer): void { $writer->writeAllSheets(); } ); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/Dompdf_Canvas_Headers.php ================================================ getCanvas()->page_script(function ( int $pageNumber, int $pageCount, Canvas $canvas, FontMetrics $fontMetrics ): void { // Get font metrics for dynamic content like page numbers $fontName = 'helvetica'; // note lowercase $fontType = 'bold'; // note lowercase $font = $fontMetrics->getFont($fontName, $fontType) ?? throw new Exception("no font metrics for $fontName $fontType"); // Example text placement (adjust coordinates and font as needed) if ($pageNumber === 1) { $header = 'Dompdf First Page'; } elseif ($pageNumber % 2 === 0) { $header = 'Dompdf Even Page'; } else { $header = 'Dompdf Odd Page'; } $text = "$header Page $pageNumber of $pageCount"; $canvas->text(40, 20, $text, $font, 12); }); } } $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $counter = 0; /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->log('Populate spreadsheet'); for ($row = 1; $row < 1001; ++$row) { $sheet->getCell("A$row")->setValue(++$counter); // Add many styles by using slight variations of font color for each. $sheet->getCell("A$row")->getStyle()->getFont() ->getColor()->setRgb(sprintf('%06x', $counter)); $sheet->getCell("B$row")->setValue(++$counter); $sheet->getCell("C$row")->setValue(++$counter); } $helper->log('Write to Dompdf with headers added by page_script'); IOFactory::registerWriter('Pdf', Dompdf_Canvas_Headers::class); $helper->write($spreadsheet, __FILE__, ['Pdf']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/Dompdf_Custom_Headers.php ================================================ header { position: fixed; top: -0.5in; /* Position in top margin area */ height: 0.5in; width: 100%; text-align: center; } footer { position: fixed; bottom: -0.5in; /* Position in bottom margin area */ height: 0.5in; width: 100%; text-align: right; } .pagenum:before {content: counter(page);} EOF; $endhead = ''; $html = str_replace($endhead, "$headerFooter$endhead", $html); $bodystring = ''; $bodyrepl = <<
Dompdf Fixed header
Page
EOF; return str_replace($bodystring, $bodyrepl, $html); } $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $counter = 0; /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->log('Populate spreadsheet'); for ($row = 1; $row < 1001; ++$row) { $sheet->getCell("A$row")->setValue(++$counter); // Add many styles by using slight variations of font color for each. $sheet->getCell("A$row")->getStyle()->getFont() ->getColor()->setRgb(sprintf('%06x', $counter)); $sheet->getCell("B$row")->setValue(++$counter); $sheet->getCell("C$row")->setValue(++$counter); } $helper->log('Write to Dompdf'); IOFactory::registerWriter('Pdf', Dompdf::class); $helper->write( $spreadsheet, __FILE__, ['Pdf'], false, function (Dompdf $writer): void { $writer->setEditHtmlCallback('addHeadersFootersDompdf2000'); } ); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/Mpdf_Custom_Headers.php ================================================ /'; $simulatedBodyStart = Mpdf::SIMULATED_BODY_START; $bodyrepl = <<
My document header
My document Page {PAGENO} of {nbpg} {DATE Y-m-j}
$simulatedBodyStart EOF; return preg_replace($bodystring, $bodyrepl, $html) ?? throw new SpreadsheetException('preg 2 failed'); } $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $counter = 0; /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->log('Populate spreadsheet'); for ($row = 1; $row < 1001; ++$row) { $sheet->getCell("A$row")->setValue(++$counter); // Add many styles by using slight variations of font color for each. $sheet->getCell("A$row")->getStyle()->getFont() ->getColor()->setRgb(sprintf('%06x', $counter)); $sheet->getCell("B$row")->setValue(++$counter); $sheet->getCell("C$row")->setValue(++$counter); } $helper->log('Write to Mpdf'); IOFactory::registerWriter('Pdf', Mpdf::class); $helper->write( $spreadsheet, __FILE__, ['Pdf'], false, function (Mpdf $writer): void { $writer->setEditHtmlCallback('addHeadersFootersMpdf2000'); } ); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Pdf/Tcpdf_Custom_Headers.php ================================================ defines(); return new Tcpdf2Class($orientation, $unit, $paperSize); } } // Override vendor class. class Tcpdf2Class extends VendorTcpdf // phpcs:ignore { // Page header public function Header(): void // phpcs:ignore { // Position at 15 mm from top $this->setY(15); // Set font $this->setFont('helvetica', 'B', 12); // Title $pageNum = $this->getPage(); if ($pageNum === 1) { $this->Cell(0, 15, 'Tcpdf first header', 0, 0, 'C', false, '', 0, false, 'M', 'M'); } elseif ($pageNum % 2 === 0) { $this->Cell(0, 15, 'Tcpdf even header', 0, 0, 'C', false, '', 0, false, 'M', 'M'); } else { $this->Cell(0, 15, 'Tcpdf odd header', 0, 0, 'C', false, '', 0, false, 'M', 'M'); } } // Page footer public function Footer(): void // phpcs:ignore { // Position at 15 mm from bottom $this->setY(-15); // Set font $this->setFont('helvetica', 'I', 8); // Page number $this->Cell(0, 10, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, 0, 'C', false, '', 0, false, 'T', 'M'); } } $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $counter = 0; /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ $helper->log('Populate spreadsheet'); for ($row = 1; $row < 1001; ++$row) { $sheet->getCell("A$row")->setValue(++$counter); // Add many styles by using slight variations of font color for each. $sheet->getCell("A$row")->getStyle()->getFont() ->getColor()->setRgb(sprintf('%06x', $counter)); $sheet->getCell("B$row")->setValue(++$counter); $sheet->getCell("C$row")->setValue(++$counter); } $helper->log('Write to Tcpdf with headers and footers'); IOFactory::registerWriter('Pdf', Tcpdf2::class); $helper->write($spreadsheet, __FILE__, ['Pdf']); $spreadsheet->disconnectWorksheets(); ================================================ FILE: samples/Reader/01_Simple_file_reader_using_IOFactory.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory to identify the format'); $spreadsheet = IOFactory::load($inputFileName); $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/02_Simple_file_reader_using_a_specified_reader.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using ' . Xls::class); $reader = new Xls(); $spreadsheet = $reader->load($inputFileName); $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/03_Simple_file_reader_using_the_IOFactory_to_return_a_reader.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $spreadsheet = $reader->load($inputFileName); $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/04_Simple_file_reader_using_the_IOFactory_to_identify_a_reader_to_use.php ================================================ log('File ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' has been identified as an ' . $inputFileType . ' file'); $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with the identified reader type'); $reader = IOFactory::createReader($inputFileType); $spreadsheet = $reader->load($inputFileName); $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/05_Simple_file_reader_using_the_read_data_only_option.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $helper->log('Turning Formatting off for Load'); $reader->setReadDataOnly(true); $spreadsheet = $reader->load($inputFileName); $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/06_Simple_file_reader_loading_all_worksheets.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading all WorkSheets'); $reader->setLoadAllSheets(); $spreadsheet = $reader->load($inputFileName); $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log($sheetIndex . ' -> ' . $loadedSheetName); } ================================================ FILE: samples/Reader/07_Simple_file_reader_loading_a_single_named_worksheet.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading Sheet "' . $sheetname . '" only'); $reader->setLoadSheetsOnly($sheetname); $spreadsheet = $reader->load($inputFileName); $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log($sheetIndex . ' -> ' . $loadedSheetName); } ================================================ FILE: samples/Reader/08_Simple_file_reader_loading_several_named_worksheets.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading Sheets "' . implode('" and "', $sheetnames) . '" only'); $reader->setLoadSheetsOnly($sheetnames); $spreadsheet = $reader->load($inputFileName); $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log($sheetIndex . ' -> ' . $loadedSheetName); } ================================================ FILE: samples/Reader/09_Simple_file_reader_using_a_read_filter.php ================================================ = 9 && $row <= 15) { if (in_array($columnAddress, range('A', 'E'))) { return true; } } return false; } } $filterSubset = new MyReadFilter(); $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $helper->log('Filter range is A9:E15'); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading Sheet "' . $sheetname . '" only'); $reader->setLoadSheetsOnly($sheetname); $helper->log('Loading Sheet using filter'); $reader->setReadFilter($filterSubset); $spreadsheet = $reader->load($inputFileName); $activeRange = $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(); $sheetData = $spreadsheet->getActiveSheet()->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php ================================================ $columns */ public function __construct( private int $startRow, private int $endRow, private array $columns ) { } public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool { if ($row >= $this->startRow && $row <= $this->endRow) { if (in_array($columnAddress, $this->columns)) { return true; } } return false; } } $filterSubset = new MyReadFilter(9, 15, range('G', 'K')); $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); $helper->log('Filter range is G9:K15'); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading Sheet "' . $sheetname . '" only'); $reader->setLoadSheetsOnly($sheetname); $helper->log('Loading Sheet using configurable filter'); $reader->setReadFilter($filterSubset); $spreadsheet = $reader->load($inputFileName); $activeRange = $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(); $sheetData = $spreadsheet->getActiveSheet()->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData); ================================================ FILE: samples/Reader/11_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_version_1.php ================================================ startRow = $startRow; $this->endRow = $startRow + $chunkSize; } public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool { // Only read the heading row, and the rows that were configured in the constructor if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { return true; } return false; } } $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); // Create a new Reader of the type defined in $inputFileType $reader = IOFactory::createReader($inputFileType); // Define how many rows we want for each "chunk" $chunkSize = 20; // Loop to read our worksheet in "chunk size" blocks for ($startRow = 2; $startRow <= 240; $startRow += $chunkSize) { $helper->log('Loading WorkSheet using configurable filter for headings row 1 and for rows ' . $startRow . ' to ' . ($startRow + $chunkSize - 1)); // Create a new Instance of our Read Filter, passing in the limits on which rows we want to read $chunkFilter = new ChunkReadFilter($startRow, $chunkSize); // Tell the Reader that we want to use the new Read Filter that we've just Instantiated $reader->setReadFilter($chunkFilter); // Load only the rows that match our filter from $inputFileName to a PhpSpreadsheet Object $spreadsheet = $reader->load($inputFileName); $sheet = $spreadsheet->getActiveSheet(); // Do some processing here $activeRange = $sheet->calculateWorksheetDataDimension(); $sheet->getStyle($activeRange)->getNumberFormat() ->setFormatCode('0.000'); $sheetData = $sheet->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData, true); } ================================================ FILE: samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_version_2.php ================================================ startRow = $startRow; $this->endRow = $startRow + $chunkSize; } public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool { // Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { return true; } return false; } } $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory with a defined reader type of ' . $inputFileType); // Create a new Reader of the type defined in $inputFileType $reader = IOFactory::createReader($inputFileType); // Define how many rows we want to read for each "chunk" $chunkSize = 20; // Create a new Instance of our Read Filter $chunkFilter = new ChunkReadFilter(); // Tell the Reader that we want to use the Read Filter that we've Instantiated $reader->setReadFilter($chunkFilter); // Loop to read our worksheet in "chunk size" blocks for ($startRow = 2; $startRow <= 240; $startRow += $chunkSize) { $helper->log('Loading WorkSheet using configurable filter for headings row 1 and for rows ' . $startRow . ' to ' . ($startRow + $chunkSize - 1)); // Tell the Read Filter, the limits on which rows we want to read this iteration $chunkFilter->setRows($startRow, $chunkSize); // Load only the rows that match our filter from $inputFileName to a PhpSpreadsheet Object $spreadsheet = $reader->load($inputFileName); $sheet = $spreadsheet->getActiveSheet(); // Do some processing here $activeRange = $sheet->calculateWorksheetDataDimension(); $sheet->getStyle($activeRange)->getNumberFormat() ->setFormatCode('0.000'); $sheetData = $sheet->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData, true); } ================================================ FILE: samples/Reader2/13_Simple_file_reader_for_multiple_CSV_files.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' into WorkSheet #1 using Csv Reader'); $spreadsheet = $reader->load($inputFileName); $spreadsheet->getActiveSheet()->setTitle(pathinfo($inputFileName, PATHINFO_BASENAME)); foreach ($inputFileNames as $sheet => $inputFileName) { $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' into WorkSheet #' . ($sheet + 2) . ' using Csv Reader'); $reader->setSheetIndex($sheet + 1); $reader->loadIntoExisting($inputFileName, $spreadsheet); $spreadsheet->getActiveSheet()->setTitle(pathinfo($inputFileName, PATHINFO_BASENAME)); } $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log('Worksheet #' . $sheetIndex . ' -> ' . $loadedSheetName . ''); $spreadsheet->setActiveSheetIndexByName($loadedSheetName); $sheet = $spreadsheet->getActiveSheet(); $activeRange = $sheet->calculateWorksheetDataDimension(); $sheet->getStyle($activeRange)->getNumberFormat() ->setFormatCode('0.000'); $sheetData = $sheet->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData, true); } ================================================ FILE: samples/Reader2/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php ================================================ startRow = $startRow; $this->endRow = $startRow + $chunkSize; } public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool { // Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { return true; } return false; } } $helper->log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using Csv reader'); // Create a new Reader of the type defined in $inputFileType $reader = new Csv(); // Define how many rows we want to read for each "chunk" $chunkSize = 100; // Create a new Instance of our Read Filter $chunkFilter = new ChunkReadFilter(); // Tell the Reader that we want to use the Read Filter that we've Instantiated // and that we want to store it in contiguous rows/columns $reader->setReadFilter($chunkFilter); $reader->setContiguous(true); // Instantiate a new PhpSpreadsheet object manually $spreadsheet = new Spreadsheet(); // Set a sheet index $sheet = 0; // Loop to read our worksheet in "chunk size" blocks /** $startRow is set to 2 initially because we always read the headings in row #1 * */ for ($startRow = 2; $startRow <= 240; $startRow += $chunkSize) { $helper->log('Loading WorkSheet #' . ($sheet + 1) . ' using configurable filter for headings row 1 and for rows ' . $startRow . ' to ' . ($startRow + $chunkSize - 1)); // Tell the Read Filter, the limits on which rows we want to read this iteration $chunkFilter->setRows($startRow, $chunkSize); // Increment the worksheet index pointer for the Reader $reader->setSheetIndex($sheet); // Load only the rows that match our filter into a new worksheet in the PhpSpreadsheet Object $reader->loadIntoExisting($inputFileName, $spreadsheet); // Set the worksheet title (to reference the "sheet" of data that we've loaded) // and increment the sheet index as well $spreadsheet->getActiveSheet()->setTitle('Country Data #' . (++$sheet)); } $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log('Worksheet #' . $sheetIndex . ' -> ' . $loadedSheetName . ''); $spreadsheet->setActiveSheetIndexByName($loadedSheetName); $sheet = $spreadsheet->getActiveSheet(); $activeRange = $sheet->calculateWorksheetDataDimension(); $sheet->getStyle($activeRange)->getNumberFormat() ->setFormatCode('0.000'); $sheetData = $sheet->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData, true); } ================================================ FILE: samples/Reader2/15_Simple_file_reader_for_tab_separated_value_file_using_the_Advanced_Value_Binder.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' into WorkSheet #1 using Csv reader'); $reader->setDelimiter("\t"); $spreadsheet = $reader->load($inputFileName); $spreadsheet->getActiveSheet()->setTitle(pathinfo($inputFileName, PATHINFO_BASENAME)); $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log('Worksheet #' . $sheetIndex . ' -> ' . $loadedSheetName . ' (Formatted)'); $spreadsheet->setActiveSheetIndexByName($loadedSheetName); $activeRange = $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(); $sheetData = $spreadsheet->getActiveSheet()->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData); } foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log('Worksheet #' . $sheetIndex . ' -> ' . $loadedSheetName . ' (Unformatted)'); $spreadsheet->setActiveSheetIndexByName($loadedSheetName); $activeRange = $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(); $sheetData = $spreadsheet->getActiveSheet()->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData); } foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log('Worksheet #' . $sheetIndex . ' -> ' . $loadedSheetName . ' (Raw)'); $spreadsheet->setActiveSheetIndexByName($loadedSheetName); $activeRange = $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(); $sheetData = $spreadsheet->getActiveSheet()->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData); } ================================================ FILE: samples/Reader2/16_Handling_loader_exceptions_using_TryCatch.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using IOFactory to identify the format'); try { $spreadsheet = IOFactory::load($inputFileName); } catch (ReaderException $e) { $helper->log('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage()); } ================================================ FILE: samples/Reader2/17_Simple_file_reader_loading_several_named_worksheets.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' using Xls reader'); $reader = new Xls(); // Read the list of Worksheet Names from the Workbook file $helper->log('Read the list of Worksheets in the WorkBook'); $worksheetNames = $reader->listWorksheetNames($inputFileName); $helper->log('There are ' . count($worksheetNames) . ' worksheet' . ((count($worksheetNames) == 1) ? '' : 's') . ' in the workbook'); foreach ($worksheetNames as $worksheetName) { $helper->log($worksheetName); } ================================================ FILE: samples/Reader2/18_Reading_list_of_worksheets_without_loading_entire_file.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' information using Xls reader'); $reader = new Xls(); $worksheetNames = $reader->listWorksheetNames($inputFileName); $helper->log('

Worksheet Names

'); $helper->log('
    '); foreach ($worksheetNames as $worksheetName) { $helper->log('
  1. ' . $worksheetName . '
  2. '); } $helper->log('
'); ================================================ FILE: samples/Reader2/19_Reading_worksheet_information_without_loading_entire_file.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' information using Xls reader'); $reader = new Xls(); $worksheetData = $reader->listWorksheetInfo($inputFileName); $helper->log('

Worksheet Information

'); $helper->log('
    '); foreach ($worksheetData as $worksheet) { $helper->log('
  1. ' . $worksheet['worksheetName']); $helper->log('Rows: ' . $worksheet['totalRows'] . ' Columns: ' . $worksheet['totalColumns']); $helper->log('Cell Range: A1:' . $worksheet['lastColumnLetter'] . $worksheet['totalRows']); $helper->log('
  2. '); } $helper->log('
'); ================================================ FILE: samples/Reader2/20_Reader_worksheet_hyperlink_image.php ================================================ log('Start'); $spreadsheet = new Spreadsheet(); $aSheet = $spreadsheet->getActiveSheet(); $gdImage = @imagecreatetruecolor(120, 20); if ($gdImage === false) { throw new Exception('imagecreatetruecolor failed'); } $textColor = imagecolorallocate($gdImage, 255, 255, 255); if ($textColor === false) { throw new Exception('imagecolorallocate failed'); } imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor); $baseUrl = 'https://phpspreadsheet.readthedocs.io'; $drawing = new PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing(); $drawing->setName('In-Memory image 1'); $drawing->setDescription('In-Memory image 1'); $drawing->setCoordinates('A1'); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction( PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG ); $drawing->setMimeType(PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT); $drawing->setHeight(36); $helper->log('Write image'); $hyperLink = new PhpOffice\PhpSpreadsheet\Cell\Hyperlink($baseUrl, 'test image'); $drawing->setHyperlink($hyperLink); $helper->log('Write link: ' . $baseUrl); $drawing->setWorksheet($aSheet); $filename = File::temporaryFilename(); $writer = PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, $inputFileType); $writer->save($filename); $reader = PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $reloadedSpreadsheet = $reader->load($filename); unlink($filename); $helper->log('reloaded Spreadsheet'); foreach ($reloadedSpreadsheet->getActiveSheet()->getDrawingCollection() as $pDrawing) { $helper->log('Read link: ' . ($pDrawing->getHyperlink()?->getUrl() ?? 'none')); } $helper->log('end'); ================================================ FILE: samples/Reader2/21_Reader_CSV_Long_Integers_with_String_Value_Binder.php ================================================ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' into WorkSheet #1 using IOFactory with a defined reader type of ' . $inputFileType); $spreadsheet = $reader->load($inputFileName); $spreadsheet->getActiveSheet()->setTitle(pathinfo($inputFileName, PATHINFO_BASENAME)); $helper->log($spreadsheet->getSheetCount() . ' worksheet' . (($spreadsheet->getSheetCount() == 1) ? '' : 's') . ' loaded'); $loadedSheetNames = $spreadsheet->getSheetNames(); foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) { $helper->log('Worksheet #' . $sheetIndex . ' -> ' . $loadedSheetName . ' (Formatted)'); $spreadsheet->setActiveSheetIndexByName($loadedSheetName); $activeRange = $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(); $sheetData = $spreadsheet->getActiveSheet()->rangeToArray($activeRange, null, true, true, true); $helper->displayGrid($sheetData); } ================================================ FILE: samples/Reader2/22_Reader_formscomments.php ================================================ log('Start'); $inputFileType = 'Xlsx'; $inputFileName = __DIR__ . '/sampleData/formscomments.xlsx'; $helper->log('Loading file ' . $inputFileName . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading all WorkSheets'); $reader->setLoadAllSheets(); $spreadsheet = $reader->load($inputFileName); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); $spreadsheet->disconnectWorksheets(); $helper->log('end'); ================================================ FILE: samples/Reader2/22_Reader_issue1767.php ================================================ log('Start'); $inputFileType = 'Xlsx'; $inputFileName = __DIR__ . '/sampleData/issue.1767.xlsx'; $helper->log('Loading file ' . $inputFileName . ' using IOFactory with a defined reader type of ' . $inputFileType); $reader = IOFactory::createReader($inputFileType); $helper->log('Loading all WorkSheets'); $reader->setLoadAllSheets(); $spreadsheet = $reader->load($inputFileName); // Save $helper->write($spreadsheet, __FILE__); $spreadsheet->disconnectWorksheets(); $helper->log('end'); ================================================ FILE: samples/Reader2/23_iterateRowsYield.php ================================================ getSheet(0); $rowGenerator = $sheet->rangeToArrayYieldRows( $spreadsheet->getActiveSheet()->calculateWorksheetDataDimension(), null, false, false ); foreach ($rowGenerator as $row) { echo '| ' . StringHelper::convertToString($row[0]) . ' | ' . StringHelper::convertToString($row[1]) . "|\n"; } ================================================ FILE: samples/Reader2/sampleData/example1.csv ================================================ First Name,Last Name,Nationality,Gender,Date of Birth,Time of Birth,Date/Time,PHP Coder,Sanity %Age Mark,Baker,British,M,19-Dec-1960,01:30,=E2+F2,TRUE,32% Toni,Baker,British,F,24-Nov-1950,20:00,=E3+F3,FALSE,95% Rachel,Baker,British,F,7-Dec-1982,00:15,=E4+F4,FALSE,100% ================================================ FILE: samples/Reader2/sampleData/example1.tsv ================================================ First Name Last Name Nationality Gender Date of Birth Time of Birth Date/Time PHP Coder Sanity %Age Mark Baker British M 19-Dec-1960 01:30 =E2+F2 TRUE 32% Toni Baker British F 24-Nov-1950 20:00 =E3+F3 FALSE 95% Rachel Baker British F 7-Dec-1982 00:15 =E4+F4 FALSE 100% ================================================ FILE: samples/Reader2/sampleData/example2.csv ================================================ "City","Country","Latitude","Longitude" "Kabul","Afghanistan",34.528455,69.171703 "Tirane","Albania",41.33,19.82 "Algiers","Algeria",36.752887,3.042048 "Pago Pago","American Samoa",-14.27933,-170.700897 "Andorra la Vella","Andorra",42.507531,1.521816 "Luanda","Angola",-8.838333,13.234444 "Buenos Aires","Argentina",-34.608417,-58.373161 "Yerevan","Armenia",40.183333,44.516667 "Oranjestad","Aruba",12.52458,-70.026459 "Canberra","Australia",-35.3075,149.124417 "Vienna","Austria",48.208333,16.373056 "Baku","Azerbaijan",40.379571,49.891233 "Nassau","Bahamas",25.06,-77.345 "Manama","Bahrain",26.216667,50.583333 "Dhaka","Bangladesh",23.709921,90.407143 "Bridgetown","Barbados",13.096111,-59.608333 "Minsk","Belarus",53.9,27.566667 "Brussels","Belgium",50.846281,4.354727 "Belmopan","Belize",17.251389,-88.766944 "Thimphu","Bhutan",27.466667,89.641667 "La Paz","Bolivia",-16.49901,-68.146248 "Sarajevo","Bosnia and Herzegovina",43.8476,18.3564 "Gaborone","Botswana",-24.65411,25.908739 "Brasilia","Brazil",-15.780148,-47.92917 "Road Town","British Virgin Islands",18.433333,-64.616667 "Bandar Seri Begawan","Brunei Darussalam",4.9431,114.9425 "Sofia","Bulgaria",42.697626,23.322284 "Ouagadougou","Burkina Faso",12.364637,-1.533864 "Bujumbura","Burundi",-3.361378,29.359878 "Phnom Penh","Cambodia",11.55,104.916667 "Yaounde","Cameroon",3.866667,11.516667 "Ottawa","Canada",45.423494,-75.697933 "Praia","Cape Verde",14.920833,-23.508333 "George Town","Cayman Islands",19.286932,-81.367439 "Bangui","Central African Republic",4.361698,18.555975 "N'Djamena","Chad",12.104797,15.044506 "Santiago","Chile",-33.42536,-70.566466 "Beijing","China",39.904667,116.408198 "Bogota","Colombia",4.647302,-74.096268 "Moroni","Comoros",-11.717216,43.247315 "Brazzaville","Congo",-4.266667,15.283333 "San Jose","Costa Rica",9.933333,-84.083333 "Yamoussoukro","Cote d'Ivoire",6.816667,-5.283333 "Zagreb","Croatia",45.814912,15.978515 "Havana","Cuba",23.133333,-82.366667 "Nicosia","Cyprus",35.166667,33.366667 "Prague","Czech Republic",50.087811,14.42046 "Kinshasa","Congo",-4.325,15.322222 "Copenhagen","Denmark",55.676294,12.568116 "Djibouti","Djibouti",11.588,43.145 "Roseau","Dominica",15.301389,-61.388333 "Santo Domingo","Dominican Republic",18.5,-69.983333 "Dili","East Timor",-8.566667,125.566667 "Quito","Ecuador",-0.229498,-78.524277 "Cairo","Egypt",30.064742,31.249509 "San Salvador","El Salvador",13.69,-89.190003 "Malabo","Equatorial Guinea",3.75,8.783333 "Asmara","Eritrea",15.33236,38.92617 "Tallinn","Estonia",59.438862,24.754472 "Addis Ababa","Ethiopia",9.022736,38.746799 "Stanley","Falkland Islands",-51.700981,-57.84919 "Torshavn","Faroe Islands",62.017707,-6.771879 "Suva","Fiji",-18.1416,178.4419 "Helsinki","Finland",60.169813,24.93824 "Paris","France",48.856667,2.350987 "Cayenne","French Guiana",4.9227,-52.3269 "Papeete","French Polynesia",-17.535021,-149.569595 "Libreville","Gabon",0.390841,9.453644 "Banjul","Gambia",13.453056,-16.5775 "T'bilisi","Georgia",41.716667,44.783333 "Berlin","Germany",52.523405,13.4114 "Accra","Ghana",5.555717,-0.196306 "Athens","Greece",37.97918,23.716647 "Nuuk","Greenland",64.18362,-51.721407 "Basse-Terre","Guadeloupe",15.998503,-61.72202 "Guatemala","Guatemala",14.641389,-90.513056 "St. Peter Port","Guernsey",49.458858,-2.534752 "Conakry","Guinea",9.537029,-13.67847 "Bissau","Guinea-Bissau",11.866667,-15.6 "Georgetown","Guyana",6.804611,-58.154831 "Port-au-Prince","Haiti",18.539269,-72.336408 "Tegucigalpa","Honduras",14.082054,-87.206285 "Budapest","Hungary",47.498406,19.040758 "Reykjavik","Iceland",64.135338,-21.89521 "New Delhi","India",28.635308,77.22496 "Jakarta","Indonesia",-6.211544,106.845172 "Tehran","Iran",35.696216,51.422945 "Baghdad","Iraq",33.3157,44.3922 "Dublin","Ireland",53.344104,-6.267494 "Jerusalem","Israel",31.7857,35.2007 "Rome","Italy",41.895466,12.482324 "Kingston","Jamaica",17.992731,-76.792009 "St. Helier","Jersey",49.190278,-2.108611 "Amman","Jordan",31.956578,35.945695 "Astana","Kazakhstan",51.10,71.30 "Nairobi","Kenya",-01.17,36.48 "Tarawa","Kiribati",01.30,173.00 "Seoul","South Korea",37.31,126.58 "Kuwait City","Kuwait",29.30,48.00 "Bishkek","Kyrgyzstan",42.54,74.46 "Riga","Latvia",56.53,24.08 "Beirut","Lebanon",33.53,35.31 "Maseru","Lesotho",-29.18,27.30 "Monrovia","Liberia",06.18,-10.47 "Vaduz","Liechtenstein",47.08,09.31 "Vilnius","Lithuania",54.38,25.19 "Luxembourg","Luxembourg",49.37,06.09 "Antananarivo","Madagascar",-18.55,47.31 "Lilongwe","Malawi",-14.00,33.48 "Kuala Lumpur","Malaysia",03.09,101.41 "Male","Maldives",04.00,73.28 "Bamako","Mali",12.34,-07.55 "Valletta","Malta",35.54,14.31 "Fort-de-France","Martinique",14.36,-61.02 "Nouakchott","Mauritania",-20.10,57.30 "Mamoudzou","Mayotte",-12.48,45.14 "Mexico City","Mexico",19.20,-99.10 "Palikir","Micronesia",06.55,158.09 "Chisinau","Moldova",47.02,28.50 "Maputo","Mozambique",-25.58,32.32 "Yangon","Myanmar",16.45,96.20 "Windhoek","Namibia",-22.35,17.04 "Kathmandu","Nepal",27.45,85.20 "Amsterdam","Netherlands",52.23,04.54 "Willemstad","Netherlands Antilles",12.05,-69.00 "Noumea","New Caledonia",-22.17,166.30 "Wellington","New Zealand",-41.19,174.46 "Managua","Nicaragua",12.06,-86.20 "Niamey","Niger",13.27,02.06 "Abuja","Nigeria",09.05,07.32 "Kingston","Norfolk Island",-45.20,168.43 "Saipan","Northern Mariana Islands",15.12,145.45 "Oslo","Norway",59.55,10.45 "Masqat","Oman",23.37,58.36 "Islamabad","Pakistan",33.40,73.10 "Koror","Palau",07.20,134.28 "Panama City","Panama",09.00,-79.25 "Port Moresby","Papua New Guinea",-09.24,147.08 "Asuncion","Paraguay",-25.10,-57.30 "Lima","Peru",-12.00,-77.00 "Manila","Philippines",14.40,121.03 "Warsaw","Poland",52.13,21.00 "Lisbon","Portugal",38.42,-09.10 "San Juan","Puerto Rico",18.28,-66.07 "Doha","Qatar",25.15,51.35 "Bucuresti","Romania",44.27,26.10 "Moskva","Russian Federation",55.45,37.35 "Kigali","Rawanda",-01.59,30.04 "Basseterre","Saint Kitts and Nevis",17.17,-62.43 "Castries","Saint Lucia",14.02,-60.58 "Saint-Pierre","Saint Pierre and Miquelon",46.46,-56.12 "Apia","Samoa",-13.50,-171.50 "San Marino","San Marino",43.55,12.30 "Sao Tome","Sao Tome and Principe",00.10,06.39 "Riyadh","Saudi Arabia",24.41,46.42 "Dakar","Senegal",14.34,-17.29 "Freetown","Sierra Leone",08.30,-13.17 "Bratislava","Slovakia",48.10,17.07 "Ljubljana","Slovenia",46.04,14.33 "Honiara","Solomon Islands",-09.27,159.57 "Mogadishu","Somalia",02.02,45.25 "Pretoria","South Africa",-25.44,28.12 "Madrid","Spain",40.25,-03.45 "Khartoum","Sudan",15.31,32.35 "Paramaribo","Suriname",05.50,-55.10 "Mbabane","Swaziland",-26.18,31.06 "Stockholm","Sweden",59.20,18.03 "Bern","Switzerland",46.57,07.28 "Damascus","Syrian Arab Republic",33.30,36.18 "Dushanbe","Tajikistan",38.33,68.48 "Bangkok","Thailand",13.45,100.35 "Lome","Togo",06.09,01.20 "Nuku'alofa","Tonga",-21.10,-174.00 "Tunis","Tunisia",36.50,10.11 "Ankara","Turkey",39.57,32.54 "Ashgabat","Turkmenistan",38.00,57.50 "Funafuti","Tuvalu",-08.31,179.13 "Kampala","Uganda",00.20,32.30 "Kiev","Ukraine",50.30,30.28 "Abu Dhabi","United Arab Emirates",24.28,54.22 "London","United Kingdom",51.36,-00.05 "Dodoma","Tanzania",-06.08,35.45 "Washington DC","United States of America",39.91,-77.02 "Montevideo","Uruguay",-34.50,-56.11 "Tashkent","Uzbekistan",41.20,69.10 "Port-Vila","Vanuatu",-17.45,168.18 "Caracas","Venezuela",10.30,-66.55 "Hanoi","Viet Nam",21.05,105.55 "Belgrade","Yugoslavia",44.50,20.37 "Lusaka","Zambia",-15.28,28.16 "Harare","Zimbabwe",-17.43,31.02 "St. John's","Antigua and Barbuda",17.08,-61.50 "Porto Novo","Benin",06.30,02.47 "Hamilton","Bermuda"","32.18,-64.48 "Avarua","Cook Islands",-21.12,-159.46 "St. George's","Grenada",12.04,-61.44 "Agaa","Guam",13.28,144.45 "Victoria","Hong Kong",22.16,114.13 "Tokyo","Japan",35.40,139.45 "Pyongyang","North Korea",39.00,125.47 "Vientiane","Laos",17.59,102.38 "Tripoli","Libya",32.54,013.11 "Skopje","Macedonia",42.00,021.28 "Majuro","Marshall Islands",07.05,171.08 "Port Louis","Mauritius",-20.10,57.30 "Monaco","Monaco",43.44,007.25 "Ulan Bator","Mongolia",47.54,106.52 "Plymouth","Montserrat",16.44,-62.14 "Rabat","Morocco",34.02,-06.51 "Alofi","Niue",-14.27,-178.05 "Saint-Denis","Runion",-20.52,55.27 "Victoria","Seychelles",-04.38,55.28 "Singapore","Singapore",01.18,103.50 "Colombo","Sri Lanka",06.55,79.52 "Kingstown","St Vincent and the Grenadines",13.12,-61.14 "Taipei","Taiwan",25.50,121.32 "Port-of-Spain","Trinidad and Tobago",10.38,-61.31 "Cockburn Harbour","Turks and Caicos Islands",21.30,-71.30 "Charlotte Amalie","US Virgin Islands",18.22,-64.56 "Vatican City","Vatican State",41.54,12.27 "Layoune","Western Sahara",27.10,-13.11 "San'a","Yemen",15.24,44.14 ================================================ FILE: samples/Reader2/sampleData/longIntegers.csv ================================================ "Column 1","Column 2" 123456789012345678901234,234567890123456789012345 345678901234567890123456,456789012345678901234567 567890123456789012345678,678901234567890123456789 789012345678901234567890,890123456789012345678901 901234567890123456789012,012345678901234567890123 ================================================ FILE: samples/Reading_workbook_data/Custom_properties.php ================================================ load($inputFileName); // Read an array list of any custom properties for this document $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); // Loop through the list of custom properties foreach ($customPropertyList as $customPropertyName) { $helper->log('' . $customPropertyName . ': '); // Retrieve the property value $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customPropertyName); // Retrieve the property type $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customPropertyName); // Manipulate properties as appropriate for display purposes switch ($propertyType) { case 'i': // integer $propertyType = 'integer number'; break; case 'f': // float $propertyType = 'floating point number'; break; case 's': // string $propertyType = 'string'; break; case 'd': // date $propertyValue = is_numeric($propertyValue) ? date('l, j<\s\u\p>S F Y g:i A', (int) $propertyValue) : '*****INVALID*****'; $propertyType = 'date'; break; case 'b': // boolean $propertyValue = ($propertyValue) ? 'TRUE' : 'FALSE'; $propertyType = 'boolean'; break; } $helper->log($propertyValue . ' (' . $propertyType . ')'); } ================================================ FILE: samples/Reading_workbook_data/Custom_property_names.php ================================================ load($inputFileName); // Read an array list of any custom properties for this document $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); foreach ($customPropertyList as $customPropertyName) { $helper->log($customPropertyName); } ================================================ FILE: samples/Reading_workbook_data/Properties.php ================================================ load($inputFileName); // Read the document's creator property $creator = $spreadsheet->getProperties()->getCreator(); $helper->log('Document Creator: ' . $creator); // Read the Date when the workbook was created (as a PHP timestamp value) $creationDatestamp = $spreadsheet->getProperties()->getCreated(); $creationDate = Date::formattedDateTimeFromTimestamp("$creationDatestamp", 'l, j<\s\u\p>S F Y'); $creationTime = Date::formattedDateTimeFromTimestamp("$creationDatestamp", 'g:i A'); $helper->log('Created On: ' . $creationDate . ' at ' . $creationTime); // Read the name of the last person to modify this workbook $modifiedBy = $spreadsheet->getProperties()->getLastModifiedBy(); $helper->log('Last Modified By: ' . $modifiedBy); // Read the Date when the workbook was last modified (as a PHP timestamp value) $modifiedDatestamp = $spreadsheet->getProperties()->getModified(); // Format the date and time using the standard PHP date() function $modifiedDate = Date::formattedDateTimeFromTimestamp("$modifiedDatestamp", 'l, j<\s\u\p>S F Y'); $modifiedTime = Date::formattedDateTimeFromTimestamp("$modifiedDatestamp", 'g:i A'); $helper->log('Last Modified On: ' . $modifiedDate . ' at ' . $modifiedTime); // Read the workbook title property $workbookTitle = $spreadsheet->getProperties()->getTitle(); $helper->log('Title: ' . $workbookTitle); // Read the workbook description property $description = $spreadsheet->getProperties()->getDescription(); $helper->log('Description: ' . $description); // Read the workbook subject property $subject = $spreadsheet->getProperties()->getSubject(); $helper->log('Subject: ' . $subject); // Read the workbook keywords property $keywords = $spreadsheet->getProperties()->getKeywords(); $helper->log('Keywords: ' . $keywords); // Read the workbook category property $category = $spreadsheet->getProperties()->getCategory(); $helper->log('Category: ' . $category); // Read the workbook company property $company = $spreadsheet->getProperties()->getCompany(); $helper->log('Company: ' . $company); // Read the workbook manager property $manager = $spreadsheet->getProperties()->getManager(); $helper->log('Manager: ' . $manager); $s = new PhpOffice\PhpSpreadsheet\Helper\Sample(); ================================================ FILE: samples/Reading_workbook_data/Worksheet_count_and_names.php ================================================ load($inputFileName); // Use the PhpSpreadsheet object's getSheetCount() method to get a count of the number of WorkSheets in the WorkBook $sheetCount = $spreadsheet->getSheetCount(); $helper->log('There ' . (($sheetCount == 1) ? 'is' : 'are') . ' ' . $sheetCount . ' WorkSheet' . (($sheetCount == 1) ? '' : 's') . ' in the WorkBook'); $helper->log('Reading the names of Worksheets in the WorkBook'); // Use the PhpSpreadsheet object's getSheetNames() method to get an array listing the names/titles of the WorkSheets in the WorkBook $sheetNames = $spreadsheet->getSheetNames(); foreach ($sheetNames as $sheetIndex => $sheetName) { $helper->log('WorkSheet #' . $sheetIndex . ' is named "' . $sheetName . '"'); } ================================================ FILE: samples/Table/01_Table.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('aswinkumar863') ->setLastModifiedBy('aswinkumar863') ->setTitle('PhpSpreadsheet Table Test Document') ->setSubject('PhpSpreadsheet Table Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Table'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Year') ->setCellValue('B1', 'Quarter') ->setCellValue('C1', 'Country') ->setCellValue('D1', 'Sales'); $dataArray = [ ['2010', 'Q1', 'United States', 790], ['2010', 'Q2', 'United States', 730], ['2010', 'Q3', 'United States', 860], ['2010', 'Q4', 'United States', 850], ['2011', 'Q1', 'United States', 800], ['2011', 'Q2', 'United States', 700], ['2011', 'Q3', 'United States', 900], ['2011', 'Q4', 'United States', 950], ['2010', 'Q1', 'Belgium', 380], ['2010', 'Q2', 'Belgium', 390], ['2010', 'Q3', 'Belgium', 420], ['2010', 'Q4', 'Belgium', 460], ['2011', 'Q1', 'Belgium', 400], ['2011', 'Q2', 'Belgium', 350], ['2011', 'Q3', 'Belgium', 450], ['2011', 'Q4', 'Belgium', 500], ['2010', 'Q1', 'UK', 690], ['2010', 'Q2', 'UK', 610], ['2010', 'Q3', 'UK', 620], ['2010', 'Q4', 'UK', 600], ['2011', 'Q1', 'UK', 720], ['2011', 'Q2', 'UK', 650], ['2011', 'Q3', 'UK', 580], ['2011', 'Q4', 'UK', 510], ['2010', 'Q1', 'France', 510], ['2010', 'Q2', 'France', 490], ['2010', 'Q3', 'France', 460], ['2010', 'Q4', 'France', 590], ['2011', 'Q1', 'France', 620], ['2011', 'Q2', 'France', 650], ['2011', 'Q3', 'France', 415], ['2011', 'Q4', 'France', 570], ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A2'); // Create Table $helper->log('Create Table'); $table = new Table('A1:D33', 'Sales_Data'); // Create Columns $table->getColumn('D')->setShowFilterButton(false); $table->getAutoFilter()->getColumn('A') ->setFilterType(AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER) ->createRule() ->setRule(AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 2011) ->setRuleType(AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); // Create Table Style $helper->log('Create Table Style'); $tableStyle = new TableStyle(); $tableStyle->setTheme(TableStyle::TABLE_STYLE_MEDIUM2); $tableStyle->setShowRowStripes(true); $tableStyle->setShowColumnStripes(true); $tableStyle->setShowFirstColumn(true); $tableStyle->setShowLastColumn(true); $table->setStyle($tableStyle); // Add Table to Worksheet $helper->log('Add Table to Worksheet'); $spreadsheet->getActiveSheet()->addTable($table); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, true, true, true)); function writerCallbackForHtml(IWriter $writer): void { if (method_exists($writer, 'setTableFormats')) { $writer->setTableFormats(true); } } // Save $helper->write($spreadsheet, __FILE__, ['Xlsx', 'Html'], writerCallback: writerCallbackForHtml(...)); ================================================ FILE: samples/Table/02_Table_Total.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('aswinkumar863') ->setLastModifiedBy('aswinkumar863') ->setTitle('PhpSpreadsheet Table Test Document') ->setSubject('PhpSpreadsheet Table Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Table'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Year') ->setCellValue('B1', 'Quarter') ->setCellValue('C1', 'Country') ->setCellValue('D1', 'Sales'); $dataArray = [ ['2010', 'Q1', 'United States', 790], ['2010', 'Q2', 'United States', 730], ['2010', 'Q3', 'United States', 860], ['2010', 'Q4', 'United States', 850], ['2011', 'Q1', 'United States', 800], ['2011', 'Q2', 'United States', 700], ['2011', 'Q3', 'United States', 900], ['2011', 'Q4', 'United States', 950], ['2010', 'Q1', 'Belgium', 380], ['2010', 'Q2', 'Belgium', 390], ['2010', 'Q3', 'Belgium', 420], ['2010', 'Q4', 'Belgium', 460], ['2011', 'Q1', 'Belgium', 400], ['2011', 'Q2', 'Belgium', 350], ['2011', 'Q3', 'Belgium', 450], ['2011', 'Q4', 'Belgium', 500], ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A2'); // Table $helper->log('Create Table'); $table = new Table(); $table->setName('SalesData'); $table->setShowTotalsRow(true); $table->setRange('A1:D18'); // +1 row for totalsRow $helper->log('Add Totals Row'); // Table column label not implemented yet, $table->getColumn('A')->setTotalsRowLabel('Total'); // So set the label directly to the cell $spreadsheet->getActiveSheet()->getCell('A18')->setValue('Total'); // Table column function not implemented yet, $table->getColumn('D')->setTotalsRowFunction('sum'); // So set the formula directly to the cell $spreadsheet->getActiveSheet()->getCell('D18')->setValue('=SUBTOTAL(109,SalesData[Sales])'); // Add Table to Worksheet $helper->log('Add Table to Worksheet'); $spreadsheet->getActiveSheet()->addTable($table); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true)); $helper->log('Calculate Structured References'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, true, true, true), true); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Table/03_Column_Formula.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('aswinkumar863') ->setLastModifiedBy('aswinkumar863') ->setTitle('PhpSpreadsheet Table Test Document') ->setSubject('PhpSpreadsheet Table Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Table'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $columnFormula = '=SUM(Sales_Data[[#This Row],[Q1]:[Q4]])'; $dataArray = [ ['Year', 'Country', 'Q1', 'Q2', 'Q3', 'Q4', 'Sales'], [2010, 'Belgium', 380, 390, 420, 460, $columnFormula], [2010, 'France', 510, 490, 460, 590, $columnFormula], [2010, 'Germany', 720, 680, 640, 660, $columnFormula], [2010, 'Italy', 440, 410, 420, 450, $columnFormula], [2010, 'Spain', 510, 490, 470, 420, $columnFormula], [2010, 'UK', 690, 610, 620, 600, $columnFormula], [2010, 'United States', 790, 730, 860, 850, $columnFormula], [2011, 'Belgium', 400, 350, 450, 500, $columnFormula], [2011, 'France', 620, 650, 415, 570, $columnFormula], [2011, 'Germany', 680, 620, 710, 690, $columnFormula], [2011, 'Italy', 430, 370, 350, 335, $columnFormula], [2011, 'Spain', 460, 390, 430, 415, $columnFormula], [2011, 'UK', 720, 650, 580, 510, $columnFormula], [2011, 'United States', 800, 700, 900, 950, $columnFormula], ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A1'); // Create Table $helper->log('Create Table'); $table = new Table('A1:G15', 'Sales_Data'); $table->setRange('A1:G15'); // Set Column Formula $table->getColumn('G')->setColumnFormula($columnFormula); // Add Table to Worksheet $helper->log('Add Table to Worksheet'); $spreadsheet->getActiveSheet()->addTable($table); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true)); $helper->log('Calculate Structured References'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, true, true, true)); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Table/04_Column_Formula_with_Totals.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $spreadsheet->getProperties()->setCreator('aswinkumar863') ->setLastModifiedBy('aswinkumar863') ->setTitle('PhpSpreadsheet Table Test Document') ->setSubject('PhpSpreadsheet Table Test Document') ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') ->setKeywords('office PhpSpreadsheet php') ->setCategory('Table'); // Create the worksheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $columnFormula = '=SUM(Sales_Data[[#This Row],[Q1]:[Q4]])'; $dataArray = [ ['Year', 'Country', 'Q1', 'Q2', 'Q3', 'Q4', 'Sales'], [2010, 'Belgium', 380, 390, 420, 460, $columnFormula], [2010, 'France', 510, 490, 460, 590, $columnFormula], [2010, 'Germany', 720, 680, 640, 660, $columnFormula], [2010, 'Italy', 440, 410, 420, 450, $columnFormula], [2010, 'Spain', 510, 490, 470, 420, $columnFormula], [2010, 'UK', 690, 610, 620, 600, $columnFormula], [2010, 'United States', 790, 730, 860, 850, $columnFormula], [2011, 'Belgium', 400, 350, 450, 500, $columnFormula], [2011, 'France', 620, 650, 415, 570, $columnFormula], [2011, 'Germany', 680, 620, 710, 690, $columnFormula], [2011, 'Italy', 430, 370, 350, 335, $columnFormula], [2011, 'Spain', 460, 390, 430, 415, $columnFormula], [2011, 'UK', 720, 650, 580, 510, $columnFormula], [2011, 'United States', 800, 700, 900, 950, $columnFormula], ]; $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A1'); // Create Table $helper->log('Create Table'); $table = new Table('A1:G16', 'Sales_Data'); // +1 row for totalsRow $table->setShowTotalsRow(true); $table->setRange('A1:G16'); // +1 row for totalsRow // Set Column Formula $table->getColumn('G')->setColumnFormula($columnFormula); $helper->log('Add Totals Row'); // Table column label not implemented yet, $table->getColumn('A')->setTotalsRowLabel('Total'); // So set the label directly to the cell $spreadsheet->getActiveSheet()->getCell('A16')->setValue('Total'); // Table column function not implemented yet, $table->getColumn('G')->setTotalsRowFunction('sum'); // So set the formula directly to the cell $spreadsheet->getActiveSheet()->getCell('G16')->setValue('=SUBTOTAL(109,Sales_Data[Sales])'); // Table column function not implemented yet, $table->getColumn('C')->setTotalsRowFunction('sum'); $table->getColumn('D')->setTotalsRowFunction('sum'); $table->getColumn('E')->setTotalsRowFunction('sum'); $table->getColumn('F')->setTotalsRowFunction('sum'); // So set the formulae directly to the cells $spreadsheet->getActiveSheet()->getCell('C16')->setValue('=SUBTOTAL(109,Sales_Data[Q1])'); $spreadsheet->getActiveSheet()->getCell('D16')->setValue('=SUBTOTAL(109,Sales_Data[Q2])'); $spreadsheet->getActiveSheet()->getCell('E16')->setValue('=SUBTOTAL(109,Sales_Data[Q3])'); $spreadsheet->getActiveSheet()->getCell('F16')->setValue('=SUBTOTAL(109,Sales_Data[Q4])'); // Add Table to Worksheet $helper->log('Add Table to Worksheet'); $spreadsheet->getActiveSheet()->addTable($table); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, false, true, true)); $helper->log('Calculate Structured References'); $helper->displayGrid($spreadsheet->getActiveSheet()->toArray(null, true, true, true), true); // Save $helper->write($spreadsheet, __FILE__, ['Xlsx']); ================================================ FILE: samples/Wizards/Header.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } $currencies = [ '$' => 'US Dollars ($)', '€' => 'Euro (€)', '¥' => 'Japanese Yen (¥)', '£' => 'Pound Sterling (£)', '₹' => 'Rupee (₹)', '₽' => 'Rouble (₽)', ]; ?>

>
>Leading >Trailing

log('The Sample Number Value must be numeric'); } elseif (!is_numeric($_POST['decimals']) || str_contains((string) $_POST['decimals'], '.') || (int) $_POST['decimals'] < 0) { $helper->log('The Decimal Places value must be positive integer'); } elseif (!in_array($_POST['currency'], array_keys($currencies), true)) { $helper->log('Unrecognized currency symbol'); } else { try { $wizard = new Wizard\Accounting($_POST['currency'], (int) $_POST['decimals'], isset($_POST['thousands']), (bool) $_POST['position']); $mask = $wizard->format(); $example = (string) NumberFormat::toFormattedString((float) $_POST['number'], $mask); $helper->log('
Code:
'); $helper->log('use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;'); $helper->log( "\$wizard = new Wizard\\Accounting('{$_POST['currency']}', {$_POST['decimals']}, Wizard\\Number::" . (isset($_POST['thousands']) ? 'WITH_THOUSANDS_SEPARATOR' : 'WITHOUT_THOUSANDS_SEPARATOR') . ', Wizard\Currency::' . (((bool) $_POST['position']) ? 'LEADING_SYMBOL' : 'TRAILING_SYMBOL') . ');' ); $helper->log('$mask = $wizard->format();'); $helper->log('
echo (string) $mask;'); $helper->log('
Mask:
'); $helper->log($mask . '
'); $helper->log('
Example:
'); $helper->log($example); } catch (SpreadsheetException $e) { $helper->log("Exception: {$e->getMessage()}"); } } } ================================================ FILE: samples/Wizards/NumberFormat/Currency.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } $negatives = [ CurrencyNegative::minus, CurrencyNegative::redMinus, CurrencyNegative::parentheses, CurrencyNegative::redParentheses, ]; $negativesString = [ 'CurrencyNegative::minus', 'CurrencyNegative::redMinus', 'CurrencyNegative::parentheses', 'CurrencyNegative::redParentheses', ]; $currencies = [ '$' => 'US Dollars ($)', '€' => 'Euro (€)', '¥' => 'Japanese Yen (¥)', '£' => 'Pound Sterling (£)', '₹' => 'Rupee (₹)', '₽' => 'Rouble (₽)', ]; $postNegative = StringHelper::convertPostToString('negative'); if (!in_array($postNegative, ['0', '1', '2', '3'], true)) { $postNegative = '0'; } $postNegative = (int) $postNegative; ?>

>
>Leading >Trailing
>Minus Sign >Red Minus Sign >Parentheses >Red Parentheses

log('The Sample Number Value must be numeric'); } elseif (!is_numeric($_POST['decimals']) || str_contains((string) $_POST['decimals'], '.') || (int) $_POST['decimals'] < 0) { $helper->log('The Decimal Places value must be positive integer'); } elseif (!in_array($_POST['currency'], array_keys($currencies), true)) { $helper->log('Unrecognized currency symbol'); } else { try { $negative = $negatives[$postNegative]; $wizard = new Wizard\Currency($_POST['currency'], (int) $_POST['decimals'], isset($_POST['thousands']), (bool) $_POST['position']); $wizard->setNegative($negative); $mask = $wizard->format(); $example = (string) NumberFormat::toFormattedString((float) $_POST['number'], $mask, [HtmlWriter::class, 'formatColorStatic']); $helper->log('
Code:
'); $helper->log('use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;'); $helper->log('use PhpOffice\PhpSpreadsheet\Style\NumberFormat\CurrencyNegative;'); $helper->log( "\$wizard = new Wizard\\Currency('{$_POST['currency']}', {$_POST['decimals']}, Wizard\\Number::" . (isset($_POST['thousands']) ? 'WITH_THOUSANDS_SEPARATOR' : 'WITHOUT_THOUSANDS_SEPARATOR') . ', Wizard\Currency::' . (((bool) $_POST['position']) ? 'LEADING_SYMBOL' : 'TRAILING_SYMBOL') . ');' ); $helper->log('$wizard->setNegative(' . $negativesString[$postNegative] . ');'); $helper->log('$mask = $wizard->format();'); $helper->log('
echo (string) $mask;'); $helper->log('
Mask:
'); $helper->log($mask . '
'); $helper->log('
Example:
'); $helper->log($example); } catch (SpreadsheetException $e) { $helper->log("Exception: {$e->getMessage()}"); } } } ================================================ FILE: samples/Wizards/NumberFormat/Number.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } ?>

>

log('The Sample Number Value must be numeric'); } elseif (!is_numeric($_POST['decimals']) || str_contains((string) $_POST['decimals'], '.') || (int) $_POST['decimals'] < 0) { $helper->log('The Decimal Places value must be positive integer'); } else { try { $wizard = new Wizard\Number((int) $_POST['decimals'], isset($_POST['thousands'])); $mask = $wizard->format(); $example = NumberFormat::toFormattedString((float) $_POST['number'], $mask); $helper->log('
Code:
'); $helper->log('use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;'); $helper->log( "\$mask = Wizard\\Number({$_POST['decimals']}, Wizard\\Number::" . (isset($_POST['thousands']) ? 'WITH_THOUSANDS_SEPARATOR' : 'WITHOUT_THOUSANDS_SEPARATOR') . ');
' ); $helper->log('echo (string) $mask;'); $helper->log('
Mask:'); $helper->log($mask); $helper->log('Example:'); $helper->log($example); } catch (SpreadsheetException $e) { $helper->log("Exception: {$e->getMessage()}"); } } } ================================================ FILE: samples/Wizards/NumberFormat/Percentage.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } ?>


log('The Sample Number Value must be numeric'); } elseif (!is_numeric($_POST['decimals']) || str_contains((string) $_POST['decimals'], '.') || (int) $_POST['decimals'] < 0) { $helper->log('The Decimal Places value must be positive integer'); } else { try { $wizard = new Wizard\Percentage((int) $_POST['decimals']); $mask = $wizard->format(); $example = (string) NumberFormat::toFormattedString((float) $_POST['number'], $mask); $helper->log('
Code:
'); $helper->log('use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;'); $helper->log("\$mask = Wizard\\Percentage({$_POST['decimals']});
"); $helper->log('echo (string) $mask;'); $helper->log('
Mask:
'); $helper->log($mask . '
'); $helper->log('
Example:
'); $helper->log($example); } catch (SpreadsheetException $e) { $helper->log("Exception: {$e->getMessage()}"); } } } ================================================ FILE: samples/Wizards/NumberFormat/Scientific.php ================================================ isCli()) { $helper->log('This example should only be run from a Web Browser' . PHP_EOL); return; } ?>


log('The Sample Number Value must be numeric'); } elseif (!is_numeric($_POST['decimals']) || str_contains((string) $_POST['decimals'], '.') || (int) $_POST['decimals'] < 0) { $helper->log('The Decimal Places value must be positive integer'); } else { try { $wizard = new Wizard\Scientific((int) $_POST['decimals']); $mask = $wizard->format(); $example = (string) NumberFormat::toFormattedString((float) $_POST['number'], $mask); $helper->log('
Code:
'); $helper->log('use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;'); $helper->log("\$mask = Wizard\\Scientific({$_POST['decimals']});
"); $helper->log('echo (string) $mask;'); $helper->log('
Mask:
'); $helper->log($mask . '
'); $helper->log('
Example:
'); $helper->log($example); } catch (SpreadsheetException $e) { $helper->log("Exception: {$e->getMessage()}"); } } } ================================================ FILE: samples/bootstrap/css/phpspreadsheet.css ================================================ body { padding-top: 20px; padding-bottom: 20px; } .navbar { margin-bottom: 20px; } .navbar + h1 { margin-top: 70px; } .passed { color: #339900; } .failed { color: #ff0000; } ================================================ FILE: samples/download.php ================================================ getTemporaryFolder(), $filename, $filetype); $downloader->download(); } catch (Exception $e) { exit($e->getMessage()); } ================================================ FILE: samples/index.php ================================================ version_compare(PHP_VERSION, '8.1', '>='), 'PHP extension XML' => extension_loaded('xml'), 'PHP extension xmlwriter' => extension_loaded('xmlwriter'), 'PHP extension mbstring' => extension_loaded('mbstring'), 'PHP extension ZipArchive' => extension_loaded('zip'), 'PHP extension GD (optional)' => extension_loaded('gd'), 'PHP extension dom (optional)' => extension_loaded('dom'), ]; /** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */ if (!$helper->isCli()) { ?>

Welcome to PHPSpreadsheet, a library written in pure PHP and providing a set of classes that allow you to read from and to write to different spreadsheet file formats, like Excel and LibreOffice Calc.

 

Fork us on Github! Read the Docs

Requirement check'; echo '
    '; foreach ($requirements as $label => $result) { $status = $result ? 'passed' : 'failed'; echo "
  • {$label} ... {$status}
  • "; } echo '
'; } else { echo 'Requirement check:' . PHP_EOL; foreach ($requirements as $label => $result) { $status = $result ? '32m passed' : '31m failed'; echo "{$label} ... \033[{$status}\033[0m" . PHP_EOL; } } ================================================ FILE: samples/templates/46readHtml.html ================================================ Competency List
Color Name HEX Color
Black #000000  
Blue #0000FF  
Green #008000  
Cyan #00FFFF  
Purple #800080  
Grey #808080  
SkyBlue #87CEEB  
Brown #A52A2A  
Silver #C0C0C0  
Chocolate #D2691E  
Tan #D2B48C  
Violet #EE82EE  
Red #FF0000  
Pink #FFC0CB  
Gold #FFD700  
Yellow #FFFF00  
LightYellow #FFFFE0  
White #FFFFFF  
================================================ FILE: samples/templates/Excel2003XMLTest.xml ================================================ 3 #000000 4 #0000ff 5 #008000 6 #00ccff 7 #800080 8 #993366 9 #c0c0c0 10 #c47512 11 #ccffcc 12 #ddbc7d 13 #ff0000 14 #ff00ff 15 #ff6600 16 #ff9900 17 #ff99cc 18 #ffff00 9000 13860 240 75 False False Test String 1 Test for a simple colour-formatted string 1 12 11 1960-12-19T00:00:00.000
================================================ FILE: samples/templates/excel2003.xml ================================================ Xml2003 Workbook Test Gnumeric Workbook Subject Mark Baker PHPExcel Xml Reader Test Keywords Some comments about the PHPExcel Gnumeric Reader Owen Leibman 2010-09-02T20:48:39Z 2010-09-03T21:48:39Z PHPExcel Xml Reader Test Category Maarten Balliauw PHPExcel https://github.com/PHPOffice/PhpSpreadsheet 16.00 AbCd1234 2019-01-31T07:00:00Z 1 3 2 3.14159 8964 23040 32767 32767 False False Test String 1Test for a simple colour-formatted string 1 5 A E 6 AE Test - String 2 2 6 B F 8 BF Dot Test #3 3 7 C G 10 CG Red Red Dash Test with (") in string 4 8 D H 12 DH Orange Orange Dash/Dot/Dot 10 26 36 Yellow Yellow Dash/Dot Test #3 1.23 1 1 22 Green Green Thin Line Test #3 2.34 0 0 36 Blue Blue Thick Dash/Dot/Dot Test #3 3.45 Purple Purple Variant Thick Dash/Dot/Dot Pink Pink Thick Dash/Dot 1960-12-19T00:00:00.000 TOP 0 Brown Brown Thick Dash 1.5 #DIV/0! Thick Line BOTTOM Extra Thick Line 1899-12-31T02:30:00.000 Мойва сушенаяTests for UTF-8 content Double Line LEFT Ärendetext 1960-12-19T01:30:00.000 Højde RIGHT BOX Test Column 1 Test Column 2 Patterned Patterned 2 Test Column 3 PhpSpreadsheet Underline None Rotate 90 Rotate 45 Rotate -90 Rotate -45 Underline 1 Subscript Underline 2 Superscript Underline 3 Underline 4 I don't know if Gnumeric supports Rich Text in the same way as Excel, And this row should be autofit height with text wrap Blue with underline 5 5 #NAME? Hidden row above
600 600 3 3 18 10 False False Heading 1 Heading 2 Third Heading Date Heading Time Heading Adjusted Date Adjusted Number ABC 1 1.1100000000000001 2001-01-01T00:00:00.000 1899-12-31T01:00:00.000 2000-12-31T00:00:00.000 1.1100000000000001 A 1A BCD 2 2.2200000000000002 2002-02-02T00:00:00.000 1899-12-31T02:00:00.000 2002-01-31T00:00:00.000 4.4400000000000004 B 2B CDE 3 3.33 2003-03-03T00:00:00.000 1899-12-31T03:00:00.000 2003-02-28T00:00:00.000 9.99 C 3C DEF 4 4.4400000000000004 2004-04-03T23:00:00.000 1899-12-31T04:00:00.000 2004-03-30T23:00:00.000 17.760000000000002 D 4D EFG 5 5.55 2005-05-04T23:00:00.000 1899-12-31T05:00:00.000 2005-04-29T23:00:00.000 27.75 E 5E FGH 6 6.66 2006-06-05T23:00:00.000 1899-12-31T06:00:00.000 2006-05-30T23:00:00.000 39.96 F 6F GHI 7 7.77 2007-07-06T23:00:00.000 1899-12-31T07:00:00.000 2007-06-29T23:00:00.000 54.39 G 7G HIJ 8 8.8800000000000008 2008-08-07T23:00:00.000 1899-12-31T08:00:00.000 2008-07-30T23:00:00.000 71.040000000000006 H 8H IJK 9 9.99 2009-09-08T23:00:00.000 1899-12-31T09:00:00.000 2009-08-30T23:00:00.000 89.91 I 9I JKL 10 11.1 2010-10-09T23:00:00.000 1899-12-31T10:00:00.000 2010-09-29T23:00:00.000 111 J 10J KLM 11 12.21 2011-11-11T00:00:00.000 1899-12-31T11:00:00.000 2011-10-31T00:00:00.000 134.31 K 11K LMN 12 13.32 2012-12-12T00:00:00.000 1900-01-12T00:00:00.000 2012-11-30T00:00:00.000 159.84 L 12L ZYX -1 -1.1100000000000001 1999-12-01T00:00:00.000 1899-12-31T23:00:00.000 1999-12-02T00:00:00.000 1.1100000000000001 M -1M
600 600 3 8 R1C9:R15C11 False False ================================================ FILE: samples/templates/largeSpreadsheet.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set properties'); $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'); // Create a first sheet $helper->log('Add data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname'); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Lastname'); $spreadsheet->getActiveSheet()->setCellValue('C1', 'Phone'); $spreadsheet->getActiveSheet()->setCellValue('D1', 'Fax'); $spreadsheet->getActiveSheet()->setCellValue('E1', 'Is Client ?'); // Hide "Phone" and "fax" column $helper->log("Hide 'Phone' and 'fax' columns"); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setVisible(false); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false); // Set outline levels $helper->log('Set outline levels'); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1) ->setVisible(false) ->setCollapsed(true); // Freeze panes $helper->log('Freeze panes'); $spreadsheet->getActiveSheet()->freezePane('A2'); // Rows to repeat at top $helper->log('Rows to repeat at top'); $spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1); // Add data for ($i = 2; $i <= 5000; ++$i) { $spreadsheet->getActiveSheet()->setCellValue('A' . $i, "FName $i") ->setCellValue('B' . $i, "LName $i") ->setCellValue('C' . $i, "PhoneNo $i") ->setCellValue('D' . $i, "FaxNo $i") ->setCellValue('E' . $i, true); } return $spreadsheet; ================================================ FILE: samples/templates/sampleSpreadsheet.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Create a first sheet, representing sales data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Invoice'); $date = new DateTime('now'); $date->setTime(0, 0, 0); $spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel($date)); $spreadsheet->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_XLSX15); $spreadsheet->getActiveSheet()->setCellValue('E1', '#12566'); $spreadsheet->getActiveSheet()->setCellValue('A3', 'Product Id'); $spreadsheet->getActiveSheet()->setCellValue('B3', 'Description'); $spreadsheet->getActiveSheet()->setCellValue('C3', 'Price'); $spreadsheet->getActiveSheet()->setCellValue('D3', 'Amount'); $spreadsheet->getActiveSheet()->setCellValue('E3', 'Total'); $spreadsheet->getActiveSheet()->setCellValue('A4', '1001'); $spreadsheet->getActiveSheet()->setCellValue('B4', 'PHP for dummies'); $spreadsheet->getActiveSheet()->setCellValue('C4', '20'); $spreadsheet->getActiveSheet()->setCellValue('D4', '1'); $spreadsheet->getActiveSheet()->setCellValue('E4', '=IF(D4<>"",C4*D4,"")'); $spreadsheet->getActiveSheet()->setCellValue('A5', '1012'); $spreadsheet->getActiveSheet()->setCellValue('B5', 'OpenXML for dummies'); $spreadsheet->getActiveSheet()->setCellValue('C5', '22'); $spreadsheet->getActiveSheet()->setCellValue('D5', '2'); $spreadsheet->getActiveSheet()->setCellValue('E5', '=IF(D5<>"",C5*D5,"")'); $spreadsheet->getActiveSheet()->setCellValue('E6', '=IF(D6<>"",C6*D6,"")'); $spreadsheet->getActiveSheet()->setCellValue('E7', '=IF(D7<>"",C7*D7,"")'); $spreadsheet->getActiveSheet()->setCellValue('E8', '=IF(D8<>"",C8*D8,"")'); $spreadsheet->getActiveSheet()->setCellValue('E9', '=IF(D9<>"",C9*D9,"")'); $spreadsheet->getActiveSheet()->setCellValue('D11', 'Total excl.:'); $spreadsheet->getActiveSheet()->setCellValue('E11', '=SUM(E4:E9)'); $spreadsheet->getActiveSheet()->setCellValue('D12', 'VAT:'); $spreadsheet->getActiveSheet()->setCellValue('E12', '=E11*0.21'); $spreadsheet->getActiveSheet()->setCellValue('D13', 'Total incl.:'); $spreadsheet->getActiveSheet()->setCellValue('E13', '=E11+E12'); // Add comment $helper->log('Add comments'); $spreadsheet->getActiveSheet()->getComment('E11')->setAuthor('PhpSpreadsheet'); $commentRichText = $spreadsheet->getActiveSheet()->getComment('E11')->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFontOrThrow()->setBold(true); $spreadsheet->getActiveSheet()->getComment('E11')->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet()->getComment('E11')->getText()->createTextRun('Total amount on the current invoice, excluding VAT.'); $spreadsheet->getActiveSheet()->getComment('E12')->setAuthor('PhpSpreadsheet'); $commentRichText = $spreadsheet->getActiveSheet()->getComment('E12')->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFontOrThrow()->setBold(true); $spreadsheet->getActiveSheet()->getComment('E12')->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet()->getComment('E12')->getText()->createTextRun('Total amount of VAT on the current invoice.'); $spreadsheet->getActiveSheet()->getComment('E13')->setAuthor('PhpSpreadsheet'); $commentRichText = $spreadsheet->getActiveSheet()->getComment('E13')->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFontOrThrow()->setBold(true); $spreadsheet->getActiveSheet()->getComment('E13')->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet()->getComment('E13')->getText()->createTextRun('Total amount on the current invoice, including VAT.'); $spreadsheet->getActiveSheet()->getComment('E13')->setWidth('100pt'); $spreadsheet->getActiveSheet()->getComment('E13')->setHeight('100pt'); $spreadsheet->getActiveSheet()->getComment('E13')->setMarginLeft('150pt'); $spreadsheet->getActiveSheet()->getComment('E13')->getFillColor()->setRGB('EEEEEE'); // Add rich-text string $helper->log('Add rich-text string'); $richText = new RichText(); $richText->createText('This invoice is '); $payable = $richText->createTextRun('payable within thirty days after the end of the month'); $payable->getFontOrThrow()->setBold(true); $payable->getFontOrThrow()->setItalic(true); $payable->getFontOrThrow()->setColor(new Color(Color::COLOR_DARKGREEN)); $richText->createText(', unless specified otherwise on the invoice.'); $spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText); // Merge cells $helper->log('Merge cells'); $spreadsheet->getActiveSheet()->mergeCells('A18:E22'); $spreadsheet->getActiveSheet()->mergeCells('A28:B28'); // Just to test... $spreadsheet->getActiveSheet()->unmergeCells('A28:B28'); // Just to test... // Protect cells $helper->log('Protect cells'); $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); // Needs to be set to true in order to enable any worksheet protection! $spreadsheet->getActiveSheet()->protectCells('A3:E13', 'PhpSpreadsheet'); // Set cell number formats $helper->log('Set cell number formats'); $spreadsheet->getActiveSheet()->getStyle('E4:E13')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_INTEGER); // Set column widths $helper->log('Set column widths'); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(12); // Set fonts $helper->log('Set fonts'); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara'); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setSize(20); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(Font::UNDERLINE_SINGLE); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(Color::COLOR_WHITE); $spreadsheet->getActiveSheet()->getStyle('D1')->getFont()->getColor()->setARGB(Color::COLOR_WHITE); $spreadsheet->getActiveSheet()->getStyle('E1')->getFont()->getColor()->setARGB(Color::COLOR_WHITE); $spreadsheet->getActiveSheet()->getStyle('D13')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('E13')->getFont()->setBold(true); // Set alignments $helper->log('Set alignments'); $spreadsheet->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('D12')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('D13')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_JUSTIFY); $spreadsheet->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); $spreadsheet->getActiveSheet()->getStyle('B5')->getAlignment()->setShrinkToFit(true); // Set thin black border outline around column $helper->log('Set thin black border outline around column'); $styleThinBlackBorderOutline = [ 'borders' => [ 'outline' => [ 'borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FF000000'], ], ], ]; $spreadsheet->getActiveSheet()->getStyle('A4:E10')->applyFromArray($styleThinBlackBorderOutline); // Set thick brown border outline around "Total" $helper->log('Set thick brown border outline around Total'); $styleThickBrownBorderOutline = [ 'borders' => [ 'outline' => [ 'borderStyle' => Border::BORDER_THICK, 'color' => ['argb' => 'FF993300'], ], ], ]; $spreadsheet->getActiveSheet()->getStyle('D13:E13')->applyFromArray($styleThickBrownBorderOutline); // Set fills $helper->log('Set fills'); $spreadsheet->getActiveSheet()->getStyle('A1:E1')->getFill()->setFillType(Fill::FILL_SOLID); $spreadsheet->getActiveSheet()->getStyle('A1:E1')->getFill()->getStartColor()->setARGB('FF808080'); // Set style for header row using alternative method $helper->log('Set style for header row using alternative method'); $spreadsheet->getActiveSheet()->getStyle('A3:E3')->applyFromArray( [ 'font' => [ 'bold' => true, ], 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_RIGHT, ], 'borders' => [ 'top' => [ 'borderStyle' => Border::BORDER_THIN, ], ], 'fill' => [ 'fillType' => Fill::FILL_GRADIENT_LINEAR, 'rotation' => 90, 'startColor' => [ 'argb' => 'FFA0A0A0', ], 'endColor' => [ 'argb' => 'FFFFFFFF', ], ], ] ); $spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray( [ 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_LEFT, ], 'borders' => [ 'left' => [ 'borderStyle' => Border::BORDER_THIN, ], ], ] ); $spreadsheet->getActiveSheet()->getStyle('B3')->applyFromArray( [ 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_LEFT, ], ] ); $spreadsheet->getActiveSheet()->getStyle('E3')->applyFromArray( [ 'borders' => [ 'right' => [ 'borderStyle' => Border::BORDER_THIN, ], ], ] ); // Unprotect a cell $helper->log('Unprotect a cell'); $spreadsheet->getActiveSheet()->getStyle('B1')->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); // Add a hyperlink to the sheet $helper->log('Add a hyperlink to an external website'); $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.example.com'); $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('https://www.example.com'); $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setTooltip('Navigate to website'); $spreadsheet->getActiveSheet()->getStyle('E26')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('E26')->getFont()->setHyperlinkTheme(); $helper->log('Add a hyperlink to another cell on a different worksheet within the workbook'); $spreadsheet->getActiveSheet()->setCellValue('E27', 'Terms and conditions'); $spreadsheet->getActiveSheet()->getCell('E27')->getHyperlink()->setUrl("sheet://'Terms and conditions'!A1"); $spreadsheet->getActiveSheet()->getCell('E27')->getHyperlink()->setTooltip('Review terms and conditions'); $spreadsheet->getActiveSheet()->getStyle('E27')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('E27')->getFont()->setHyperlinkTheme(); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new Drawing(); $drawing->setName('Logo'); $drawing->setDescription('Logo'); $drawing->setPath(__DIR__ . '/../images/officelogo.jpg'); $drawing->setHeight(36); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new Drawing(); $drawing->setName('Paid'); $drawing->setDescription('Paid'); $drawing->setPath(__DIR__ . '/../images/paid.png'); $drawing->setCoordinates('B15'); $drawing->setOffsetX(110); $drawing->setRotation(25); $drawing->getShadow()->setVisible(true); $drawing->getShadow()->setDirection(45); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new Drawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setDescription('PhpSpreadsheet logo'); $drawing->setPath(__DIR__ . '/../images/PhpSpreadsheet_logo.png'); $drawing->setHeight(36); $drawing->setCoordinates('D24'); $drawing->setOffsetX(10); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Play around with inserting and removing rows and columns $helper->log('Play around with inserting and removing rows and columns'); $spreadsheet->getActiveSheet()->insertNewRowBefore(6, 10); $spreadsheet->getActiveSheet()->removeRow(6, 10); $spreadsheet->getActiveSheet()->insertNewColumnBefore('E', 5); $spreadsheet->getActiveSheet()->removeColumn('E', 5); // Set header and footer. When no different headers for odd/even are used, odd header is assumed. $helper->log('Set header/footer'); $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BInvoice&RPrinted on &D'); $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N'); // Set page orientation and size $helper->log('Set page orientation and size'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT); $spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4); // Rename first worksheet $helper->log('Rename first worksheet'); $spreadsheet->getActiveSheet()->setTitle('Invoice'); // Create a new worksheet, after the default sheet $helper->log('Create a second Worksheet object'); $spreadsheet->createSheet(); // Llorem ipsum... $sLloremIpsum = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus eget ante. Sed cursus nunc semper tortor. Aliquam luctus purus non elit. Fusce vel elit commodo sapien dignissim dignissim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur accumsan magna sed massa. Nullam bibendum quam ac ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin augue. Praesent malesuada justo sed orci. Pellentesque lacus ligula, sodales quis, ultricies a, ultricies vitae, elit. Sed luctus consectetuer dolor. Vivamus vel sem ut nisi sodales accumsan. Nunc et felis. Suspendisse semper viverra odio. Morbi at odio. Integer a orci a purus venenatis molestie. Nam mattis. Praesent rhoncus, nisi vel mattis auctor, neque nisi faucibus sem, non dapibus elit pede ac nisl. Cras turpis.'; // Add some data to the second sheet, resembling some different data types $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(1); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Terms and conditions'); $spreadsheet->getActiveSheet()->setCellValue('A3', $sLloremIpsum); $spreadsheet->getActiveSheet()->setCellValue('A4', $sLloremIpsum); $spreadsheet->getActiveSheet()->setCellValue('A5', $sLloremIpsum); $spreadsheet->getActiveSheet()->setCellValue('A6', $sLloremIpsum); // Set the worksheet tab color $helper->log('Set the worksheet tab color'); $spreadsheet->getActiveSheet()->getTabColor()->setARGB('FF0094FF'); // Set alignments $helper->log('Set alignments'); $spreadsheet->getActiveSheet()->getStyle('A3:A6')->getAlignment()->setWrapText(true); // Set column widths $helper->log('Set column widths'); $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(80); // Set fonts $helper->log('Set fonts'); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setName('Candara'); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setSize(20); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setUnderline(Font::UNDERLINE_SINGLE); $spreadsheet->getActiveSheet()->getStyle('A3:A6')->getFont()->setSize(8); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new Drawing(); $drawing->setName('Terms and conditions'); $drawing->setDescription('Terms and conditions'); $drawing->setPath(__DIR__ . '/../images/termsconditions.jpg'); $drawing->setCoordinates('B14'); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Set page orientation and size $helper->log('Set page orientation and size'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4); // Rename second worksheet $helper->log('Rename second worksheet'); $spreadsheet->getActiveSheet()->setTitle('Terms and conditions'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); return $spreadsheet; ================================================ FILE: samples/templates/sampleSpreadsheet2.php ================================================ log('Create new Spreadsheet object'); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log('Set document properties'); $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'); // Create a first sheet, representing sales data $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Invoice'); $date = new DateTime('now'); $date->setTime(0, 0, 0); $spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel($date)); $spreadsheet->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_XLSX15); $spreadsheet->getActiveSheet()->setCellValue('E1', '#12566'); $spreadsheet->getActiveSheet()->setCellValue('A3', 'Product Id'); $spreadsheet->getActiveSheet()->setCellValue('B3', 'Description'); $spreadsheet->getActiveSheet()->setCellValue('C3', 'Price'); $spreadsheet->getActiveSheet()->setCellValue('D3', 'Amount'); $spreadsheet->getActiveSheet()->setCellValue('E3', 'Total'); $spreadsheet->getActiveSheet()->setCellValue('A4', '1001'); $spreadsheet->getActiveSheet()->setCellValue('B4', 'PHP for dummies'); $spreadsheet->getActiveSheet()->setCellValue('C4', '20'); $spreadsheet->getActiveSheet()->setCellValue('D4', '1'); $spreadsheet->getActiveSheet()->setCellValue('E4', '=IF(D4<>"",C4*D4,"")'); $spreadsheet->getActiveSheet()->setCellValue('A5', '1012'); $spreadsheet->getActiveSheet()->setCellValue('B5', 'OpenXML for dummies'); $spreadsheet->getActiveSheet()->setCellValue('C5', '22'); $spreadsheet->getActiveSheet()->setCellValue('D5', '2'); $spreadsheet->getActiveSheet()->setCellValue('E5', '=IF(D5<>"",C5*D5,"")'); $spreadsheet->getActiveSheet()->setCellValue('E6', '=IF(D6<>"",C6*D6,"")'); $spreadsheet->getActiveSheet()->setCellValue('E7', '=IF(D7<>"",C7*D7,"")'); $spreadsheet->getActiveSheet()->setCellValue('E8', '=IF(D8<>"",C8*D8,"")'); $spreadsheet->getActiveSheet()->setCellValue('E9', '=IF(D9<>"",C9*D9,"")'); $spreadsheet->getActiveSheet()->setCellValue('D11', 'Total excl.:'); $spreadsheet->getActiveSheet()->setCellValue('E11', '=SUM(E4:E9)'); $spreadsheet->getActiveSheet()->setCellValue('D12', 'VAT:'); $spreadsheet->getActiveSheet()->setCellValue('E12', '=E11*0.21'); $spreadsheet->getActiveSheet()->setCellValue('D13', 'Total incl.:'); $spreadsheet->getActiveSheet()->setCellValue('E13', '=E11+E12'); // Add comment $helper->log('Add comments'); $spreadsheet->getActiveSheet()->getComment('E11')->setAuthor('PhpSpreadsheet'); $commentRichText = $spreadsheet->getActiveSheet()->getComment('E11')->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFontOrThrow()->setBold(true); $spreadsheet->getActiveSheet()->getComment('E11')->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet()->getComment('E11')->getText()->createTextRun('Total amount on the current invoice, excluding VAT.'); $spreadsheet->getActiveSheet()->getComment('E12')->setAuthor('PhpSpreadsheet'); $commentRichText = $spreadsheet->getActiveSheet()->getComment('E12')->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFontOrThrow()->setBold(true); $spreadsheet->getActiveSheet()->getComment('E12')->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet()->getComment('E12')->getText()->createTextRun('Total amount of VAT on the current invoice.'); $spreadsheet->getActiveSheet()->getComment('E13')->setAuthor('PhpSpreadsheet'); $commentRichText = $spreadsheet->getActiveSheet()->getComment('E13')->getText()->createTextRun('PhpSpreadsheet:'); $commentRichText->getFontOrThrow()->setBold(true); $spreadsheet->getActiveSheet()->getComment('E13')->getText()->createTextRun("\r\n"); $spreadsheet->getActiveSheet()->getComment('E13')->getText()->createTextRun('Total amount on the current invoice, including VAT.'); $spreadsheet->getActiveSheet()->getComment('E13')->setWidth('100pt'); $spreadsheet->getActiveSheet()->getComment('E13')->setHeight('100pt'); $spreadsheet->getActiveSheet()->getComment('E13')->setMarginLeft('150pt'); $spreadsheet->getActiveSheet()->getComment('E13')->getFillColor()->setRGB('EEEEEE'); // Add rich-text string $helper->log('Add rich-text string'); $richText = new RichText(); $richText->createText('This invoice is '); $payable = $richText->createTextRun('payable within thirty days after the end of the month'); $payable->getFontOrThrow()->setBold(true); $payable->getFontOrThrow()->setItalic(true); $payable->getFontOrThrow()->setColor(new Color(Color::COLOR_DARKGREEN)); $richText->createText(', unless specified otherwise on the invoice.'); $spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText); // Merge cells $helper->log('Merge cells'); $spreadsheet->getActiveSheet()->mergeCells('A18:E22'); $spreadsheet->getActiveSheet()->mergeCells('A28:B28'); // Just to test... $spreadsheet->getActiveSheet()->unmergeCells('A28:B28'); // Just to test... // Protect cells $helper->log('Protect cells'); $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); // Needs to be set to true in order to enable any worksheet protection! $spreadsheet->getActiveSheet()->protectCells('A3:E13', 'PhpSpreadsheet'); // Set cell number formats $helper->log('Set cell number formats'); $spreadsheet->getActiveSheet()->getStyle('E4:E13')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_INTEGER); // Set column widths $helper->log('Set column widths'); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(12); // Set fonts $helper->log('Set fonts'); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara'); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setSize(20); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(Font::UNDERLINE_SINGLE); $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(Color::COLOR_WHITE); $spreadsheet->getActiveSheet()->getStyle('D1')->getFont()->getColor()->setARGB(Color::COLOR_WHITE); $spreadsheet->getActiveSheet()->getStyle('E1')->getFont()->getColor()->setARGB(Color::COLOR_WHITE); $spreadsheet->getActiveSheet()->getStyle('D13')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('E13')->getFont()->setBold(true); // Set alignments $helper->log('Set alignments'); $spreadsheet->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('D12')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('D13')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_JUSTIFY); $spreadsheet->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); $spreadsheet->getActiveSheet()->getStyle('B5')->getAlignment()->setShrinkToFit(true); // Set thin black border outline around column $helper->log('Set thin black border outline around column'); $styleThinBlackBorderOutline = [ 'borders' => [ 'outline' => [ 'borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FF000000'], ], ], ]; $spreadsheet->getActiveSheet()->getStyle('A4:E10')->applyFromArray($styleThinBlackBorderOutline); // Set thick brown border outline around "Total" $helper->log('Set thick brown border outline around Total'); $styleThickBrownBorderOutline = [ 'borders' => [ 'outline' => [ 'borderStyle' => Border::BORDER_THICK, 'color' => ['argb' => 'FF993300'], ], ], ]; $spreadsheet->getActiveSheet()->getStyle('D13:E13')->applyFromArray($styleThickBrownBorderOutline); // Set fills $helper->log('Set fills'); $spreadsheet->getActiveSheet()->getStyle('A1:E1')->getFill()->setFillType(Fill::FILL_SOLID); $spreadsheet->getActiveSheet()->getStyle('A1:E1')->getFill()->getStartColor()->setARGB('FF808080'); // Set style for header row using alternative method $helper->log('Set style for header row using alternative method'); $spreadsheet->getActiveSheet()->getStyle('A3:E3')->applyFromArray( [ 'font' => [ 'bold' => true, ], 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_RIGHT, ], 'borders' => [ 'top' => [ 'borderStyle' => Border::BORDER_THIN, ], ], 'fill' => [ 'fillType' => Fill::FILL_GRADIENT_LINEAR, 'rotation' => 90, 'startColor' => [ 'argb' => 'FFA0A0A0', ], 'endColor' => [ 'argb' => 'FFFFFFFF', ], ], ] ); $spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray( [ 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_LEFT, ], 'borders' => [ 'left' => [ 'borderStyle' => Border::BORDER_THIN, ], ], ] ); $spreadsheet->getActiveSheet()->getStyle('B3')->applyFromArray( [ 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_LEFT, ], ] ); $spreadsheet->getActiveSheet()->getStyle('E3')->applyFromArray( [ 'borders' => [ 'right' => [ 'borderStyle' => Border::BORDER_THIN, ], ], ] ); // Unprotect a cell $helper->log('Unprotect a cell'); $spreadsheet->getActiveSheet()->getStyle('B1')->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); // Add a hyperlink to the sheet $helper->log('Add a hyperlink to an external website'); $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.example.com'); $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('https://www.example.com'); $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setTooltip('Navigate to website'); $spreadsheet->getActiveSheet()->getStyle('E26')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('E26')->getFont()->setHyperlinkTheme(); $helper->log('Add a hyperlink to another cell on a different worksheet within the workbook'); $spreadsheet->getActiveSheet()->setCellValue('E27', 'Terms and conditions'); $spreadsheet->getActiveSheet()->getCell('E27')->getHyperlink()->setUrl("sheet://'Terms and conditions'!A1"); $spreadsheet->getActiveSheet()->getCell('E27')->getHyperlink()->setTooltip('Review terms and conditions'); $spreadsheet->getActiveSheet()->getStyle('E27')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); $spreadsheet->getActiveSheet()->getStyle('E27')->getFont()->setHyperlinkTheme(); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new Drawing(); $drawing->setName('Logo'); $drawing->setDescription('Logo'); $drawing->setPath(__DIR__ . '/../images/officelogo.jpg'); $drawing->setHeight(36); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Add a drawing to the worksheet $helper->log('Add a drawing to the worksheet'); $drawing = new Drawing(); $drawing->setName('Paid'); $drawing->setDescription('Paid'); $drawing->setPath(__DIR__ . '/../images/paid.png'); $drawing->setCoordinates('B15'); $drawing->setOffsetX(110); $drawing->setRotation(25); $drawing->getShadow()->setVisible(true); $drawing->getShadow()->setDirection(45); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Add a drawing to the worksheet $helper->log('Add a drawing with Japanese file name to the worksheet'); $drawing = new Drawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setDescription('PhpSpreadsheet logo'); $drawing->setPath(__DIR__ . '/../images/サンプル.png'); $drawing->setHeight(36); $drawing->setCoordinates('D24'); $drawing->setOffsetX(10); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Play around with inserting and removing rows and columns $helper->log('Play around with inserting and removing rows and columns'); $spreadsheet->getActiveSheet()->insertNewRowBefore(6, 10); $spreadsheet->getActiveSheet()->removeRow(6, 10); $spreadsheet->getActiveSheet()->insertNewColumnBefore('E', 5); $spreadsheet->getActiveSheet()->removeColumn('E', 5); // Set header and footer. When no different headers for odd/even are used, odd header is assumed. $helper->log('Set header/footer'); $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BInvoice&RPrinted on &D'); $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N'); // Set page orientation and size $helper->log('Set page orientation and size'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT); $spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4); // Rename first worksheet $helper->log('Rename first worksheet'); $spreadsheet->getActiveSheet()->setTitle('Invoice'); // Create a new worksheet, after the default sheet $helper->log('Create a second Worksheet object'); $spreadsheet->createSheet(); // Llorem ipsum... $sLloremIpsum = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus eget ante. Sed cursus nunc semper tortor. Aliquam luctus purus non elit. Fusce vel elit commodo sapien dignissim dignissim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur accumsan magna sed massa. Nullam bibendum quam ac ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin augue. Praesent malesuada justo sed orci. Pellentesque lacus ligula, sodales quis, ultricies a, ultricies vitae, elit. Sed luctus consectetuer dolor. Vivamus vel sem ut nisi sodales accumsan. Nunc et felis. Suspendisse semper viverra odio. Morbi at odio. Integer a orci a purus venenatis molestie. Nam mattis. Praesent rhoncus, nisi vel mattis auctor, neque nisi faucibus sem, non dapibus elit pede ac nisl. Cras turpis.'; // Add some data to the second sheet, resembling some different data types $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(1); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Terms and conditions'); $spreadsheet->getActiveSheet()->setCellValue('A3', $sLloremIpsum); $spreadsheet->getActiveSheet()->setCellValue('A4', $sLloremIpsum); $spreadsheet->getActiveSheet()->setCellValue('A5', $sLloremIpsum); $spreadsheet->getActiveSheet()->setCellValue('A6', $sLloremIpsum); // Set the worksheet tab color $helper->log('Set the worksheet tab color'); $spreadsheet->getActiveSheet()->getTabColor()->setARGB('FF0094FF'); // Set alignments $helper->log('Set alignments'); $spreadsheet->getActiveSheet()->getStyle('A3:A6')->getAlignment()->setWrapText(true); // Set column widths $helper->log('Set column widths'); $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(80); // Set fonts $helper->log('Set fonts'); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setName('Candara'); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setSize(20); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setBold(true); $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setUnderline(Font::UNDERLINE_SINGLE); $spreadsheet->getActiveSheet()->getStyle('A3:A6')->getFont()->setSize(8); // Add a drawing to the worksheet $helper->log('Add a drawing with space and # in filename to the worksheet'); $drawing = new Drawing(); $drawing->setName('Terms and conditions'); $drawing->setDescription('Terms and conditions'); $drawing->setPath(__DIR__ . '/../images/terms con#ditions.jpg'); $drawing->setCoordinates('B14'); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Repeat drawing to the worksheet $helper->log('Repeat drawing from other worksheet on this one'); $drawing = new Drawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setDescription('PhpSpreadsheet logo'); $drawing->setPath(__DIR__ . '/../images/サンプル.png'); $drawing->setHeight(36); $drawing->setCoordinates('B18'); $drawing->setOffsetX(10); $drawing->setWorksheet($spreadsheet->getActiveSheet()); // Set page orientation and size $helper->log('Set page orientation and size'); $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); $spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4); // Rename second worksheet $helper->log('Rename second worksheet'); $spreadsheet->getActiveSheet()->setTitle('Terms and conditions'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); return $spreadsheet; ================================================ FILE: src/PhpSpreadsheet/Calculation/ArrayEnabled.php ================================================ initialise($arguments); } /** * Handles array argument processing when the function accepts a single argument that can be an array argument. * Example use for: * DAYOFMONTH() or FACT(). * * @param mixed[] $values * * @return mixed[] */ protected static function evaluateSingleArgumentArray(callable $method, array $values): array { $result = []; foreach ($values as $value) { $result[] = $method($value); } return $result; } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument. * Example use for: * ROUND() or DATE(). * * @return mixed[] */ protected static function evaluateArrayArguments(callable $method, mixed ...$arguments): array { self::initialiseHelper($arguments); $arguments = self::$arrayArgumentHelper->arguments(); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * but only the first few (up to limit) can be an array arguments. * Example use for: * NETWORKDAYS() or CONCATENATE(), where the last argument is a matrix (or a series of values) that need * to be treated as a such rather than as an array arguments. * * @return mixed[] */ protected static function evaluateArrayArgumentsSubset(callable $method, int $limit, mixed ...$arguments): array { self::initialiseHelper(array_slice($arguments, 0, $limit)); $trailingArguments = array_slice($arguments, $limit); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($arguments, $trailingArguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } private static function testFalse(mixed $value): bool { return $value === false; } /** * Handles array argument processing when the function accepts multiple arguments, * but only the last few (from start) can be an array arguments. * Example use for: * Z.TEST() or INDEX(), where the first argument 1 is a matrix that needs to be treated as a dataset * rather than as an array argument. * * @return mixed[] */ protected static function evaluateArrayArgumentsSubsetFrom(callable $method, int $start, mixed ...$arguments): array { $arrayArgumentsSubset = array_combine( range($start, count($arguments) - $start), array_slice($arguments, $start) ); if (self::testFalse($arrayArgumentsSubset)) { return ['#VALUE!']; } self::initialiseHelper($arrayArgumentsSubset); $leadingArguments = array_slice($arguments, 0, $start); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($leadingArguments, $arguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument except for the one specified by ignore. * Example use for: * HLOOKUP() and VLOOKUP(), where argument 1 is a matrix that needs to be treated as a database * rather than as an array argument. * * @return mixed[] */ protected static function evaluateArrayArgumentsIgnore(callable $method, int $ignore, mixed ...$arguments): array { $leadingArguments = array_slice($arguments, 0, $ignore); $ignoreArgument = array_slice($arguments, $ignore, 1); $trailingArguments = array_slice($arguments, $ignore + 1); self::initialiseHelper(array_merge($leadingArguments, [[null]], $trailingArguments)); $arguments = self::$arrayArgumentHelper->arguments(); array_splice($arguments, $ignore, 1, $ignoreArgument); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/BinaryComparison.php ================================================ '' && $operand1[0] == Calculation::FORMULA_STRING_QUOTE) { $operand1 = Calculation::unwrapResult($operand1); } if (ErrorValue::isError($operand1, true)) { /** @var string $operand1 */ return $operand1; } if (is_string($operand2) && $operand2 > '' && $operand2[0] == Calculation::FORMULA_STRING_QUOTE) { $operand2 = Calculation::unwrapResult($operand2); } if (ErrorValue::isError($operand2, true)) { /** @var string $operand2 */ return $operand2; } // Use case-insensitive comparison if not OpenOffice mode if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { if (is_string($operand1)) { $operand1 = StringHelper::strToUpper($operand1); } if (is_string($operand2)) { $operand2 = StringHelper::strToUpper($operand2); } } $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE; return self::evaluateComparison($operand1, $operand2, $operator, $useLowercaseFirstComparison); } private static function evaluateComparison(mixed $operand1, mixed $operand2, string $operator, bool $useLowercaseFirstComparison): bool { return match ($operator) { '=' => self::equal($operand1, $operand2), '>' => self::greaterThan($operand1, $operand2, $useLowercaseFirstComparison), '<' => self::lessThan($operand1, $operand2, $useLowercaseFirstComparison), '>=' => self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison), '<=' => self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison), '<>' => self::notEqual($operand1, $operand2), default => throw new Exception('Unsupported binary comparison operator'), }; } private static function equal(mixed $operand1, mixed $operand2): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = (abs($operand1 - $operand2) < self::DELTA); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 == $operand2; } else { $result = self::strcmpAllowNull($operand1, $operand2) == 0; } return $result; } private static function greaterThanOrEqual(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 > $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 >= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) >= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) >= 0; } return $result; } private static function lessThanOrEqual(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 < $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 <= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) <= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) <= 0; } return $result; } private static function greaterThan(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } private static function lessThan(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } private static function notEqual(mixed $operand1, mixed $operand2): bool { return self::equal($operand1, $operand2) !== true; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Calculation.php ================================================ =:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; // Used only to detect spill operator # const CALCULATION_REGEXP_CELLREF_SPILL = '/' . self::CALCULATION_REGEXP_CELLREF . '#/i'; // Cell reference (with or without a sheet reference) ensuring absolute/relative const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])'; const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\".(?:[^\"]|\"[^!])?\"))!)?(\$?[a-z]{1,3})):(?![.*])'; const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative // Cell ranges ensuring absolute/relative const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})'; // Defined Names: Named Range of cells, or Named Formulae const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)'; // Structured Reference (Fully Qualified and Unqualified) const CALCULATION_REGEXP_STRUCTURED_REFERENCE = '([\p{L}_\\\][\p{L}\p{N}\._]+)?(\[(?:[^\d\]+-])?)'; // Error const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; /** constants */ const RETURN_ARRAY_AS_ERROR = 'error'; const RETURN_ARRAY_AS_VALUE = 'value'; const RETURN_ARRAY_AS_ARRAY = 'array'; /** Preferable to use instance variable instanceArrayReturnType rather than this static property. */ private static string $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; /** Preferable to use this instance variable rather than static returnArrayAsType */ private ?string $instanceArrayReturnType = null; /** * Instance of this class. */ private static ?Calculation $instance = null; /** * Instance of the spreadsheet this Calculation Engine is using. */ private ?Spreadsheet $spreadsheet; /** * Calculation cache. * * @var mixed[] */ private array $calculationCache = []; /** * Calculation cache enabled. */ private bool $calculationCacheEnabled = true; private BranchPruner $branchPruner; protected bool $branchPruningEnabled = true; /** * List of operators that can be used within formulae * The true/false value indicates whether it is a binary operator or a unary operator. */ private const CALCULATION_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * List of binary operators (those that expect two operands). */ private const BINARY_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * The debug log generated by the calculation engine. */ private Logger $debugLog; private bool $suppressFormulaErrors = false; private bool $processingAnchorArray = false; /** * Error message for any error that was raised/thrown by the calculation engine. */ public ?string $formulaError = null; /** * An array of the nested cell references accessed by the calculation engine, used for the debug log. */ private CyclicReferenceStack $cyclicReferenceStack; /** @var mixed[] */ private array $cellStack = []; /** * Current iteration counter for cyclic formulae * If the value is 0 (or less) then cyclic formulae will throw an exception, * otherwise they will iterate to the limit defined here before returning a result. */ private int $cyclicFormulaCounter = 1; private string $cyclicFormulaCell = ''; /** * Number of iterations for cyclic formulae. */ public int $cyclicFormulaCount = 1; /** * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value. */ private const EXCEL_CONSTANTS = [ 'TRUE' => true, 'FALSE' => false, 'NULL' => null, ]; public static function keyInExcelConstants(string $key): bool { return array_key_exists($key, self::EXCEL_CONSTANTS); } public static function getExcelConstants(string $key): bool|null { return self::EXCEL_CONSTANTS[$key]; } /** * Internal functions used for special control purposes. * * @var array|string>> */ private static array $controlFunctions = [ 'MKMATRIX' => [ 'argumentCount' => '*', 'functionCall' => [Internal\MakeMatrix::class, 'make'], ], 'NAME.ERROR' => [ 'argumentCount' => '*', 'functionCall' => [ExcelError::class, 'NAME'], ], 'WILDCARDMATCH' => [ 'argumentCount' => '2', 'functionCall' => [Internal\WildcardMatch::class, 'compare'], ], ]; public function __construct(?Spreadsheet $spreadsheet = null) { $this->spreadsheet = $spreadsheet; $this->cyclicReferenceStack = new CyclicReferenceStack(); $this->debugLog = new Logger($this->cyclicReferenceStack); $this->branchPruner = new BranchPruner($this->branchPruningEnabled); } /** * Get an instance of this class. * * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, * or NULL to create a standalone calculation engine */ public static function getInstance(?Spreadsheet $spreadsheet = null): self { if ($spreadsheet !== null) { return $spreadsheet->getCalculationEngine(); } if (!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * Intended for use only via a destructor. * * @internal */ public static function getInstanceOrNull(?Spreadsheet $spreadsheet = null): ?self { if ($spreadsheet !== null) { return $spreadsheet->getCalculationEngineOrNull(); } return null; } /** * Flush the calculation cache for any existing instance of this class * but only if a Calculation instance exists. */ public function flushInstance(): void { $this->clearCalculationCache(); $this->branchPruner->clearBranchStore(); } /** * Get the Logger for this calculation engine instance. */ public function getDebugLog(): Logger { return $this->debugLog; } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning the calculation engine is not allowed!'); } /** * Set the Array Return Type (Array or Value of first element in the array). * * @param string $returnType Array return type * * @return bool Success or failure */ public static function setArrayReturnType(string $returnType): bool { if ( ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY) ) { self::$returnArrayAsType = $returnType; return true; } return false; } /** * Return the Array Return Type (Array or Value of first element in the array). * * @return string $returnType Array return type */ public static function getArrayReturnType(): string { return self::$returnArrayAsType; } /** * Set the Instance Array Return Type (Array or Value of first element in the array). * * @param string $returnType Array return type * * @return bool Success or failure */ public function setInstanceArrayReturnType(string $returnType): bool { if ( ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY) ) { $this->instanceArrayReturnType = $returnType; return true; } return false; } /** * Return the Array Return Type (Array or Value of first element in the array). * * @return string $returnType Array return type for instance if non-null, otherwise static property */ public function getInstanceArrayReturnType(): string { return $this->instanceArrayReturnType ?? self::$returnArrayAsType; } /** * Is calculation caching enabled? */ public function getCalculationCacheEnabled(): bool { return $this->calculationCacheEnabled; } /** * Enable/disable calculation cache. */ public function setCalculationCacheEnabled(bool $calculationCacheEnabled): self { $this->calculationCacheEnabled = $calculationCacheEnabled; $this->clearCalculationCache(); return $this; } /** * Enable calculation cache. */ public function enableCalculationCache(): void { $this->setCalculationCacheEnabled(true); } /** * Disable calculation cache. */ public function disableCalculationCache(): void { $this->setCalculationCacheEnabled(false); } /** * Clear calculation cache. */ public function clearCalculationCache(): void { $this->calculationCache = []; } /** * Clear calculation cache for a specified worksheet. */ public function clearCalculationCacheForWorksheet(string $worksheetName): void { if (isset($this->calculationCache[$worksheetName])) { unset($this->calculationCache[$worksheetName]); } } /** * Rename calculation cache for a specified worksheet. */ public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void { if (isset($this->calculationCache[$fromWorksheetName])) { $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; unset($this->calculationCache[$fromWorksheetName]); } } public function getBranchPruningEnabled(): bool { return $this->branchPruningEnabled; } public function setBranchPruningEnabled(mixed $enabled): self { $this->branchPruningEnabled = (bool) $enabled; $this->branchPruner = new BranchPruner($this->branchPruningEnabled); return $this; } public function enableBranchPruning(): void { $this->setBranchPruningEnabled(true); } public function disableBranchPruning(): void { $this->setBranchPruningEnabled(false); } /** * Wrap string values in quotes. */ public static function wrapResult(mixed $value): mixed { if (is_string($value)) { // Error values cannot be "wrapped" if (Preg::isMatch('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) { // Return Excel errors "as is" return $value; } // Return strings wrapped in quotes return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { // Convert numeric errors to NaN error return ExcelError::NAN(); } return $value; } /** * Remove quotes used as a wrapper to identify string values. */ public static function unwrapResult(mixed $value): mixed { if (is_string($value)) { if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) { return substr($value, 1, -1); } // Convert numeric errors to NAN error } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { return ExcelError::NAN(); } return $value; } /** * Calculate cell value (using formula from a cell ID) * Retained for backward compatibility. * * @param ?Cell $cell Cell to calculate */ public function calculate(?Cell $cell = null): mixed { try { return $this->calculateCellValue($cell); } catch (\Exception $e) { throw new Exception($e->getMessage()); } } /** * Calculate the value of a cell formula. * * @param ?Cell $cell Cell to calculate * @param bool $resetLog Flag indicating whether the debug log should be reset or not */ public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed { if ($cell === null) { return null; } if ($resetLog) { // Initialise the logging settings if requested $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $this->cyclicFormulaCounter = 1; } // Execute the calculation for the cell formula $this->cellStack[] = [ 'sheet' => $cell->getWorksheet()->getTitle(), 'cell' => $cell->getCoordinate(), ]; $cellAddressAttempted = false; $cellAddress = null; try { $value = $cell->getValue(); if (is_string($value) && $cell->getDataType() === DataType::TYPE_FORMULA) { $value = Preg::replaceCallback( self::CALCULATION_REGEXP_CELLREF_SPILL, fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')', $value ); } $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell)); //* @phpstan-ignore-line if ($this->spreadsheet === null) { throw new Exception('null spreadsheet in calculateCellValue'); } $cellAddressAttempted = true; $cellAddress = array_pop($this->cellStack); if ($cellAddress === null) { throw new Exception('null cellAddress in calculateCellValue'); } /** @var array{sheet: string, cell: string} $cellAddress */ $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']); if ($testSheet === null) { throw new Exception('worksheet not found in calculateCellValue'); } $testSheet->getCell($cellAddress['cell']); } catch (\Exception $e) { if (!$cellAddressAttempted) { $cellAddress = array_pop($this->cellStack); } if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) { $sheetName = $cellAddress['sheet'] ?? null; $testSheet = is_string($sheetName) ? $this->spreadsheet->getSheetByName($sheetName) : null; if ($testSheet !== null && array_key_exists('cell', $cellAddress)) { /** @var array{cell: string} $cellAddress */ $testSheet->getCell($cellAddress['cell']); } } throw new Exception($e->getMessage(), $e->getCode(), $e); } if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) { $testResult = Functions::flattenArray($result); if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) { return ExcelError::VALUE(); } $result = array_shift($testResult); } if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) { return 0; } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { return ExcelError::NAN(); } return $result; } /** * Validate and parse a formula string. * * @param string $formula Formula to parse * * @return array|bool */ public function parseFormula(string $formula): array|bool { $formula = Preg::replaceCallback( self::CALCULATION_REGEXP_CELLREF_SPILL, fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')', $formula ); // Basic validation that this is indeed a formula // We return an empty array if not $formula = trim($formula); if ((!isset($formula[0])) || ($formula[0] != '=')) { return []; } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return []; } // Parse the formula and return the token stack return $this->internalParseFormula($formula); } /** * Calculate the value of a formula. * * @param string $formula Formula to parse * @param ?string $cellID Address of the cell to calculate * @param ?Cell $cell Cell to calculate */ public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed { // Initialise the logging settings $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $resetCache = $this->getCalculationCacheEnabled(); if ($this->spreadsheet !== null && $cellID === null && $cell === null) { $cellID = 'A1'; $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID); } else { // Disable calculation cacheing because it only applies to cell calculations, not straight formulae // But don't actually flush any cache $this->calculationCacheEnabled = false; } // Execute the calculation try { $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell)); } catch (\Exception $e) { throw new Exception($e->getMessage()); } if ($this->spreadsheet === null) { // Reset calculation cacheing to its previous state $this->calculationCacheEnabled = $resetCache; } return $result; } public function getValueFromCache(string $cellReference, mixed &$cellValue): bool { $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference); // Is calculation cacheing enabled? // If so, is the required value present in calculation cache? if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; return true; } return false; } public function saveValueToCache(string $cellReference, mixed $cellValue): void { if ($this->calculationCacheEnabled) { $this->calculationCache[$cellReference] = $cellValue; } } /** * Parse a cell formula and calculate its value. * * @param string $formula The formula to parse and calculate * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating * @param ?Cell $cell Cell to calculate * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed */ public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed { $cellValue = null; // Quote-Prefixed cell values cannot be formulae, but are treated as strings if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) { return self::wrapResult((string) $formula); } // https://www.reddit.com/r/excel/comments/chr41y/cmd_formula_stopped_working_since_last_update/ if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) { return ExcelError::REF(); // returns #BLOCKED in newer versions } // Basic validation that this is indeed a formula // We simply return the cell value if not $formula = trim($formula); if ($formula === '' || $formula[0] !== '=') { return self::wrapResult($formula); } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return self::wrapResult($formula); } $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk"; $wsCellReference = $wsTitle . '!' . $cellID; if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { return $cellValue; } $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference); if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { $this->cyclicFormulaCell = ''; return $this->raiseFormulaError('Cyclic Reference in Formula'); } elseif ($this->cyclicFormulaCell === $wsCellReference) { ++$this->cyclicFormulaCounter; if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { $this->cyclicFormulaCell = ''; return $cellValue; } } elseif ($this->cyclicFormulaCell == '') { if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { return $cellValue; } $this->cyclicFormulaCell = $wsCellReference; } } $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula); // Parse the formula onto the token stack and calculate the value $this->cyclicReferenceStack->push($wsCellReference); $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell); $this->cyclicReferenceStack->pop(); // Save to calculation cache if ($cellID !== null) { $this->saveValueToCache($wsCellReference, $cellValue); } // Return the calculated value return $cellValue; } /** * Ensure that paired matrix operands are both matrices and of the same size. * * @param mixed $operand1 First matrix operand * * @param-out mixed[] $operand1 * * @param mixed $operand2 Second matrix operand * * @param-out mixed[] $operand2 * * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. * 0 = no resize * 1 = shrink to fit * 2 = extend to fit * * @return mixed[] */ public static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array { // Examine each of the two operands, and turn them into an array if they aren't one already // Note that this function should only be called if one or both of the operand is already an array if (!is_array($operand1)) { if (is_array($operand2)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2); $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1)); $resize = 0; } else { $operand1 = [$operand1]; $operand2 = [$operand2]; } } elseif (!is_array($operand2)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1); $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2)); $resize = 0; } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); if ($resize === 3) { $resize = 2; } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) { $resize = 1; } if ($resize == 2) { // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } elseif ($resize == 1) { // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller /** @var mixed[][] $operand1 */ /** @var mixed[][] $operand2 */ self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns]; } /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0. * * @param mixed[] $matrix matrix operand * * @return int[] An array comprising the number of rows, and number of columns */ public static function getMatrixDimensions(array &$matrix): array { $matrixRows = count($matrix); $matrixColumns = 0; foreach ($matrix as $rowKey => $rowValue) { if (!is_array($rowValue)) { $matrix[$rowKey] = [$rowValue]; $matrixColumns = max(1, $matrixColumns); } else { $matrix[$rowKey] = array_values($rowValue); $matrixColumns = max(count($rowValue), $matrixColumns); } } $matrix = array_values($matrix); return [$matrixRows, $matrixColumns]; } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param mixed[][] $matrix1 First matrix operand * @param mixed[][] $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Rows < $matrix1Rows) { for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { unset($matrix1[$i]); } } if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { unset($matrix1[$i][$j]); } } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Rows < $matrix2Rows) { for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { unset($matrix2[$i]); } } if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { unset($matrix2[$i][$j]); } } } } } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param mixed[] $matrix1 First matrix operand * @param mixed[] $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { /** @var mixed[][] $matrix2 */ $x = ($matrix2Columns === 1) ? $matrix2[$i][0] : null; for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { $matrix2[$i][$j] = $x; } } } if ($matrix2Rows < $matrix1Rows) { $x = ($matrix2Rows === 1) ? $matrix2[0] : array_fill(0, $matrix2Columns, null); for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { $matrix2[$i] = $x; } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { /** @var mixed[][] $matrix1 */ $x = ($matrix1Columns === 1) ? $matrix1[$i][0] : null; for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { $matrix1[$i][$j] = $x; } } } if ($matrix1Rows < $matrix2Rows) { $x = ($matrix1Rows === 1) ? $matrix1[0] : array_fill(0, $matrix2Columns, null); for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { $matrix1[$i] = $x; } } } } /** * Format details of an operand for display in the log (based on operand type). * * @param mixed $value First matrix operand */ private function showValue(mixed $value): mixed { if ($this->debugLog->getWriteDebugLog()) { $testArray = Functions::flattenArray($value); if (count($testArray) == 1) { $value = array_pop($testArray); } if (is_array($value)) { $returnMatrix = []; $pad = $rpad = ', '; foreach ($value as $row) { if (is_array($row)) { $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row)); $rpad = '; '; } else { $returnMatrix[] = $this->showValue($row); } } return '{ ' . implode($rpad, $returnMatrix) . ' }'; } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) { return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif (is_bool($value)) { return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } elseif ($value === null) { return self::$localeBoolean['NULL']; } } return Functions::flattenSingleValue($value); } /** * Format type and details of an operand for display in the log (based on operand type). * * @param mixed $value First matrix operand */ private function showTypeDetails(mixed $value): ?string { if ($this->debugLog->getWriteDebugLog()) { $testArray = Functions::flattenArray($value); if (count($testArray) == 1) { $value = array_pop($testArray); } if ($value === null) { return 'a NULL value'; } elseif (is_float($value)) { $typeString = 'a floating point number'; } elseif (is_int($value)) { $typeString = 'an integer number'; } elseif (is_bool($value)) { $typeString = 'a boolean'; } elseif (is_array($value)) { $typeString = 'a matrix'; } else { /** @var string $value */ if ($value == '') { return 'an empty string'; } elseif ($value[0] == '#') { return 'a ' . $value . ' error'; } $typeString = 'a string'; } return $typeString . ' with a value of ' . StringHelper::convertToString($this->showValue($value)); } return null; } private const MATRIX_REPLACE_FROM = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE]; private const MATRIX_REPLACE_TO = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))']; /** * @return false|string False indicates an error */ private function convertMatrixReferences(string $formula): false|string { // Convert any Excel matrix references to the MKMATRIX() function if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) { // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators if (str_contains($formula, self::FORMULA_STRING_QUOTE)) { // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded // the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); // Open and Closed counts used for trapping mismatched braces in the formula $openCount = $closeCount = 0; $notWithinQuotes = false; foreach ($temp as &$value) { // Only count/replace in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE); $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE); $value = str_replace(self::MATRIX_REPLACE_FROM, self::MATRIX_REPLACE_TO, $value); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE); $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = str_replace(self::MATRIX_REPLACE_FROM, self::MATRIX_REPLACE_TO, $formula); } // Trap for mismatched braces and trigger an appropriate error if ($openCount < $closeCount) { if ($openCount > 0) { return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'"); } return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered"); } elseif ($openCount > $closeCount) { if ($closeCount > 0) { return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'"); } return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered"); } } return $formula; } /** * Comparison (Boolean) Operators. * These operators work on two values, but always return a boolean result. */ private const COMPARISON_OPERATORS = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true]; /** * Operator Precedence. * This list includes all valid operators, whether binary (including boolean) or unary (such as %). * Array key is the operator, the value is its precedence. */ private const OPERATOR_PRECEDENCE = [ ':' => 9, // Range '∩' => 8, // Intersect '∪' => 7, // Union '~' => 6, // Negation '%' => 5, // Percentage '^' => 4, // Exponentiation '*' => 3, '/' => 3, // Multiplication and Division '+' => 2, '-' => 2, // Addition and Subtraction '&' => 1, // Concatenation '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison ]; /** @param string[] $matches */ private static function unionForComma(array $matches): string { return $matches[1] . str_replace(',', '∪', $matches[2]); } private const CELL_OR_CELLRANGE_OR_DEFINED_NAME = '(?:' . self::CALCULATION_REGEXP_CELLREF // cell address . '(?::' . self::CALCULATION_REGEXP_CELLREF . ')?' // optional range address, non-capturing . '|' . self::CALCULATION_REGEXP_DEFINEDNAME . ')' ; public const UNIONABLE_COMMAS = '/((?:[,(]|^)\s*)' // comma or open paren or start of string, followed by optional whitespace . '([(]' // open paren . self::CELL_OR_CELLRANGE_OR_DEFINED_NAME // cell address . '(?:\s*,\s*' // optioonal whitespace, comma, optional whitespace, non-capturing . self::CELL_OR_CELLRANGE_OR_DEFINED_NAME // cell address . ')+' // one or more occurrences . '\s*[)])/i'; // optional whitespace, end paren /** * @return array|false */ private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array { if (($formula = $this->convertMatrixReferences(trim($formula))) === false) { return false; } $oldFormula = $formula; $formula = Preg::replaceCallback(self::UNIONABLE_COMMAS, self::unionForComma(...), $formula); // @phpstan-ignore-line if ($oldFormula !== $formula) { $this->debugLog->writeDebugLog('Reformulated as %s', $formula); } $phpSpreadsheetFunctions = &self::getFunctionsAddress(); // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet), // so we store the parent worksheet so that we can re-attach it when necessary $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $regexpMatchString = '/^((?' . self::CALCULATION_REGEXP_STRING . ')|(?' . self::CALCULATION_REGEXP_FUNCTION . ')|(?' . self::CALCULATION_REGEXP_CELLREF . ')|(?' . self::CALCULATION_REGEXP_COLUMN_RANGE . ')|(?' . self::CALCULATION_REGEXP_ROW_RANGE . ')|(?' . self::CALCULATION_REGEXP_NUMBER . ')|(?' . self::CALCULATION_REGEXP_OPENBRACE . ')|(?' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . ')|(?' . self::CALCULATION_REGEXP_DEFINEDNAME . ')|(?' . self::CALCULATION_REGEXP_ERROR . '))/sui'; // Start with initialisation $index = 0; $stack = new Stack($this->branchPruner); $output = []; $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a // - is a negation or + is a positive operator rather than an operation $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand // should be null in a function call // The guts of the lexical parser // Loop through the formula extracting each operator and operand in turn while (true) { // Branch pruning: we adapt the output item to the context (it will // be used to limit its computation) $this->branchPruner->initialiseForLoop(); $opCharacter = $formula[$index]; // Get the first character of the value at the current index position if ($opCharacter === "\xe2") { // intersection or union $opCharacter .= $formula[++$index]; $opCharacter .= $formula[++$index]; } // Check for two-character operators (e.g. >=, <=, <>) if ((isset(self::COMPARISON_OPERATORS[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::COMPARISON_OPERATORS[$formula[$index + 1]])) { $opCharacter .= $formula[++$index]; } // Find out if we're currently at the beginning of a number, variable, cell/row/column reference, // function, defined name, structured reference, parenthesis, error or operand $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match); $expectingOperatorCopy = $expectingOperator; if ($opCharacter === '-' && !$expectingOperator) { // Is it a negation instead of a minus? // Put a negation on the stack $stack->push('Unary Operator', '~'); ++$index; // and drop the negation symbol } elseif ($opCharacter === '%' && $expectingOperator) { // Put a percentage on the stack $stack->push('Unary Operator', '%'); ++$index; } elseif ($opCharacter === '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? ++$index; // Drop the redundant plus symbol } elseif ((($opCharacter === '~') /*|| ($opCharacter === '∩') || ($opCharacter === '∪')*/) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde, union or intersect because they are legal return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? while (self::swapOperands($stack, $opCharacter)) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } // Finally put our current operator onto the stack $stack->push('Binary Operator', $opCharacter); ++$index; $expectingOperator = false; } elseif ($opCharacter === ')' && $expectingOperator) { // Are we expecting to close a parenthesis? $expectingOperand = false; while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( $output[] = $o2; } $d = $stack->last(2); // Branch pruning we decrease the depth whether is it a function // call or a parenthesis $this->branchPruner->decrementDepth(); if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($d['value']), $matches)) { // Did this parenthesis just close a function? try { $this->branchPruner->closingBrace($d['value']); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } $functionName = $matches[1]; // Get the function name $d = $stack->pop(); $argumentCount = $d['value'] ?? 0; // See how many arguments there were (argument count is the next value stored on the stack) $output[] = $d; // Dump the argument count on the output $output[] = $stack->pop(); // Pop the function and push onto the output if (isset(self::$controlFunctions[$functionName])) { $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount']; } elseif (isset($phpSpreadsheetFunctions[$functionName])) { $expectedArgumentCount = $phpSpreadsheetFunctions[$functionName]['argumentCount']; } else { // did we somehow push a non-function on the stack? this should never happen return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack'); } // Check the argument count $argumentCountError = false; $expectedArgumentCountString = null; if (is_numeric($expectedArgumentCount)) { if ($expectedArgumentCount < 0) { if ($argumentCount > abs($expectedArgumentCount + 0)) { $argumentCountError = true; $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0); } } else { if ($argumentCount != $expectedArgumentCount) { $argumentCountError = true; $expectedArgumentCountString = $expectedArgumentCount; } } } elseif (is_string($expectedArgumentCount) && $expectedArgumentCount !== '*') { if (!Preg::isMatch('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) { $argMatch = ['', '', '', '']; } switch ($argMatch[2]) { case '+': if ($argumentCount < $argMatch[1]) { $argumentCountError = true; $expectedArgumentCountString = $argMatch[1] . ' or more '; } break; case '-': if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) { $argumentCountError = true; $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3]; } break; case ',': if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) { $argumentCountError = true; $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3]; } break; } } if ($argumentCountError) { /** @var int $argumentCount */ return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected'); } } ++$index; } elseif ($opCharacter === ',') { // Is this the separator for function arguments? try { $this->branchPruner->argumentSeparator(); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( $output[] = $o2; // pop the argument expression stuff and push onto the output } // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { $output[] = $stack->getStackItem('Empty Argument', null, 'NULL'); } // make sure there was a function $d = $stack->last(2); /** @var string */ $temp = $d['value'] ?? ''; if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $temp, $matches)) { // Can we inject a dummy function at this point so that the braces at least have some context // because at least the braces are paired up (at this stage in the formula) // MS Excel allows this if the content is cell references; but doesn't allow actual values, // but at this point, we can't differentiate (so allow both) //return $this->raiseFormulaError('Formula Error: Unexpected ,'); $stack->push('Binary Operator', '∪'); ++$index; $expectingOperator = false; continue; } /** @var array $d */ $d = $stack->pop(); ++$d['value']; // increment the argument count $stack->pushStackItem($d); $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again $expectingOperator = false; $expectingOperand = true; ++$index; } elseif ($opCharacter === '(' && !$expectingOperator) { // Branch pruning: we go deeper $this->branchPruner->incrementDepth(); $stack->push('Brace', '(', null); ++$index; } elseif ($isOperandOrFunction && !$expectingOperatorCopy) { // do we now have a function/variable/number? $expectingOperator = true; $expectingOperand = false; $val = $match[1] ?? ''; //* @phpstan-ignore-line $length = strlen($val); if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) { // $val is known to be valid unicode from statement above, so Preg::replace is okay even with u modifier $val = Preg::replace('/\s/u', '', $val); if (isset($phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function $valToUpper = strtoupper($val); } else { $valToUpper = 'NAME.ERROR('; } // here $matches[1] will contain values like "IF" // and $val "IF(" $this->branchPruner->functionCall($valToUpper); $stack->push('Function', $valToUpper); // tests if the function is closed right after opening $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length)); if ($ax) { $stack->push('Operand Count for Function ' . $valToUpper . ')', 0); $expectingOperator = true; } else { $stack->push('Operand Count for Function ' . $valToUpper . ')', 1); $expectingOperator = false; } $stack->push('Brace', '('); } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) { // Watch for this case-change when modifying to allow cell references in different worksheets... // Should only be applied to the actual cell column, not the worksheet name // If the last entry on the stack was a : operator, then we have a cell range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { // If we have a worksheet reference, then we're playing with a 3D reference if ($matches[2] === '') { // Otherwise, we 'inherit' the worksheet reference from the start cell reference // The start of the cell range reference should be the last entry in $output $rangeStartCellRef = $output[count($output) - 1]['value'] ?? ''; if ($rangeStartCellRef === ':') { // Do we have chained range operators? $rangeStartCellRef = $output[count($output) - 2]['value'] ?? ''; } /** @var string $rangeStartCellRef */ preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); if (array_key_exists(2, $rangeStartMatches)) { if ($rangeStartMatches[2] > '') { $val = $rangeStartMatches[2] . '!' . $val; } } else { $val = ExcelError::REF(); } } else { $rangeStartCellRef = $output[count($output) - 1]['value'] ?? ''; if ($rangeStartCellRef === ':') { // Do we have chained range operators? $rangeStartCellRef = $output[count($output) - 2]['value'] ?? ''; } /** @var string $rangeStartCellRef */ preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) { return $this->raiseFormulaError('3D Range references are not yet supported'); } } } elseif (!str_contains($val, '!') && $pCellParent !== null) { $worksheet = $pCellParent->getTitle(); $val = "'{$worksheet}'!{$val}"; } // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $outputItem = $stack->getStackItem('Cell Reference', $val, $val); $output[] = $outputItem; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) { try { $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } $val = $structuredReference->value(); $length = strlen($val); $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null); $output[] = $outputItem; $expectingOperator = true; } else { // it's a variable, constant, string, number or boolean $localeConstant = false; $stackItemType = 'Value'; $stackItemReference = null; // If the last entry on the stack was a : operator, then we may have a row or column range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { $stackItemType = 'Cell Reference'; if ( !is_numeric($val) && ((ctype_alpha($val) === false || strlen($val) > 3)) && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false) && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null) ) { $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val); if ($namedRange !== null) { $stackItemType = 'Defined Name'; $address = str_replace('$', '', $namedRange->getValue()); $stackItemReference = $val; if (str_contains($address, ':')) { // We'll need to manipulate the stack for an actual named range rather than a named cell $fromTo = explode(':', $address); $to = array_pop($fromTo); foreach ($fromTo as $from) { $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference); $output[] = $stack->getStackItem('Binary Operator', ':'); } $address = $to; } $val = $address; } } elseif ($val === ExcelError::REF()) { $stackItemReference = $val; } else { /** @var non-empty-string $startRowColRef */ $startRowColRef = $output[count($output) - 1]['value'] ?? ''; [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); $rangeSheetRef = $rangeWS1; if ($rangeWS1 !== '') { $rangeWS1 .= '!'; } if (str_starts_with($rangeSheetRef, "'")) { $rangeSheetRef = Worksheet::unApostrophizeTitle($rangeSheetRef); } [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true); if ($rangeWS2 !== '') { $rangeWS2 .= '!'; } else { $rangeWS2 = $rangeWS1; } $refSheet = $pCellParent; if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) { $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef); } if (ctype_digit($val) && $val <= AddressRange::MAX_ROW) { // Row range $stackItemType = 'Row Reference'; $valx = $val; $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; // Max 16,384 columns for Excel2007 $val = "{$rangeWS2}{$endRowColRef}{$val}"; } elseif (ctype_alpha($val) && strlen($val) <= 3) { // Column range $stackItemType = 'Column Reference'; $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; // Max 1,048,576 rows for Excel2007 $val = "{$rangeWS2}{$val}{$endRowColRef}"; } $stackItemReference = $val; } } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) { // UnEscape any quotes within the string $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, StringHelper::convertToString(self::unwrapResult($val)))); } elseif (isset(self::EXCEL_CONSTANTS[trim(strtoupper($val))])) { $stackItemType = 'Constant'; $excelConstant = trim(strtoupper($val)); $val = self::EXCEL_CONSTANTS[$excelConstant]; $stackItemReference = $excelConstant; } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { $stackItemType = 'Constant'; $val = self::EXCEL_CONSTANTS[$localeConstant]; $stackItemReference = $localeConstant; } elseif ( preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference) ) { $val = $rowRangeReference[1]; $length = strlen($rowRangeReference[1]); $stackItemType = 'Row Reference'; // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $column = 'A'; if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { $column = $pCellParent->getHighestDataColumn($val); } $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}"; $stackItemReference = $val; } elseif ( preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference) ) { $val = $columnRangeReference[1]; $length = strlen($val); $stackItemType = 'Column Reference'; // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $row = '1'; if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { $row = $pCellParent->getHighestDataRow($val); } $val = "{$val}{$row}"; $stackItemReference = $val; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) { $stackItemType = 'Defined Name'; $stackItemReference = $val; } elseif (is_numeric($val)) { if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { $val = (float) $val; } else { $val = (int) $val; } } $details = $stack->getStackItem($stackItemType, $val, $stackItemReference); if ($localeConstant) { $details['localeValue'] = $localeConstant; } $output[] = $details; } $index += $length; } elseif ($opCharacter === '$') { // absolute row or column range ++$index; } elseif ($opCharacter === ')') { // miscellaneous error checking if ($expectingOperand) { $output[] = $stack->getStackItem('Empty Argument', null, 'NULL'); $expectingOperand = false; $expectingOperator = true; } else { return $this->raiseFormulaError("Formula Error: Unexpected ')'"); } } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) { return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); } else { // I don't even want to know what you did to get here return $this->raiseFormulaError('Formula Error: An unexpected error occurred'); } // Test for end of formula string if ($index == strlen($formula)) { // Did we end with an operator?. // Only valid for the % unary operator if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) { return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands"); } break; } // Ignore white space while (($formula[$index] === "\n") || ($formula[$index] === "\r")) { ++$index; } if ($formula[$index] === ' ') { while ($formula[$index] === ' ') { ++$index; } // If we're expecting an operator, but only have a space between the previous and next operands (and both are // Cell References, Defined Names or Structured References) then we have an INTERSECTION operator $countOutputMinus1 = count($output) - 1; if ( ($expectingOperator) && array_key_exists($countOutputMinus1, $output) && is_array($output[$countOutputMinus1]) && array_key_exists('type', $output[$countOutputMinus1]) && ( (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === 'Cell Reference') || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value') || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value') ) ) { while (self::swapOperands($stack, $opCharacter)) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } $stack->push('Binary Operator', '∩'); // Put an Intersect Operator on the stack $expectingOperator = false; } } } while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output if ($op['value'] == '(') { return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced } $output[] = $op; } return $output; } /** @param mixed[] $operandData */ private static function dataTestReference(array &$operandData): mixed { $operand = $operandData['value']; if (($operandData['reference'] === null) && (is_array($operand))) { $rKeys = array_keys($operand); $rowKey = array_shift($rKeys); if (is_array($operand[$rowKey]) === false) { $operandData['value'] = $operand[$rowKey]; return $operand[$rowKey]; } $cKeys = array_keys(array_keys($operand[$rowKey])); $colKey = array_shift($cKeys); if (ctype_upper("$colKey")) { $operandData['reference'] = $colKey . $rowKey; } } return $operand; } private static int $matchIndex8 = 8; private static int $matchIndex9 = 9; private static int $matchIndex10 = 10; /** * @param array|false $tokens * * @return array|false|string */ private function processTokenStack(false|array $tokens, ?string $cellID = null, ?Cell $cell = null) { if ($tokens === false) { return false; } $phpSpreadsheetFunctions = &self::getFunctionsAddress(); // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection), // so we store the parent cell collection so that we can re-attach it when necessary $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null; $originalCoordinate = $cell?->getCoordinate(); $pCellParent = ($cell !== null) ? $cell->getParent() : null; $stack = new Stack($this->branchPruner); // Stores branches that have been pruned $fakedForBranchPruning = []; // help us to know when pruning ['branchTestId' => true/false] $branchStore = []; // Loop through each token in turn foreach ($tokens as $tokenIdx => $tokenData) { /** @var mixed[] $tokenData */ $this->processingAnchorArray = false; if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') { //* @phpstan-ignore-line $this->processingAnchorArray = true; } $token = $tokenData['value']; // Branch pruning: skip useless resolutions /** @var ?string */ $storeKey = $tokenData['storeKey'] ?? null; if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) { /** @var string */ $onlyIfStoreKey = $tokenData['onlyIf']; $storeValue = $branchStore[$onlyIfStoreKey] ?? null; $storeValueAsBool = ($storeValue === null) ? true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } if ( (isset($storeValue) || $tokenData['reference'] === 'NULL') && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is not true, we don't need to compute /** @var string $onlyIfStoreKey */ if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) { /** @var string $token */ $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token); $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true; } if (isset($storeKey)) { // We are processing an if condition // We cascade the pruning to the depending branches $branchStore[$storeKey] = 'Pruned branch'; $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true; $fakedForBranchPruning['onlyIf-' . $storeKey] = true; } continue; } } if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) { /** @var string */ $onlyIfNotStoreKey = $tokenData['onlyIfNot']; $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null; $storeValueAsBool = ($storeValue === null) ? true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } if ( (isset($storeValue) || $tokenData['reference'] === 'NULL') && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) { /** @var string $token */ $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token); $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true; } if (isset($storeKey)) { // We are processing an if condition // We cascade the pruning to the depending branches $branchStore[$storeKey] = 'Pruned branch'; $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true; $fakedForBranchPruning['onlyIf-' . $storeKey] = true; } continue; } } if ($token instanceof Operands\StructuredReference) { if ($cell === null) { return $this->raiseFormulaError('Structured References must exist in a Cell context'); } try { $cellRange = $token->parse($cell); if (str_contains($cellRange, ':')) { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange); $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell); $stack->push('Value', $rangeValue); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue)); } else { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange); $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false); $stack->push('Cell Reference', $cellValue, $cellRange); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue)); } } catch (Exception $e) { if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) { $stack->push('Error', ExcelError::REF(), null); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF()); } else { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } } } elseif (!is_numeric($token) && !is_object($token) && isset($token, self::BINARY_OPERATORS[$token])) { //* @phpstan-ignore-line // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack // We must have two operands, error if we don't $operand2Data = $stack->pop(); if ($operand2Data === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $operand1Data = $stack->pop(); if ($operand1Data === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $operand1 = self::dataTestReference($operand1Data); $operand2 = self::dataTestReference($operand2Data); // Log what we're doing if ($token == ':') { $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference'])); } else { $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2)); } // Process the operation in the appropriate manner switch ($token) { // Comparison (Boolean) Operators case '>': // Greater than case '<': // Less than case '>=': // Greater than or Equal to case '<=': // Less than or Equal to case '=': // Equality case '<>': // Inequality $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; // Binary Operators case ':': // Range if ($operand1Data['type'] === 'Error') { $stack->push($operand1Data['type'], $operand1Data['value'], null); break; } if ($operand2Data['type'] === 'Error') { $stack->push($operand2Data['type'], $operand2Data['value'], null); break; } if ($operand1Data['type'] === 'Defined Name') { /** @var array{reference: string} $operand1Data */ if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) { /** @var string[] $operand1Data */ $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']); if ($definedName !== null) { $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue()); } } } /** @var array{reference?: ?string} $operand1Data */ if (str_contains($operand1Data['reference'] ?? '', '!')) { [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true, true); } else { $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : ''; } //$sheet1 ??= ''; // phpstan level 10 says this is unneeded /** @var string */ $op2ref = $operand2Data['reference']; [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($op2ref, true, true); if (empty($sheet2)) { $sheet2 = $sheet1; } if ($sheet1 === $sheet2) { /** @var array{reference: ?string, value: string|string[]} $operand1Data */ if ($operand1Data['reference'] === null && $cell !== null) { if (is_array($operand1Data['value'])) { $operand1Data['reference'] = $cell->getCoordinate(); } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value']; } elseif (trim($operand1Data['value']) == '') { $operand1Data['reference'] = $cell->getCoordinate(); } else { $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow(); } } /** @var array{reference: ?string, value: string|string[]} $operand2Data */ if ($operand2Data['reference'] === null && $cell !== null) { if (is_array($operand2Data['value'])) { $operand2Data['reference'] = $cell->getCoordinate(); } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value']; } elseif (trim($operand2Data['value']) == '') { $operand2Data['reference'] = $cell->getCoordinate(); } else { $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow(); } } $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? '')); $oCol = $oRow = []; $breakNeeded = false; foreach ($oData as $oDatum) { try { $oCR = Coordinate::coordinateFromString($oDatum); $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1; $oRow[] = $oCR[1]; } catch (\Exception) { $stack->push('Error', ExcelError::REF(), null); $breakNeeded = true; break; } } if ($breakNeeded) { break; } $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line if ($pCellParent !== null && $this->spreadsheet !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue)); $stack->push('Cell Reference', $cellValue, $cellRef); } else { $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error'); $stack->push('Error', ExcelError::REF(), null); } break; case '+': // Addition case '-': // Subtraction case '*': // Multiplication case '/': // Division case '^': // Exponential $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; case '&': // Concatenation // If either of the operands is a matrix, we need to treat them both as matrices // (converting the other operand to a matrix if need be); then perform the required // matrix operation $operand1 = self::boolToString($operand1); $operand2 = self::boolToString($operand2); if (is_array($operand1) || is_array($operand2)) { if (is_string($operand1)) { $operand1 = self::unwrapResult($operand1); } if (is_string($operand2)) { $operand2 = self::unwrapResult($operand2); } // Ensure that both operands are arrays/matrices [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { /** @var mixed[][] $operand1 */ $op1x = self::boolToString($operand1[$row][$column]); /** @var mixed[][] $operand2 */ $op2x = self::boolToString($operand2[$row][$column]); if (Information\ErrorValue::isError($op1x)) { // no need to do anything } elseif (Information\ErrorValue::isError($op2x)) { $operand1[$row][$column] = $op2x; } else { /** @var string $op1x */ /** @var string $op2x */ $operand1[$row][$column] = StringHelper::substring( $op1x . $op2x, 0, DataType::MAX_STRING_LENGTH ); } } } $result = $operand1; } else { if (Information\ErrorValue::isError($operand1)) { $result = $operand1; } elseif (Information\ErrorValue::isError($operand2)) { $result = $operand2; } else { $result = str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)); //* @phpstan-ignore-line $result = StringHelper::substring( $result, 0, DataType::MAX_STRING_LENGTH ); $result = self::FORMULA_STRING_QUOTE . $result . self::FORMULA_STRING_QUOTE; } } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; case '∩': // Intersect /** @var mixed[][] $operand1 */ /** @var mixed[][] $operand2 */ $rowIntersect = array_intersect_key($operand1, $operand2); $cellIntersect = $oCol = $oRow = []; foreach (array_keys($rowIntersect) as $row) { $oRow[] = $row; foreach ($rowIntersect[$row] as $col => $data) { $oCol[] = Coordinate::columnIndexFromString($col) - 1; $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]); } } if (count(Functions::flattenArray($cellIntersect)) === 0) { $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); $stack->push('Error', ExcelError::null(), null); } else { $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' // @phpstan-ignore-line . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); $stack->push('Value', $cellIntersect, $cellRef); } break; case '∪': // union /** @var mixed[][] $operand1 */ /** @var mixed[][] $operand2 */ $cellUnion = array_merge($operand1, $operand2); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellUnion)); $stack->push('Value', $cellUnion, 'A1'); break; } } elseif (($token === '~') || ($token === '%')) { // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on if (($arg = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $arg = $arg['value']; if ($token === '~') { $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg)); $multiplier = -1; } else { $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg)); $multiplier = 0.01; } if (is_array($arg)) { $operand2 = $multiplier; $result = $arg; [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { /** @var mixed[][] $result */ if (self::isNumericOrBool($result[$row][$column])) { /** @var float|int|numeric-string */ $temp = $result[$row][$column]; $result[$row][$column] = $temp * $multiplier; } else { $result[$row][$column] = self::makeError($result[$row][$column]); } } } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } else { $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack); } } elseif (Preg::isMatch('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', StringHelper::convertToString($token ?? ''), $matches)) { $cellRef = null; /* Phpstan says matches[8/9/10] is never set, and code coverage report seems to confirm. regex101.com confirms - only 7 capturing groups. My theory is that this code expected regexp to match cell *or* cellRange, but it does not match the latter. Retain the code for now in case we do want to add the range match later. Probably delete this block later. Until delete happens, turn code coverage off. */ if (isset($matches[self::$matchIndex8])) { // @codeCoverageIgnoreStart if ($cell === null) { // We can't access the range, so return a REF error $cellValue = ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7] . ':' . $matches[self::$matchIndex9] . $matches[self::$matchIndex10]; $matches[2] = (string) $matches[2]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) { // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } $matches[2] = trim($matches[2], "\"'"); $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } // @codeCoverageIgnoreEnd } else { if ($cell === null) { // We can't access the cell, so return a REF error $cellValue = ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7]; $matches[2] = (string) $matches[2]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) { // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellSheet = $this->spreadsheet->getSheetByName($matches[2]); if ($cellSheet && !$cellSheet->cellExists($cellRef)) { try { $cellSheet->setCellValue($cellRef, null); } catch (SpreadsheetException) { // do nothing } } if ($cellSheet && $cellSheet->cellExists($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); $cell->attach($pCellParent); } else { $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef; $cellValue = ($cellSheet !== null) ? null : ExcelError::REF(); } } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef); if ($pCellParent !== null && $pCellParent->has($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); $cell->attach($pCellParent); } else { $cellValue = null; } $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) { while (is_array($cellValue)) { $cellValue = array_shift($cellValue); } if (is_string($cellValue)) { $cellValue = Preg::replace('/"/', '""', $cellValue); } $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } $this->processingAnchorArray = false; $stack->push('Cell Value', $cellValue, $cellRef); if (isset($storeKey)) { $branchStore[$storeKey] = $cellValue; } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($token ?? ''), $matches)) { // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on if ($cell !== null && $pCellParent !== null) { $cell->attach($pCellParent); } $functionName = $matches[1]; /** @var array $argCount */ $argCount = $stack->pop(); $argCount = $argCount['value']; if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's')); } if ((isset($phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function $passByReference = false; $passCellReference = false; $functionCall = null; if (isset($phpSpreadsheetFunctions[$functionName])) { $functionCall = $phpSpreadsheetFunctions[$functionName]['functionCall']; $passByReference = isset($phpSpreadsheetFunctions[$functionName]['passByReference']); $passCellReference = isset($phpSpreadsheetFunctions[$functionName]['passCellReference']); } elseif (isset(self::$controlFunctions[$functionName])) { $functionCall = self::$controlFunctions[$functionName]['functionCall']; $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); } // get the arguments for this function $args = $argArrayVals = []; $emptyArguments = []; for ($i = 0; $i < $argCount; ++$i) { $arg = $stack->pop(); $a = $argCount - $i - 1; if ( ($passByReference) && (isset($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) //* @phpstan-ignore-line && ($phpSpreadsheetFunctions[$functionName]['passByReference'][$a]) ) { /** @var mixed[] $arg */ if ($arg['reference'] === null) { $nextArg = $cellID; if ($functionName === 'ISREF' && ($arg['type'] ?? '') === 'Value') { if (array_key_exists('value', $arg)) { $argValue = $arg['value']; if (is_scalar($argValue)) { $nextArg = $argValue; } elseif (empty($argValue)) { $nextArg = ''; } } } elseif (($arg['type'] ?? '') === 'Error') { $argValue = $arg['value']; if (is_scalar($argValue)) { $nextArg = $argValue; } elseif (empty($argValue)) { $nextArg = ''; } } $args[] = $nextArg; if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($cellID); } } else { $args[] = $arg['reference']; if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['reference']); } } } else { /** @var mixed[] $arg */ if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) { $emptyArguments[] = false; $args[] = $arg['value'] = 0; $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0'); } else { $emptyArguments[] = $arg['type'] === 'Empty Argument'; $args[] = self::unwrapResult($arg['value']); } if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['value']); } } } // Reverse the order of the arguments krsort($args); krsort($emptyArguments); if ($argCount > 0 && is_array($functionCall)) { /** @var string[] */ $functionCallCopy = $functionCall; $args = $this->addDefaultArgumentValues($functionCallCopy, $args, $emptyArguments); } if (($passByReference) && ($argCount == 0)) { $args[] = $cellID; $argArrayVals[] = $this->showValue($cellID); } if ($functionName !== 'MKMATRIX') { if ($this->debugLog->getWriteDebugLog()) { krsort($argArrayVals); $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals))); } } // Process the argument with the appropriate function call if ($pCellWorksheet !== null && $originalCoordinate !== null) { $pCellWorksheet->getCell($originalCoordinate); } /** @var array|string $functionCall */ $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell); if (!is_array($functionCall)) { foreach ($args as &$arg) { $arg = Functions::flattenSingleValue($arg); } unset($arg); } /** @var callable $functionCall */ try { $result = call_user_func_array($functionCall, $args); } catch (TypeError $e) { if (!$this->suppressFormulaErrors) { throw $e; } $result = false; } if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result)); } $stack->push('Value', self::wrapResult($result)); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } } else { // if the token is a number, boolean, string or an Excel error, push it onto the stack /** @var ?string $token */ if (isset(self::EXCEL_CONSTANTS[strtoupper($token ?? '')])) { $excelConstant = strtoupper("$token"); $stack->push('Constant Value', self::EXCEL_CONSTANTS[$excelConstant]); if (isset($storeKey)) { $branchStore[$storeKey] = self::EXCEL_CONSTANTS[$excelConstant]; } $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::EXCEL_CONSTANTS[$excelConstant])); } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { //* @phpstan-ignore-line /** @var array{type: string, reference: ?string} $tokenData */ $stack->push($tokenData['type'], $token, $tokenData['reference']); if (isset($storeKey)) { $branchStore[$storeKey] = $token; } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) { // if the token is a named range or formula, evaluate it and push the result onto the stack $definedName = $matches[6]; if (str_starts_with($definedName, '_xleta')) { return Functions::NOT_YET_IMPLEMENTED; } if ($cell === null || $pCellWorksheet === null) { return $this->raiseFormulaError("undefined name '$token'"); } $specifiedWorksheet = trim($matches[2], "'"); $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName); $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet); // If not Defined Name, try as Table. if ($namedRange === null && $this->spreadsheet !== null) { $table = $this->spreadsheet->getTableByName($definedName); if ($table !== null) { $tableRange = Coordinate::getRangeBoundaries($table->getRange()); if ($table->getShowHeaderRow()) { ++$tableRange[0][1]; } if ($table->getShowTotalsRow()) { --$tableRange[1][1]; } $tableRangeString = '$' . $tableRange[0][0] . '$' . $tableRange[0][1] . ':' . '$' . $tableRange[1][0] . '$' . $tableRange[1][1]; $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString); } } if ($namedRange === null) { $result = ExcelError::NAME(); $stack->push('Error', $result, null); $this->debugLog->writeDebugLog("Error $result"); } else { $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== ''); } if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } else { return $this->raiseFormulaError("undefined name '$token'"); } } } // when we're out of tokens, the stack should have a single element, the final result if ($stack->count() != 1) { return $this->raiseFormulaError('internal error'); } /** @var array|false|string> */ $output = $stack->pop(); $output = $output['value']; return $output; } private function validateBinaryOperand(mixed &$operand, Stack &$stack): bool { if (is_array($operand)) { if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) { do { $operand = array_pop($operand); } while (is_array($operand)); } } // Numbers, matrices and booleans can pass straight through, as they're already valid if (is_string($operand)) { // We only need special validations for the operand if it is a string // Start by stripping off the quotation marks we use to identify true excel string values internally if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) { $operand = StringHelper::convertToString(self::unwrapResult($operand)); } // If the string is a numeric value, we treat it as a numeric, so no further testing if (!is_numeric($operand)) { // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations if ($operand > '' && $operand[0] == '#') { $stack->push('Value', $operand); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand)); return false; } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) { // If not a numeric, a fraction or a percentage, then it's a text string, and so can't be used in mathematical binary operations $stack->push('Error', '#VALUE!'); $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!')); return false; } } } // return a true if the value of the operand is one that we can use in normal binary mathematical operations return true; } /** @return mixed[] */ private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array { $result = []; if (!is_array($operand2) && is_array($operand1)) { // Operand 1 is an array, Operand 2 is a scalar foreach ($operand1 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2)); $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack); /** @var array $r */ $r = $stack->pop(); $result[$x] = $r['value']; } } elseif (is_array($operand2) && !is_array($operand1)) { // Operand 1 is a scalar, Operand 2 is an array foreach ($operand2 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData)); $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack); /** @var array $r */ $r = $stack->pop(); $result[$x] = $r['value']; } } elseif (is_array($operand2) && is_array($operand1)) { // Operand 1 and Operand 2 are both arrays if (!$recursingArrays) { self::checkMatrixOperands($operand1, $operand2, 2); } foreach ($operand1 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x])); $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true); /** @var array $r */ $r = $stack->pop(); $result[$x] = $r['value']; } } else { throw new Exception('Neither operand is an arra'); } // Log the result details $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Array', $result); return $result; } /** @return array|bool|string */ private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool|string { // If we're dealing with matrix operations, we want a matrix result if ((is_array($operand1)) || (is_array($operand2))) { return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays); } $result = BinaryComparison::compare($operand1, $operand2, $operation); // Log the result details $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed { // Validate the two operands if ( ($this->validateBinaryOperand($operand1, $stack) === false) || ($this->validateBinaryOperand($operand2, $stack) === false) ) { return false; } if ( (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '') || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== '')) ) { $result = ExcelError::VALUE(); } elseif (is_array($operand1) || is_array($operand2)) { // Ensure that both operands are arrays/matrices if (is_array($operand1)) { foreach ($operand1 as $key => $value) { $operand1[$key] = Functions::flattenArray($value); } } if (is_array($operand2)) { foreach ($operand2 as $key => $value) { $operand2[$key] = Functions::flattenArray($value); } } [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { /** @var mixed[][] $operand1 */ if (($operand1[$row][$column] ?? null) === null) { $operand1[$row][$column] = 0; } elseif (!self::isNumericOrBool($operand1[$row][$column])) { $operand1[$row][$column] = self::makeError($operand1[$row][$column]); continue; } /** @var mixed[][] $operand2 */ if (($operand2[$row][$column] ?? null) === null) { $operand2[$row][$column] = 0; } elseif (!self::isNumericOrBool($operand2[$row][$column])) { $operand1[$row][$column] = self::makeError($operand2[$row][$column]); continue; } /** @var float|int */ $operand1Val = $operand1[$row][$column]; /** @var float|int */ $operand2Val = $operand2[$row][$column]; switch ($operation) { case '+': $operand1[$row][$column] = $operand1Val + $operand2Val; break; case '-': $operand1[$row][$column] = $operand1Val - $operand2Val; break; case '*': $operand1[$row][$column] = $operand1Val * $operand2Val; break; case '/': if ($operand2Val == 0) { $operand1[$row][$column] = ExcelError::DIV0(); } else { $operand1[$row][$column] = $operand1Val / $operand2Val; } break; case '^': $operand1[$row][$column] = $operand1Val ** $operand2Val; break; default: throw new Exception('Unsupported numeric binary operation'); } } } $result = $operand1; } else { // If we're dealing with non-matrix operations, execute the necessary operation /** @var float|int $operand1 */ /** @var float|int $operand2 */ switch ($operation) { // Addition case '+': $result = $operand1 + $operand2; break; // Subtraction case '-': $result = $operand1 - $operand2; break; // Multiplication case '*': $result = $operand1 * $operand2; break; // Division case '/': if ($operand2 == 0) { // Trap for Divide by Zero error $stack->push('Error', ExcelError::DIV0()); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0())); return false; } $result = $operand1 / $operand2; break; // Power case '^': $result = $operand1 ** $operand2; break; default: throw new Exception('Unsupported numeric binary operation'); } } // Log the result details $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } /** * Trigger an error, but nicely, if need be. * * @return false */ protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool { $this->formulaError = $errorMessage; $this->cyclicReferenceStack->clear(); $suppress = $this->suppressFormulaErrors; $suppressed = $suppress ? ' $suppressed' : ''; $this->debugLog->writeDebugLog("Raise Error$suppressed $errorMessage"); if (!$suppress) { throw new Exception($errorMessage, $code, $exception); } return false; } /** * Extract range values. * * @param string $range String based range representation * @param ?Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed[] Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true, bool $createCell = false): array { // Return value /** @var mixed[][] */ $returnValue = []; if ($worksheet !== null) { $worksheetName = $worksheet->getTitle(); if (str_contains($range, '!')) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true); $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName); } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($range); $range = "'" . $worksheetName . "'" . '!' . $range; $currentCol = ''; $currentRow = 0; if (!isset($aReferences[1])) { // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); /** @var string $currentCol */ /** @var int $currentRow */ if ($createCell && $worksheet !== null && !$worksheet->cellExists($aReferences[0])) { $worksheet->setCellValue($aReferences[0], null); } if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) { $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) { while (is_array($temp)) { $temp = array_shift($temp); } } $returnValue[$currentRow][$currentCol] = $temp; } else { $returnValue[$currentRow][$currentCol] = null; } } else { // Extract cell data for all cells in the range foreach ($aReferences as $reference) { // Extract range sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); /** @var string $currentCol */ /** @var int $currentRow */ if ($createCell && $worksheet !== null && !$worksheet->cellExists($reference)) { $worksheet->setCellValue($reference, null); } if ($worksheet !== null && $worksheet->cellExists($reference)) { $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog); if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) { while (is_array($temp)) { $temp = array_shift($temp); } } $returnValue[$currentRow][$currentCol] = $temp; } else { $returnValue[$currentRow][$currentCol] = null; } } } } return $returnValue; } /** * Extract range values. * * @param string $range String based range representation * @param null|Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed[]|string Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array { // Return value $returnValue = []; if ($worksheet !== null) { if (str_contains($range, '!')) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true); $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName); } // Named range? $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet); if ($namedRange === null) { return ExcelError::REF(); } $worksheet = $namedRange->getWorksheet(); $range = $namedRange->getValue(); $splitRange = Coordinate::splitRange($range); // Convert row and column references if ($worksheet !== null && ctype_alpha($splitRange[0][0])) { $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow(); } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) { $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1]; } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($range); if (!isset($aReferences[1])) { // Single cell (or single column or row) in range [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]); /** @var mixed[][] $returnValue */ if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } else { // Extract cell data for all cells in the range foreach ($aReferences as $reference) { // Extract range [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference); if ($worksheet !== null && $worksheet->cellExists($reference)) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } } } return $returnValue; } /** * Is a specific function implemented? * * @param string $function Function Name */ public function isImplemented(string $function): bool { $function = strtoupper($function); $phpSpreadsheetFunctions = &self::getFunctionsAddress(); $notImplemented = !isset($phpSpreadsheetFunctions[$function]) || (is_array($phpSpreadsheetFunctions[$function]['functionCall']) && $phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY'); return !$notImplemented; } /** * Get a list of implemented Excel function names. * * @return string[] */ public function getImplementedFunctionNames(): array { $returnValue = []; $phpSpreadsheetFunctions = &self::getFunctionsAddress(); foreach ($phpSpreadsheetFunctions as $functionName => $function) { if ($this->isImplemented($functionName)) { $returnValue[] = $functionName; } } return $returnValue; } /** * @param string[] $functionCall * @param mixed[] $args * @param mixed[] $emptyArguments * * @return mixed[] */ private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array { $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]); $methodArguments = $reflector->getParameters(); if (count($methodArguments) > 0) { // Apply any defaults for empty argument values foreach ($emptyArguments as $argumentId => $isArgumentEmpty) { if ($isArgumentEmpty === true) { $reflectedArgumentId = count($args) - (int) $argumentId - 1; if ( !array_key_exists($reflectedArgumentId, $methodArguments) || $methodArguments[$reflectedArgumentId]->isVariadic() ) { break; } $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]); } } } return $args; } private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed { $defaultValue = null; if ($methodArgument->isDefaultValueAvailable()) { $defaultValue = $methodArgument->getDefaultValue(); if ($methodArgument->isDefaultValueConstant()) { $constantName = $methodArgument->getDefaultValueConstantName() ?? ''; // read constant value if (str_contains($constantName, '::')) { [$className, $constantName] = explode('::', $constantName); /** @var class-string $className */ $constantReflector = new ReflectionClassConstant($className, $constantName); return $constantReflector->getValue(); } return constant($constantName); } } return $defaultValue; } /** * Add cell reference if needed while making sure that it is the last argument. * * @param mixed[] $args * @param string|string[] $functionCall * * @return mixed[] */ private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array { if ($passCellReference) { if (is_array($functionCall)) { $className = $functionCall[0]; $methodName = $functionCall[1]; $reflectionMethod = new ReflectionMethod($className, $methodName); $argumentCount = count($reflectionMethod->getParameters()); while (count($args) < $argumentCount - 1) { $args[] = null; } } $args[] = $cell; } return $args; } private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed { $definedNameScope = $namedRange->getScope(); if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet && !$ignoreScope) { // The defined name isn't in our current scope, so #REF $result = ExcelError::REF(); $stack->push('Error', $result, $namedRange->getName()); return $result; } $definedNameValue = $namedRange->getValue(); $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range'; if ($definedNameType === 'Range') { if (Preg::isMatch('/^(.*!)?(.*)$/', $definedNameValue, $matches)) { $matches2 = Preg::replace( ['/ +/', '/,/'], [' ∩ ', ' ∪ '], trim($matches[2]) ); $definedNameValue = $matches[1] . $matches2; } } $definedNameWorksheet = $namedRange->getWorksheet(); if ($definedNameValue[0] !== '=') { $definedNameValue = '=' . $definedNameValue; } $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue); $originalCoordinate = $cell->getCoordinate(); $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet) ? $definedNameWorksheet->getCell('A1') : $cell; $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate(); // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns $definedNameValue = ReferenceHelper::getInstance() ->updateFormulaReferencesAnyWorksheet( $definedNameValue, Coordinate::columnIndexFromString( $cell->getColumn() ) - 1, $cell->getRow() - 1 ); $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue); $recursiveCalculator = new self($this->spreadsheet); $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog()); $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog()); $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true); $cellWorksheet->getCell($originalCoordinate); if ($this->getDebugLog()->getWriteDebugLog()) { $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3)); $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result)); } $y = $namedRange->getWorksheet()?->getTitle(); $x = $namedRange->getLocalOnly(); if ($x && $y !== null) { $stack->push('Defined Name', $result, "'$y'!" . $namedRange->getName()); } else { $stack->push('Defined Name', $result, $namedRange->getName()); } return $result; } public function setSuppressFormulaErrors(bool $suppressFormulaErrors): self { $this->suppressFormulaErrors = $suppressFormulaErrors; return $this; } public function getSuppressFormulaErrors(): bool { return $this->suppressFormulaErrors; } public static function boolToString(mixed $operand1): mixed { if (is_bool($operand1)) { $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } elseif ($operand1 === null) { $operand1 = ''; } return $operand1; } private static function isNumericOrBool(mixed $operand): bool { return is_numeric($operand) || is_bool($operand); } private static function makeError(mixed $operand = ''): string { return (is_string($operand) && Information\ErrorValue::isError($operand)) ? $operand : ExcelError::VALUE(); } private static function swapOperands(Stack $stack, string $opCharacter): bool { $retVal = false; if ($stack->count() > 0) { $o2 = $stack->last(); if ($o2) { /** @var array{value: string} $o2 */ if (isset(self::CALCULATION_OPERATORS[$o2['value']])) { $retVal = (self::OPERATOR_PRECEDENCE[$opCharacter] ?? 0) <= self::OPERATOR_PRECEDENCE[$o2['value']]; } } } return $retVal; } public function getSpreadsheet(): ?Spreadsheet { return $this->spreadsheet; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/CalculationBase.php ================================================ */ public static function getFunctions(): array { return FunctionArray::$phpSpreadsheetFunctions; } /** * Get address of list of all implemented functions as an array of function objects. * * @return array> */ protected static function &getFunctionsAddress(): array { return FunctionArray::$phpSpreadsheetFunctions; } /** * @param array{category: string, functionCall: string|string[], argumentCount: string, passCellReference?: bool, passByReference?: bool[], custom?: bool} $value */ public static function addFunction(string $key, array $value): bool { $key = strtoupper($key); if ( array_key_exists($key, FunctionArray::$phpSpreadsheetFunctions) && !self::isDummy($key) ) { return false; } $value['custom'] = true; FunctionArray::$phpSpreadsheetFunctions[$key] = $value; return true; } private static function isDummy(string $key): bool { // key is already known to exist $functionCall = FunctionArray::$phpSpreadsheetFunctions[$key]['functionCall'] ?? null; if (!is_array($functionCall)) { return false; } if (($functionCall[1] ?? '') !== 'DUMMY') { return false; } return true; } public static function removeFunction(string $key): bool { $key = strtoupper($key); if (array_key_exists($key, FunctionArray::$phpSpreadsheetFunctions)) { if (FunctionArray::$phpSpreadsheetFunctions[$key]['custom'] ?? false) { unset(FunctionArray::$phpSpreadsheetFunctions[$key]); return true; } } return false; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/CalculationLocale.php ================================================ */ protected static array $localeBoolean = [ 'TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL', ]; /** @var array> */ protected static array $falseTrueArray = []; public static function getLocaleBoolean(string $index): string { return self::$localeBoolean[$index]; } protected static function loadLocales(): void { $localeFileDirectory = __DIR__ . '/locale/'; $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: []; foreach ($localeFileNames as $filename) { $filename = substr($filename, strlen($localeFileDirectory)); if ($filename != 'en') { self::$validLocaleLanguages[] = $filename; $subdirs = glob("$localeFileDirectory$filename/*", GLOB_ONLYDIR) ?: []; foreach ($subdirs as $subdir) { $subdirx = basename($subdir); self::$validLocaleLanguages[] = "{$filename}_{$subdirx}"; } } } } /** * Return the locale-specific translation of TRUE. * * @return string locale-specific translation of TRUE */ public static function getTRUE(): string { return self::$localeBoolean['TRUE']; } /** * Return the locale-specific translation of FALSE. * * @return string locale-specific translation of FALSE */ public static function getFALSE(): string { return self::$localeBoolean['FALSE']; } /** * Get the currently defined locale code. */ public function getLocale(): string { return self::$localeLanguage; } protected function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string { $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { // If there isn't a locale specific file, look for a language specific file $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { throw new Exception('Locale file not found'); } } return $localeFileName; } /** @return array> */ public function getFalseTrueArray(): array { if (!empty(self::$falseTrueArray)) { return self::$falseTrueArray; } if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } $falseTrueArray = [['FALSE'], ['TRUE']]; foreach (self::$validLocaleLanguages as $language) { if (str_starts_with($language, 'en')) { continue; } $locale = $language; if (str_contains($locale, '_')) { [$language] = explode('_', $locale); } $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); try { $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); } catch (Exception $e) { continue; } // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (str_contains($localeFunction, '=')) { [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ($fName === 'FALSE') { $falseTrueArray[0][] = $lfName; } elseif ($fName === 'TRUE') { $falseTrueArray[1][] = $lfName; } } } } self::$falseTrueArray = $falseTrueArray; return $falseTrueArray; } /** * Set the locale code. * * @param string $locale The locale to use for formula translation, eg: 'en_us' */ public function setLocale(string $locale): bool { // Identify our locale and language $language = $locale = strtolower($locale); if (str_contains($locale, '_')) { [$language] = explode('_', $locale); } if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages, true)) { // initialise language/locale settings self::$localeFunctions = []; self::$localeArgumentSeparator = ','; self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; // Default is US English, if user isn't requesting US english, then read the necessary data from the locale files if ($locale !== 'en_us') { $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); // Search for a file with a list of function names for locale try { $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); } catch (Exception $e) { return false; } // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; $phpSpreadsheetFunctions = &self::getFunctionsAddress(); foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (str_contains($localeFunction, '=')) { [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ((str_starts_with($fName, '*') || isset($phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { self::$localeFunctions[$fName] = $lfName; } } } // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions if (isset(self::$localeFunctions['TRUE'])) { self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE']; } if (isset(self::$localeFunctions['FALSE'])) { self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } try { $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config'); } catch (Exception) { return false; } $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeSettings as $localeSetting) { [$localeSetting] = explode('##', $localeSetting); // Strip out comments if (str_contains($localeSetting, '=')) { [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting)); $settingName = strtoupper($settingName); if ($settingValue !== '') { switch ($settingName) { case 'ARGUMENTSEPARATOR': self::$localeArgumentSeparator = $settingValue; break; } } } } } self::$functionReplaceFromExcel = self::$functionReplaceToExcel = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; self::$localeLanguage = $locale; return true; } return false; } public static function translateSeparator( string $fromSeparator, string $toSeparator, string $formula, int &$inBracesLevel, string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE, string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE ): string { $strlen = mb_strlen($formula); for ($i = 0; $i < $strlen; ++$i) { $chr = mb_substr($formula, $i, 1); switch ($chr) { case $openBrace: ++$inBracesLevel; break; case $closeBrace: --$inBracesLevel; break; case $fromSeparator: if ($inBracesLevel > 0) { $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1); } } } return $formula; } /** * @param string[] $from * @param string[] $to */ protected static function translateFormulaBlock( array $from, array $to, string $formula, int &$inFunctionBracesLevel, int &$inMatrixBracesLevel, string $fromSeparator, string $toSeparator ): string { // Function Names $formula = (string) preg_replace($from, $to, $formula); // Temporarily adjust matrix separators so that they won't be confused with function arguments $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); // Function Argument Separators $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel); // Restore matrix separators $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); return $formula; } /** * @param string[] $from * @param string[] $to */ protected static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string { // Convert any Excel function names and constant names to the required language; // and adjust function argument separators if (self::$localeLanguage !== 'en_us') { $inFunctionBracesLevel = 0; $inMatrixBracesLevel = 0; // If there is the possibility of separators within a quoted string, then we treat them as literals if (str_contains($formula, self::FORMULA_STRING_QUOTE)) { // So instead we skip replacing in any quoted strings by only replacing in every other array element // after we've exploded the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); $notWithinQuotes = false; foreach ($temp as &$value) { // Only adjust in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } return $formula; } /** @var null|string[] */ private static ?array $functionReplaceFromExcel; /** @var null|string[] */ private static ?array $functionReplaceToLocale; public function translateFormulaToLocale(string $formula): string { $formula = preg_replace(self::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula) ?? ''; // Build list of function names and constants for translation if (self::$functionReplaceFromExcel === null) { self::$functionReplaceFromExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToLocale === null) { self::$functionReplaceToLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2'; } foreach (self::$localeBoolean as $localeBoolean) { self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2'; } } return self::translateFormula( self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator ); } /** @var null|string[] */ protected static ?array $functionReplaceFromLocale; /** @var null|string[] */ protected static ?array $functionReplaceToExcel; public function translateFormulaToEnglish(string $formula): string { if (self::$functionReplaceFromLocale === null) { self::$functionReplaceFromLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui'; } foreach (self::$localeBoolean as $excelBoolean) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToExcel === null) { self::$functionReplaceToExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2'; } } return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); } public static function localeFunc(string $function): string { if (self::$localeLanguage !== 'en_us') { $functionName = trim($function, '('); if (isset(self::$localeFunctions[$functionName])) { $brace = ($functionName != $function); $function = self::$localeFunctions[$functionName]; if ($brace) { $function .= '('; } } } return $function; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/CalculationParserOnly.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|int|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Averages::average( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DCount.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnError = true): string|int { $field = self::fieldExtract($database, $field); if ($returnError && $field === null) { return ExcelError::VALUE(); } return Counts::COUNT( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DCountA.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|int { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Counts::COUNTA( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DGet.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): null|float|int|string { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } $columnData = self::getFilteredColumn($database, $field, $criteria); if (count($columnData) > 1) { return ExcelError::NAN(); } /** @var array */ $row = array_pop($columnData); return array_pop($row); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DMax.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnError = true): null|float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnError ? ExcelError::VALUE() : null; } return Maximum::max( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DMin.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnError = true): float|string|null { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnError ? ExcelError::VALUE() : null; } return Minimum::min( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DProduct.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return MathTrig\Operations::product( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DStDev.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return StandardDeviations::STDEV( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DStDevP.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return StandardDeviations::STDEVP( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DSum.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnNull = false): null|float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnNull ? null : ExcelError::VALUE(); } return MathTrig\Sum::sumIgnoringStrings( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DVar.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string (string if result is an error) */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Variances::VAR( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DVarP.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string (string if result is an error) */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Variances::VARP( self::getFilteredColumn($database, $field, $criteria) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php ================================================ |int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ abstract public static function evaluate(array $database, array|null|int|string $field, array $criteria): null|float|int|string; /** * fieldExtract. * * Extracts the column ID to use for the data field. * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. */ protected static function fieldExtract(array $database, mixed $field): ?int { /** @var ?string */ $single = Functions::flattenSingleValue($field); $field = strtoupper($single ?? ''); if ($field === '') { return null; } /** @var callable */ $callable = 'strtoupper'; $fieldNames = array_map($callable, array_shift($database)); //* @phpstan-ignore-line if (is_numeric($field)) { $field = (int) $field - 1; if ($field < 0 || $field >= count($fieldNames)) { return null; } return $field; } $key = array_search($field, array_values($fieldNames), true); return ($key !== false) ? (int) $key : null; } /** * filter. * * Parses the selection criteria, extracts the database rows that match those criteria, and * returns that subset of rows. * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed[][] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return mixed[] */ protected static function filter(array $database, array $criteria): array { /** @var mixed[] */ $fieldNames = array_shift($database); $criteriaNames = array_shift($criteria); // Convert the criteria into a set of AND/OR conditions with [:placeholders] /** @var string[] $criteriaNames */ $query = self::buildQuery($criteriaNames, $criteria); // Loop through each row of the database /** @var mixed[][] $criteriaNames */ return self::executeQuery($database, $query, $criteriaNames, $fieldNames); } /** * @param mixed[] $database The range of cells that makes up the list or database * @param mixed[][] $criteria * * @return mixed[] */ protected static function getFilteredColumn(array $database, ?int $field, array $criteria): array { // reduce the database to a set of rows that match all the criteria $database = self::filter($database, $criteria); $defaultReturnColumnValue = ($field === null) ? 1 : null; // extract an array of values for the requested column $columnData = []; /** @var mixed[] $row */ foreach ($database as $rowKey => $row) { $keys = array_keys($row); $key = ($field === null) ? null : ($keys[$field] ?? null); $columnKey = $key ?? 'A'; $columnData[$rowKey][$columnKey] = ($key === null) ? $defaultReturnColumnValue : ($row[$key] ?? $defaultReturnColumnValue); } return $columnData; } /** * @param string[] $criteriaNames * @param mixed[][] $criteria */ private static function buildQuery(array $criteriaNames, array $criteria): string { $baseQuery = []; foreach ($criteria as $key => $criterion) { foreach ($criterion as $field => $value) { $criterionName = $criteriaNames[$field]; if ($value !== null) { $condition = self::buildCondition($value, $criterionName); $baseQuery[$key][] = $condition; } } } $rowQuery = array_map( fn ($rowValue): string => (count($rowValue) > 1) ? 'AND(' . implode(',', $rowValue) . ')' : ($rowValue[0] ?? ''), // @phpstan-ignore-line $baseQuery ); return (count($rowQuery) > 1) ? 'OR(' . implode(',', $rowQuery) . ')' : ($rowQuery[0] ?? ''); } private static function buildCondition(mixed $criterion, string $criterionName): string { $ifCondition = Functions::ifCondition($criterion); // Check for wildcard characters used in the condition $result = preg_match('/(?[^"]*)(?".*[*?].*")/ui', $ifCondition, $matches); if ($result !== 1) { return "[:{$criterionName}]{$ifCondition}"; } $trueFalse = ($matches['operator'] !== '<>'); $wildcard = WildcardMatch::wildcard($matches['operand']); $condition = "WILDCARDMATCH([:{$criterionName}],{$wildcard})"; if ($trueFalse === false) { $condition = "NOT({$condition})"; } return $condition; } /** * @param mixed[] $database * @param mixed[][] $criteria * @param array $fields * * @return mixed[] */ private static function executeQuery(array $database, string $query, array $criteria, array $fields): array { foreach ($database as $dataRow => $dataValues) { // Substitute actual values from the database row for our [:placeholders] $conditions = $query; foreach ($criteria as $criterion) { /** @var string $criterion */ /** @var mixed[] $dataValues */ $conditions = self::processCondition($criterion, $fields, $dataValues, $conditions); } // evaluate the criteria against the row data $result = Calculation::getInstance()->_calculateFormulaValue('=' . $conditions); // If the row failed to meet the criteria, remove it from the database if ($result !== true) { unset($database[$dataRow]); } } return $database; } /** * @param array $fields * @param array $dataValues */ private static function processCondition(string $criterion, array $fields, array $dataValues, string $conditions): string { $key = array_search($criterion, $fields, true); $dataValue = 'NULL'; if (is_bool($dataValues[$key])) { $dataValue = ($dataValues[$key]) ? 'TRUE' : 'FALSE'; } elseif ($dataValues[$key] !== null) { $dataValue = $dataValues[$key]; // escape quotes if we have a string containing quotes if (is_string($dataValue) && str_contains($dataValue, '"')) { $dataValue = str_replace('"', '""', $dataValue); } if (is_string($dataValue)) { $dataValue = Calculation::wrapResult(strtoupper($dataValue)); } $dataValue = StringHelper::convertToString($dataValue); } return str_replace('[:' . $criterion . ']', $dataValue, $conditions); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php ================================================ self::DOW_SUNDAY, self::DOW_MONDAY, self::STARTWEEK_MONDAY_ALT => self::DOW_MONDAY, self::DOW_TUESDAY, self::DOW_WEDNESDAY, self::DOW_THURSDAY, self::DOW_FRIDAY, self::DOW_SATURDAY, self::DOW_SUNDAY, self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, ]; } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php ================================================ format('c')); return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray, true) : ExcelError::VALUE(); } /** * DATETIMENOW. * * Returns the current date and time. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * NOW() * * @return DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function now(): DateTime|float|int|string { $dti = new DateTimeImmutable(); $dateArray = Helpers::dateParse($dti->format('c')); return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray) : ExcelError::VALUE(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php ================================================ |float|int|string $year The value of the year argument can include one to four digits. * Excel interprets the year argument according to the configured * date system: 1900 or 1904. * If year is between 0 (zero) and 1899 (inclusive), Excel adds that * value to 1900 to calculate the year. For example, DATE(108,1,2) * returns January 2, 2008 (1900+108). * If year is between 1900 and 9999 (inclusive), Excel uses that * value as the year. For example, DATE(2008,1,2) returns January 2, * 2008. * If year is less than 0 or is 10000 or greater, Excel returns the * #NUM! error value. * @param array|float|int|string $month A positive or negative integer representing the month of the year * from 1 to 12 (January to December). * If month is greater than 12, month adds that number of months to * the first month in the year specified. For example, DATE(2008,14,2) * returns the serial number representing February 2, 2009. * If month is less than 1, month subtracts the magnitude of that * number of months, plus 1, from the first month in the year * specified. For example, DATE(2008,-3,2) returns the serial number * representing September 2, 2007. * @param array|float|int|string $day A positive or negative integer representing the day of the month * from 1 to 31. * If day is greater than the number of days in the month specified, * day adds that number of days to the first day in the month. For * example, DATE(2008,1,35) returns the serial number representing * February 4, 2008. * If day is less than 1, day subtracts the magnitude that number of * days, plus one, from the first day of the month specified. For * example, DATE(2008,1,-15) returns the serial number representing * December 16, 2007. * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromYMD(array|float|int|string $year, null|array|bool|float|int|string $month, array|float|int|string $day): float|int|DateTime|string|array { if (is_array($year) || is_array($month) || is_array($day)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $year, $month, $day); } $baseYear = SharedDateHelper::getExcelCalendar(); try { $year = self::getYear($year, $baseYear); $month = self::getMonth($month); $day = self::getDay($day); self::adjustYearMonth($year, $month, $baseYear); } catch (Exception $e) { return $e->getMessage(); } // Execute function $excelDateValue = SharedDateHelper::formattedPHPToExcel($year, $month, $day); return Helpers::returnIn3FormatsFloat($excelDateValue); } /** * Convert year from multiple formats to int. */ private static function getYear(mixed $year, int $baseYear): int { if ($year === null) { $year = 0; } elseif (is_scalar($year)) { $year = StringHelper::testStringAsNumeric((string) $year); } if (!is_numeric($year)) { throw new Exception(ExcelError::VALUE()); } $year = (int) $year; if ($year < ($baseYear - 1900)) { throw new Exception(ExcelError::NAN()); } if ((($baseYear - 1900) !== 0) && ($year < $baseYear) && ($year >= 1900)) { throw new Exception(ExcelError::NAN()); } if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { $year += 1900; } return (int) $year; } /** * Convert month from multiple formats to int. */ private static function getMonth(mixed $month): int { if (is_string($month)) { if (!is_numeric($month)) { $month = SharedDateHelper::monthStringToNumber($month); } } elseif ($month === null) { $month = 0; } elseif (is_bool($month)) { $month = (int) $month; } if (!is_numeric($month)) { throw new Exception(ExcelError::VALUE()); } return (int) $month; } /** * Convert day from multiple formats to int. */ private static function getDay(mixed $day): int { if (is_string($day) && !is_numeric($day)) { $day = SharedDateHelper::dayStringToNumber($day); } if ($day === null) { $day = 0; } elseif (is_scalar($day)) { $day = StringHelper::testStringAsNumeric((string) $day); } if (!is_numeric($day)) { throw new Exception(ExcelError::VALUE()); } return (int) $day; } private static function adjustYearMonth(int &$year, int &$month, int $baseYear): void { if ($month < 1) { // Handle year/month adjustment if month < 1 --$month; $year += (int) (ceil($month / 12) - 1); $month = 13 - abs($month % 12); } elseif ($month > 12) { // Handle year/month adjustment if month > 12 $year += intdiv($month, 12); $month = ($month % 12); } // Re-validate the year parameter after adjustments if (($year < $baseYear) || ($year >= 10000)) { throw new Exception(ExcelError::NAN()); } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php ================================================ |int|string Day of the month * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function day(mixed $dateValue): array|int|string { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } $weirdResult = self::weirdCondition($dateValue); if ($weirdResult >= 0) { return $weirdResult; } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); SharedDateHelper::roundMicroseconds($PHPDateObject); return (int) $PHPDateObject->format('j'); } /** * MONTHOFYEAR. * * Returns the month of a date represented by a serial number. * The month is given as an integer, ranging from 1 (January) to 12 (December). * * Excel Function: * MONTH(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Month of the year * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function month(mixed $dateValue): array|string|int { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { return 1; } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); SharedDateHelper::roundMicroseconds($PHPDateObject); return (int) $PHPDateObject->format('n'); } /** * YEAR. * * Returns the year corresponding to a date. * The year is returned as an integer in the range 1900-9999. * * Excel Function: * YEAR(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Year * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function year(mixed $dateValue): array|string|int { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { return 1900; } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); SharedDateHelper::roundMicroseconds($PHPDateObject); return (int) $PHPDateObject->format('Y'); } /** * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string */ private static function weirdCondition(mixed $dateValue): int { // Excel does not treat 0 consistently for DAY vs. (MONTH or YEAR) if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900 && Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { if (is_bool($dateValue)) { return (int) $dateValue; } if ($dateValue === null) { return 0; } if (is_numeric($dateValue) && $dateValue < 1 && $dateValue >= 0) { return 0; } } return -1; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php ================================================ |bool|float|int|string $dateValue Text that represents a date in a Microsoft Excel date format. * For example, "1/30/2008" or "30-Jan-2008" are text strings within * quotation marks that represent dates. Using the default date * system in Excel for Windows, date_text must represent a date from * January 1, 1900, to December 31, 9999. Using the default date * system in Excel for the Macintosh, date_text must represent a date * from January 1, 1904, to December 31, 9999. DATEVALUE returns the * #VALUE! error value if date_text is out of this range. * Or can be an array of date values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromString(null|array|string|int|bool|float $dateValue): array|string|float|int|DateTime { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } // try to parse as date iff there is at least one digit if (is_string($dateValue) && preg_match('/\d/', $dateValue) !== 1) { return ExcelError::VALUE(); } $dti = new DateTimeImmutable(); $baseYear = SharedDateHelper::getExcelCalendar(); $dateValue = trim((string) $dateValue, '"'); // Strip any ordinals because they're allowed in Excel (English only) $dateValue = (string) preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) $dateValue = str_replace(['/', '.', '-', ' '], ' ', $dateValue); $yearFound = false; $t1 = explode(' ', $dateValue); $t = ''; foreach ($t1 as &$t) { if ((is_numeric($t)) && ($t > 31)) { if ($yearFound) { return ExcelError::VALUE(); } if ($t < 100) { $t += 1900; } $yearFound = true; } } if (count($t1) === 1) { // We've been fed a time value without any date return ((!str_contains((string) $t, ':'))) ? ExcelError::Value() : 0.0; } unset($t); $dateValue = self::t1ToString($t1, $dti, $yearFound); $PHPDateArray = self::setUpArray($dateValue, $dti); return self::finalResults($PHPDateArray, $dti, $baseYear); } /** @param mixed[] $t1 */ private static function t1ToString(array $t1, DateTimeImmutable $dti, bool $yearFound): string { if (count($t1) == 2) { // We only have two parts of the date: either day/month or month/year if ($yearFound) { array_unshift($t1, 1); } else { if (is_numeric($t1[1]) && $t1[1] > 29) { $t1[1] += 1900; array_unshift($t1, 1); } else { $t1[] = $dti->format('Y'); } } } $dateValue = implode(' ', $t1); return $dateValue; } /** * Parse date. * * @return mixed[] */ private static function setUpArray(string $dateValue, DateTimeImmutable $dti): array { $PHPDateArray = Helpers::dateParse($dateValue); if (!Helpers::dateParseSucceeded($PHPDateArray)) { // If original count was 1, we've already returned. // If it was 2, we added another. // Therefore, neither of the first 2 strtoks below can fail. $testVal1 = strtok($dateValue, '- '); $testVal2 = strtok('- '); $testVal3 = strtok('- ') ?: $dti->format('Y'); Helpers::adjustYear((string) $testVal1, (string) $testVal2, $testVal3); $PHPDateArray = Helpers::dateParse($testVal1 . '-' . $testVal2 . '-' . $testVal3); if (!Helpers::dateParseSucceeded($PHPDateArray)) { $PHPDateArray = Helpers::dateParse($testVal2 . '-' . $testVal1 . '-' . $testVal3); } } return $PHPDateArray; } /** * Final results. * * @param mixed[] $PHPDateArray * * @return DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ private static function finalResults(array $PHPDateArray, DateTimeImmutable $dti, int $baseYear): string|float|int|DateTime { $retValue = ExcelError::Value(); if (Helpers::dateParseSucceeded($PHPDateArray)) { /** @var array{year: int, month: int, day: int, hour: int, minute: int, second: int} $PHPDateArray */ // Execute function Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y')); if ($PHPDateArray['year'] < $baseYear) { return ExcelError::VALUE(); } Helpers::replaceIfEmpty($PHPDateArray['month'], $dti->format('m')); Helpers::replaceIfEmpty($PHPDateArray['day'], $dti->format('d')); /** @var array{year: int, month: int, day: int, hour: int, minute: int, second: int} $PHPDateArray */ $PHPDateArray['hour'] = 0; $PHPDateArray['minute'] = 0; $PHPDateArray['second'] = 0; $month = self::getInt($PHPDateArray, 'month'); $day = self::getInt($PHPDateArray, 'day'); $year = self::getInt($PHPDateArray, 'year'); if (!checkdate($month, $day, $year)) { return ($year === 1900 && $month === 2 && $day === 29) ? Helpers::returnIn3FormatsFloat(60.0) : ExcelError::VALUE(); } $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true); } return $retValue; } /** @param mixed[] $array */ private static function getInt(array $array, string $index): int { return (array_key_exists($index, $array) && is_numeric($array[$index])) ? (int) $array[$index] : 0; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php ================================================ |DateTimeInterface|float|int|string $endDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|DateTimeInterface|float|int|string $startDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Number of days between start date and end date or an error * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function between(array|DateTimeInterface|float|int|string $endDate, array|DateTimeInterface|float|int|string $startDate): array|int|string { if (is_array($endDate) || is_array($startDate)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $endDate, $startDate); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $days = ExcelError::VALUE(); $diff = $PHPStartDateObject->diff($PHPEndDateObject); if (!is_bool($diff->days)) { $days = $diff->days; if ($diff->invert) { $days = -$days; } } return $days; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php ================================================ |int|string Number of days between start date and end date * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function between(mixed $startDate = 0, mixed $endDate = 0, mixed $method = false): array|string|int { if (is_array($startDate) || is_array($endDate) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $method); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); } catch (Exception $e) { return $e->getMessage(); } if (!is_bool($method)) { return ExcelError::VALUE(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $startDay = $PHPStartDateObject->format('j'); $startMonth = $PHPStartDateObject->format('n'); $startYear = $PHPStartDateObject->format('Y'); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $endDay = $PHPEndDateObject->format('j'); $endMonth = $PHPEndDateObject->format('n'); $endYear = $PHPEndDateObject->format('Y'); return self::dateDiff360((int) $startDay, (int) $startMonth, (int) $startYear, (int) $endDay, (int) $endMonth, (int) $endYear, !$method); } /** * Return the number of days between two dates based on a 360-day calendar. */ private static function dateDiff360(int $startDay, int $startMonth, int $startYear, int $endDay, int $endMonth, int $endYear, bool $methodUS): int { $startDay = self::getStartDay($startDay, $startMonth, $startYear, $methodUS); $endDay = self::getEndDay($endDay, $endMonth, $endYear, $startDay, $methodUS); return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; } private static function getStartDay(int $startDay, int $startMonth, int $startYear, bool $methodUS): int { if ($startDay == 31) { --$startDay; } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !Helpers::isLeapYear($startYear))))) { $startDay = 30; } return $startDay; } private static function getEndDay(int $endDay, int &$endMonth, int &$endYear, int $startDay, bool $methodUS): int { if ($endDay == 31) { if ($methodUS && $startDay != 30) { $endDay = 1; if ($endMonth == 12) { ++$endYear; $endMonth = 1; } else { ++$endMonth; } } else { $endDay = 30; } } return $endDay; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php ================================================ |string $unit Or can be an array of unit values * * @return array|int|string Interval between the dates * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function interval(mixed $startDate, mixed $endDate, array|string $unit = 'D') { if (is_array($startDate) || is_array($endDate) || is_array($unit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $unit); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); $difference = self::initialDiff($startDate, $endDate); $unit = strtoupper($unit); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $startDays = (int) $PHPStartDateObject->format('j'); //$startMonths = (int) $PHPStartDateObject->format('n'); $startYears = (int) $PHPStartDateObject->format('Y'); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $endDays = (int) $PHPEndDateObject->format('j'); //$endMonths = (int) $PHPEndDateObject->format('n'); $endYears = (int) $PHPEndDateObject->format('Y'); $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject); $retVal = false; $retVal = self::replaceRetValue($retVal, $unit, 'D') ?? self::datedifD($difference); $retVal = self::replaceRetValue($retVal, $unit, 'M') ?? self::datedifM($PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'MD') ?? self::datedifMD($startDays, $endDays, $PHPEndDateObject, $PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'Y') ?? self::datedifY($PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'YD') ?? self::datedifYD($difference, $startYears, $endYears, $PHPStartDateObject, $PHPEndDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'YM') ?? self::datedifYM($PHPDiffDateObject); return is_bool($retVal) ? ExcelError::VALUE() : $retVal; } private static function initialDiff(float $startDate, float $endDate): float { // Validate parameters if ($startDate > $endDate) { throw new Exception(ExcelError::NAN()); } return $endDate - $startDate; } /** * Decide whether it's time to set retVal. */ private static function replaceRetValue(bool|int $retVal, string $unit, string $compare): null|bool|int { if ($retVal !== false || $unit !== $compare) { return $retVal; } return null; } private static function datedifD(float $difference): int { return (int) $difference; } private static function datedifM(DateInterval $PHPDiffDateObject): int { return 12 * (int) $PHPDiffDateObject->format('%y') + (int) $PHPDiffDateObject->format('%m'); } private static function datedifMD(int $startDays, int $endDays, DateTime $PHPEndDateObject, DateInterval $PHPDiffDateObject): int { if ($endDays < $startDays) { $retVal = $endDays; $PHPEndDateObject->modify('-' . $endDays . ' days'); $adjustDays = (int) $PHPEndDateObject->format('j'); $retVal += ($adjustDays - $startDays); } else { $retVal = (int) $PHPDiffDateObject->format('%d'); } return $retVal; } private static function datedifY(DateInterval $PHPDiffDateObject): int { return (int) $PHPDiffDateObject->format('%y'); } private static function datedifYD(float $difference, int $startYears, int $endYears, DateTime $PHPStartDateObject, DateTime $PHPEndDateObject): int { $retVal = (int) $difference; if ($endYears > $startYears) { $isLeapStartYear = $PHPStartDateObject->format('L'); $wasLeapEndYear = $PHPEndDateObject->format('L'); // Adjust end year to be as close as possible as start year while ($PHPEndDateObject >= $PHPStartDateObject) { $PHPEndDateObject->modify('-1 year'); //$endYears = $PHPEndDateObject->format('Y'); } $PHPEndDateObject->modify('+1 year'); // Get the result $retVal = (int) $PHPEndDateObject->diff($PHPStartDateObject)->days; // Adjust for leap years cases $isLeapEndYear = $PHPEndDateObject->format('L'); $limit = new DateTime($PHPEndDateObject->format('Y-02-29')); if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { --$retVal; } } return (int) $retVal; } private static function datedifYM(DateInterval $PHPDiffDateObject): int { return (int) $PHPDiffDateObject->format('%m'); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php ================================================ format('m'); $oYear = (int) $PHPDateObject->format('Y'); $adjustmentMonthsString = (string) $adjustmentMonths; if ($adjustmentMonths > 0) { $adjustmentMonthsString = '+' . $adjustmentMonths; } if ($adjustmentMonths != 0) { $PHPDateObject->modify($adjustmentMonthsString . ' months'); } $nMonth = (int) $PHPDateObject->format('m'); $nYear = (int) $PHPDateObject->format('Y'); $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); if ($monthDiff != $adjustmentMonths) { $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); } return $PHPDateObject; } /** * Help reduce perceived complexity of some tests. */ public static function replaceIfEmpty(mixed &$value, mixed $altValue): void { $value = $value ?: $altValue; } /** * Adjust year in ambiguous situations. */ public static function adjustYear(string $testVal1, string $testVal2, string &$testVal3): void { if (!is_numeric($testVal1) || $testVal1 < 31) { if (!is_numeric($testVal2) || $testVal2 < 12) { if (is_numeric($testVal3) && $testVal3 < 12) { $testVal3 = (string) ($testVal3 + 2000); } } } } /** * Return result in one of three formats. * * @param array{year: int, month: int, day: int, hour: int, minute: int, second: int} $dateArray */ public static function returnIn3FormatsArray(array $dateArray, bool $noFrac = false): DateTime|float|int { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { return new DateTime( $dateArray['year'] . '-' . $dateArray['month'] . '-' . $dateArray['day'] . ' ' . $dateArray['hour'] . ':' . $dateArray['minute'] . ':' . $dateArray['second'] ); } $excelDateValue = SharedDateHelper::formattedPHPToExcel( $dateArray['year'], $dateArray['month'], $dateArray['day'], $dateArray['hour'], $dateArray['minute'], $dateArray['second'] ); if ($retType === Functions::RETURNDATE_EXCEL) { return $noFrac ? floor($excelDateValue) : $excelDateValue; } // RETURNDATE_UNIX_TIMESTAMP) return SharedDateHelper::excelToTimestamp($excelDateValue); } /** * Return result in one of three formats. */ public static function returnIn3FormatsFloat(float $excelDateValue): float|int|DateTime { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { return $excelDateValue; } if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { return SharedDateHelper::excelToTimestamp($excelDateValue); } // RETURNDATE_PHP_DATETIME_OBJECT return SharedDateHelper::excelToDateTimeObject($excelDateValue); } /** * Return result in one of three formats. */ public static function returnIn3FormatsObject(DateTime $PHPDateObject): DateTime|float|int { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { return $PHPDateObject; } if ($retType === Functions::RETURNDATE_EXCEL) { return (float) SharedDateHelper::PHPToExcel($PHPDateObject); } // RETURNDATE_UNIX_TIMESTAMP $stamp = SharedDateHelper::PHPToExcel($PHPDateObject); $stamp = is_bool($stamp) ? ((int) $stamp) : $stamp; return SharedDateHelper::excelToTimestamp($stamp); } private static function baseDate(): int { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return 0; } if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904) { return 0; } return 1; } /** * Many functions accept null/false/true argument treated as 0/0/1. */ public static function nullFalseTrueToNumber(mixed &$number, bool $allowBool = true): void { $number = Functions::flattenSingleValue($number); $nullVal = self::baseDate(); if ($number === null) { $number = $nullVal; } elseif ($allowBool && is_bool($number)) { $number = $nullVal + (int) $number; } } /** * Many functions accept null argument treated as 0. */ public static function validateNumericNull(mixed $number): int|float { $number = Functions::flattenSingleValue($number); if ($number === null) { return 0; } if (is_int($number)) { return $number; } if (is_numeric($number)) { return (float) $number; } throw new Exception(ExcelError::VALUE()); } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @phpstan-assert float $number */ public static function validateNotNegative(mixed $number): float { if (!is_numeric($number)) { throw new Exception(ExcelError::VALUE()); } if ($number >= 0) { return (float) $number; } throw new Exception(ExcelError::NAN()); } public static function silly1900(DateTime $PHPDateObject, string $mod = '-1 day'): void { $isoDate = $PHPDateObject->format('c'); if ($isoDate < '1900-03-01') { $PHPDateObject->modify($mod); } } /** @return array{year: int, month: int, day: int, hour: int, minute: int, second: int} */ public static function dateParse(string $string): array { /** @var array{year: int, month: int, day: int, hour: int, minute: int, second: int} */ $temp = self::forceArray(date_parse($string)); return $temp; } /** @param mixed[] $dateArray */ public static function dateParseSucceeded(array $dateArray): bool { return $dateArray['error_count'] === 0; } /** * Despite documentation, date_parse probably never returns false. * Just in case, this routine helps guarantee it. * * @param array|false $dateArray * * @return mixed[] */ private static function forceArray(array|bool $dateArray): array { return is_array($dateArray) ? $dateArray : ['error_count' => 1]; } public static function floatOrInt(mixed $value): float|int { $result = Functions::scalar($value); return is_numeric($result) ? ($result + 0) : 0; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php ================================================ |int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * Or can be an array of adjustment values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function adjust(mixed $dateValue, array|string|bool|float|int $adjustmentMonths): DateTime|float|int|string|array { if (is_array($dateValue) || is_array($adjustmentMonths)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); } try { $dateValue = Helpers::getDateValue($dateValue, false); $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); } catch (Exception $e) { return $e->getMessage(); } $dateValue = floor($dateValue); $adjustmentMonths = floor($adjustmentMonths); // Execute function $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths); return Helpers::returnIn3FormatsObject($PHPDateObject); } /** * EOMONTH. * * Returns the date value for the last day of the month that is the indicated number of months * before or after start_date. * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. * * Excel Function: * EOMONTH(dateValue,adjustmentMonths) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * Or can be an array of adjustment values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function lastDay(mixed $dateValue, array|float|int|bool|string $adjustmentMonths): array|string|DateTime|float|int { if (is_array($dateValue) || is_array($adjustmentMonths)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); } try { $dateValue = Helpers::getDateValue($dateValue, false); $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); } catch (Exception $e) { return $e->getMessage(); } $dateValue = floor($dateValue); $adjustmentMonths = floor($adjustmentMonths); // Execute function $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths + 1); $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); return Helpers::returnIn3FormatsObject($PHPDateObject); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php ================================================ |int|string Interval between the dates * If an array of values is passed for the $startDate or $endDate arguments, then the returned result * will also be an array with matching dimensions */ public static function count(mixed $startDate, mixed $endDate, mixed ...$dateArgs): array|string|int { if (is_array($startDate) || is_array($endDate)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $startDate, $endDate, ...$dateArgs ); } try { // Retrieve the mandatory start and end date that are referenced in the function definition $sDate = Helpers::getDateValue($startDate); $eDate = Helpers::getDateValue($endDate); $startDate = min($sDate, $eDate); $endDate = max($sDate, $eDate); // Get the optional days $dateArgs = Functions::flattenArray($dateArgs); // Test any extra holiday parameters $holidayArray = []; foreach ($dateArgs as $holidayDate) { $holidayArray[] = Helpers::getDateValue($holidayDate); } } catch (Exception $e) { return $e->getMessage(); } // Execute function $startDow = self::calcStartDow($startDate); $endDow = self::calcEndDow($endDate); $wholeWeekDays = (int) floor(($endDate - $startDate) / 7) * 5; $partWeekDays = self::calcPartWeekDays($startDow, $endDow); // Test any extra holiday parameters $holidayCountedArray = []; foreach ($holidayArray as $holidayDate) { if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { if ((Week::day($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { --$partWeekDays; $holidayCountedArray[] = $holidayDate; } } } return self::applySign($wholeWeekDays + $partWeekDays, $sDate, $eDate); } private static function calcStartDow(float $startDate): int { $startDow = 6 - (int) Week::day($startDate, 2); if ($startDow < 0) { $startDow = 5; } return $startDow; } private static function calcEndDow(float $endDate): int { $endDow = (int) Week::day($endDate, 2); if ($endDow >= 6) { $endDow = 0; } return $endDow; } private static function calcPartWeekDays(int $startDow, int $endDow): int { $partWeekDays = $endDow + $startDow; if ($partWeekDays > 5) { $partWeekDays -= 5; } return $partWeekDays; } private static function applySign(int $result, float $sDate, float $eDate): int { return ($sDate > $eDate) ? -$result : $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php ================================================ |bool|float|int|string $hour A number from 0 (zero) to 32767 representing the hour. * Any value greater than 23 will be divided by 24 and the remainder * will be treated as the hour value. For example, TIME(27,0,0) = * TIME(3,0,0) = .125 or 3:00 AM. * @param null|array|bool|float|int|string $minute A number from 0 to 32767 representing the minute. * Any value greater than 59 will be converted to hours and minutes. * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. * @param null|array|bool|float|int|string $second A number from 0 to 32767 representing the second. * Any value greater than 59 will be converted to hours, minutes, * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 * or 12:33:20 AM * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromHMS(array|int|float|bool|null|string $hour, array|int|float|bool|null|string $minute, array|int|float|bool|null|string $second): array|string|float|int|DateTime { if (is_array($hour) || is_array($minute) || is_array($second)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $hour, $minute, $second); } try { $hour = self::toIntWithNullBool($hour); $minute = self::toIntWithNullBool($minute); $second = self::toIntWithNullBool($second); } catch (Exception $e) { return $e->getMessage(); } self::adjustSecond($second, $minute); self::adjustMinute($minute, $hour); if ($hour > 23) { $hour = $hour % 24; } elseif ($hour < 0) { return ExcelError::NAN(); } // Execute function $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { $calendar = SharedDateHelper::getExcelCalendar(); $date = (int) ($calendar !== SharedDateHelper::CALENDAR_WINDOWS_1900); return (float) SharedDateHelper::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); } if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { return (int) SharedDateHelper::excelToTimestamp(SharedDateHelper::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 } // RETURNDATE_PHP_DATETIME_OBJECT // Hour has already been normalized (0-23) above $phpDateObject = new DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); return $phpDateObject; } private static function adjustSecond(int &$second, int &$minute): void { if ($second < 0) { $minute += (int) floor($second / 60); $second = 60 - abs($second % 60); if ($second == 60) { $second = 0; } } elseif ($second >= 60) { $minute += intdiv($second, 60); $second = $second % 60; } } private static function adjustMinute(int &$minute, int &$hour): void { if ($minute < 0) { $hour += (int) floor($minute / 60); $minute = 60 - abs($minute % 60); if ($minute == 60) { $minute = 0; } } elseif ($minute >= 60) { $hour += intdiv($minute, 60); $minute = $minute % 60; } } /** * @param mixed $value expect int */ private static function toIntWithNullBool(mixed $value): int { $value = $value ?? 0; if (is_bool($value)) { $value = (int) $value; } if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php ================================================ |int|string Hour * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function hour(mixed $timeValue): array|string|int { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (is_string($timeValue) && !is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function try { SharedDateHelper::excelToDateTimeObject($timeValue); } catch (Throwable) { return ExcelError::NAN(); } $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); SharedDateHelper::roundMicroseconds($timeValue); return (int) $timeValue->format('H'); } /** * MINUTE. * * Returns the minutes of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * MINUTE(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Minute * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function minute(mixed $timeValue): array|string|int { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (is_string($timeValue) && !is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function try { SharedDateHelper::excelToDateTimeObject($timeValue); } catch (Throwable) { return ExcelError::NAN(); } $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); SharedDateHelper::roundMicroseconds($timeValue); return (int) $timeValue->format('i'); } /** * SECOND. * * Returns the seconds of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * SECOND(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Second * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function second(mixed $timeValue): array|string|int { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (is_string($timeValue) && !is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function try { SharedDateHelper::excelToDateTimeObject($timeValue); } catch (Throwable) { return ExcelError::NAN(); } $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); SharedDateHelper::roundMicroseconds($timeValue); return (int) $timeValue->format('s'); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php ================================================ |bool|float|int|string $timeValue A text string that represents a time in any one of the Microsoft * Excel time formats; for example, "6:45 PM" and "18:45" text strings * within quotation marks that represent time. * Date information in time_text is ignored. * Or can be an array of date/time values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromString(null|array|string|int|bool|float $timeValue): array|string|DateTime|int|float { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } // try to parse as time iff there is at least one digit if (is_string($timeValue) && !Preg::isMatch('/\d/', $timeValue)) { return ExcelError::VALUE(); } $timeValue = trim((string) $timeValue, '"'); if (Preg::isMatch(self::EXTRACT_TIME, $timeValue, $matches)) { if (empty($matches[6])) { // am/pm $hour = (int) $matches[0]; $timeValue = ($hour % 24) . $matches[2]; } elseif ($matches[6] === $matches[7]) { // Excel wants space before am/pm return ExcelError::VALUE(); } else { $timeValue = $matches[0] . 'm'; } } $PHPDateArray = Helpers::dateParse($timeValue); $retValue = ExcelError::VALUE(); if (Helpers::dateParseSucceeded($PHPDateArray)) { $hour = $PHPDateArray['hour']; $minute = $PHPDateArray['minute']; $second = $PHPDateArray['second']; // OpenOffice-specific code removed - it works just like Excel $excelDateValue = SharedDateHelper::formattedPHPToExcel(1900, 1, 1, $hour, $minute, $second) - 1; $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { $retValue = (float) $excelDateValue; } elseif ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { $retValue = (int) SharedDateHelper::excelToTimestamp($excelDateValue + 25569) - 3600; } else { $retValue = new DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); } } return $retValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php ================================================ |int $method Week begins on Sunday or Monday * 1 or omitted Week begins on Sunday. * 2 Week begins on Monday. * 11 Week begins on Monday. * 12 Week begins on Tuesday. * 13 Week begins on Wednesday. * 14 Week begins on Thursday. * 15 Week begins on Friday. * 16 Week begins on Saturday. * 17 Week begins on Sunday. * 21 ISO (Jan. 4 is week 1, begins on Monday). * Or can be an array of methods * * @return array|int|string Week Number * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function number(mixed $dateValue, array|int|string|null $method = Constants::STARTWEEK_SUNDAY): array|int|string { if (is_array($dateValue) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $method); } $origDateValueNull = empty($dateValue); try { $method = self::validateMethod($method); if ($dateValue === null) { // boolean not allowed $dateValue = (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 || $method === Constants::DOW_SUNDAY) ? 0 : 1; } $dateValue = self::validateDateValue($dateValue); if (!$dateValue && self::buggyWeekNum1900($method)) { // This seems to be an additional Excel bug. return 0; } } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); if ($method == Constants::STARTWEEK_MONDAY_ISO) { Helpers::silly1900($PHPDateObject); return (int) $PHPDateObject->format('W'); } if (self::buggyWeekNum1904($method, $origDateValueNull, $PHPDateObject)) { return 0; } Helpers::silly1900($PHPDateObject, '+ 5 years'); // 1905 calendar matches $dayOfYear = (int) $PHPDateObject->format('z'); $PHPDateObject->modify('-' . $dayOfYear . ' days'); $firstDayOfFirstWeek = (int) $PHPDateObject->format('w'); $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; $daysInFirstWeek += 7 * !$daysInFirstWeek; $endFirstWeek = $daysInFirstWeek - 1; $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); return (int) $weekOfYear; } /** * ISOWEEKNUM. * * Returns the ISO 8601 week number of the year for a specified date. * * Excel Function: * ISOWEEKNUM(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Week Number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function isoWeekNumber(mixed $dateValue): array|int|string { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } if (self::apparentBug($dateValue)) { return 52; } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); Helpers::silly1900($PHPDateObject); return (int) $PHPDateObject->format('W'); } /** * WEEKDAY. * * Returns the day of the week for a specified date. The day is given as an integer * ranging from 0 to 7 (dependent on the requested style). * * Excel Function: * WEEKDAY(dateValue[,style]) * * @param null|array|bool|float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $style A number that determines the type of return value * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). * 2 Numbers 1 (Monday) through 7 (Sunday). * 3 Numbers 0 (Monday) through 6 (Sunday). * Or can be an array of styles * * @return array|int|string Day of the week value * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function day(null|array|float|int|string|bool $dateValue, mixed $style = 1): array|string|int { if (is_array($dateValue) || is_array($style)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $style); } try { $dateValue = Helpers::getDateValue($dateValue); $style = self::validateStyle($style); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); Helpers::silly1900($PHPDateObject); $DoW = (int) $PHPDateObject->format('w'); switch ($style) { case 1: ++$DoW; break; case 2: $DoW = self::dow0Becomes7($DoW); break; case 3: $DoW = self::dow0Becomes7($DoW) - 1; break; } return $DoW; } /** * @param mixed $style expect int */ private static function validateStyle(mixed $style): int { if (!is_numeric($style)) { throw new Exception(ExcelError::VALUE()); } $style = (int) $style; if (($style < 1) || ($style > 3)) { throw new Exception(ExcelError::NAN()); } return $style; } private static function dow0Becomes7(int $DoW): int { return ($DoW === 0) ? 7 : $DoW; } /** * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string */ private static function apparentBug(mixed $dateValue): bool { if (SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { if (is_bool($dateValue)) { return true; } if (is_numeric($dateValue) && !((int) $dateValue)) { return true; } } return false; } /** * Validate dateValue parameter. */ private static function validateDateValue(mixed $dateValue): float { if (is_bool($dateValue)) { throw new Exception(ExcelError::VALUE()); } return Helpers::getDateValue($dateValue); } /** * Validate method parameter. */ private static function validateMethod(mixed $method): int { if ($method === null) { $method = Constants::STARTWEEK_SUNDAY; } if (!is_numeric($method)) { throw new Exception(ExcelError::VALUE()); } $method = (int) $method; if (!array_key_exists($method, Constants::METHODARR)) { throw new Exception(ExcelError::NAN()); } $method = Constants::METHODARR[$method]; return $method; } private static function buggyWeekNum1900(int $method): bool { return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900; } private static function buggyWeekNum1904(int $method, bool $origNull, DateTime $dateObject): bool { // This appears to be another Excel bug. return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 && !$origNull && $dateObject->format('Y-m-d') === '1904-01-01'; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php ================================================ |mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $endDays The number of nonweekend and nonholiday days before or after * startDate. A positive value for days yields a future date; a * negative value yields a past date. * Or can be an array of int values * @param null|mixed $dateArgs An array of dates (such as holidays) to exclude from the calculation * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function date(mixed $startDate, array|int|string $endDays, mixed ...$dateArgs): array|float|int|DateTime|string { if (is_array($startDate) || is_array($endDays)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $startDate, $endDays, ...$dateArgs ); } // Retrieve the mandatory start date and days that are referenced in the function definition try { $startDate = Helpers::getDateValue($startDate); $endDays = Helpers::validateNumericNull($endDays); $holidayArray = array_map([Helpers::class, 'getDateValue'], Functions::flattenArray($dateArgs)); } catch (Exception $e) { return $e->getMessage(); } $startDate = (float) floor($startDate); $endDays = (int) floor($endDays); // If endDays is 0, we always return startDate if ($endDays == 0) { return $startDate; } if ($endDays < 0) { return self::decrementing($startDate, $endDays, $holidayArray); } return self::incrementing($startDate, $endDays, $holidayArray); } /** * Use incrementing logic to determine Workday. * * @param array $holidayArray */ private static function incrementing(float $startDate, int $endDays, array $holidayArray): float|int|DateTime { // Adjust the start date if it falls over a weekend $startDoW = self::getWeekDay($startDate, 3); if ($startDoW >= 5) { $startDate += 7 - $startDoW; --$endDays; } // Add endDays $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); $endDays = $endDays % 5; while ($endDays > 0) { ++$endDate; // Adjust the calculated end date if it falls over a weekend $endDow = self::getWeekDay($endDate, 3); if ($endDow >= 5) { $endDate += 7 - $endDow; } --$endDays; } // Test any extra holiday parameters if (!empty($holidayArray)) { $endDate = self::incrementingArray($startDate, $endDate, $holidayArray); } return Helpers::returnIn3FormatsFloat($endDate); } /** @param array $holidayArray */ private static function incrementingArray(float $startDate, float $endDate, array $holidayArray): float { $holidayCountedArray = $holidayDates = []; foreach ($holidayArray as $holidayDate) { /** @var float $holidayDate */ if (self::getWeekDay($holidayDate, 3) < 5) { $holidayDates[] = $holidayDate; } } sort($holidayDates, SORT_NUMERIC); foreach ($holidayDates as $holidayDate) { if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { if (!in_array($holidayDate, $holidayCountedArray)) { ++$endDate; $holidayCountedArray[] = $holidayDate; } } // Adjust the calculated end date if it falls over a weekend $endDoW = self::getWeekDay($endDate, 3); if ($endDoW >= 5) { $endDate += 7 - $endDoW; } } return $endDate; } /** * Use decrementing logic to determine Workday. * * @param array $holidayArray */ private static function decrementing(float $startDate, int $endDays, array $holidayArray): float|int|DateTime { // Adjust the start date if it falls over a weekend $startDoW = self::getWeekDay($startDate, 3); if ($startDoW >= 5) { $startDate += -$startDoW + 4; ++$endDays; } // Add endDays $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); $endDays = $endDays % 5; while ($endDays < 0) { --$endDate; // Adjust the calculated end date if it falls over a weekend $endDow = self::getWeekDay($endDate, 3); if ($endDow >= 5) { $endDate += 4 - $endDow; } ++$endDays; } // Test any extra holiday parameters if (!empty($holidayArray)) { $endDate = self::decrementingArray($startDate, $endDate, $holidayArray); } return Helpers::returnIn3FormatsFloat($endDate); } /** @param array $holidayArray */ private static function decrementingArray(float $startDate, float $endDate, array $holidayArray): float { $holidayCountedArray = $holidayDates = []; foreach ($holidayArray as $holidayDate) { /** @var float $holidayDate */ if (self::getWeekDay($holidayDate, 3) < 5) { $holidayDates[] = $holidayDate; } } rsort($holidayDates, SORT_NUMERIC); foreach ($holidayDates as $holidayDate) { if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { if (!in_array($holidayDate, $holidayCountedArray)) { --$endDate; $holidayCountedArray[] = $holidayDate; } } // Adjust the calculated end date if it falls over a weekend $endDoW = self::getWeekDay($endDate, 3); /** int $endDoW */ if ($endDoW >= 5) { $endDate += -$endDoW + 4; } } return $endDate; } private static function getWeekDay(float $date, int $wd): int { $result = Functions::scalar(Week::day($date, $wd)); return is_int($result) ? $result : -1; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php ================================================ |int $method Method used for the calculation * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * Or can be an array of methods * * @return array|float|int|string fraction of the year, or a string containing an error * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function fraction(mixed $startDate, mixed $endDate, array|int|string|null $method = 0): array|string|int|float { if (is_array($startDate) || is_array($endDate) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $method); } try { $method = (int) Helpers::validateNumericNull($method); $sDate = Helpers::getDateValue($startDate); $eDate = Helpers::getDateValue($endDate); $sDate = self::excelBug($sDate, $startDate, $endDate, $method); $eDate = self::excelBug($eDate, $endDate, $startDate, $method); $startDate = min($sDate, $eDate); $endDate = max($sDate, $eDate); } catch (Exception $e) { return $e->getMessage(); } return match ($method) { 0 => Helpers::floatOrInt(Days360::between($startDate, $endDate)) / 360, 1 => self::method1($startDate, $endDate), 2 => Helpers::floatOrInt(Difference::interval($startDate, $endDate)) / 360, 3 => Helpers::floatOrInt(Difference::interval($startDate, $endDate)) / 365, 4 => Helpers::floatOrInt(Days360::between($startDate, $endDate, true)) / 360, default => ExcelError::NAN(), }; } /** * Excel 1900 calendar treats date argument of null as 1900-01-00. Really. */ private static function excelBug(float $sDate, mixed $startDate, mixed $endDate, int $method): float { if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE && SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { if ($endDate === null && $startDate !== null) { if (DateParts::month($sDate) == 12 && DateParts::day($sDate) === 31 && $method === 0) { $sDate += 2; } else { ++$sDate; } } } return $sDate; } private static function method1(float $startDate, float $endDate): float { $days = Helpers::floatOrInt(Difference::interval($startDate, $endDate)); $startYear = (int) DateParts::year($startDate); $endYear = (int) DateParts::year($endDate); $years = $endYear - $startYear + 1; $startMonth = (int) DateParts::month($startDate); $startDay = (int) DateParts::day($startDate); $endMonth = (int) DateParts::month($endDate); $endDay = (int) DateParts::day($endDate); $startMonthDay = 100 * $startMonth + $startDay; $endMonthDay = 100 * $endMonth + $endDay; if ($years == 1) { $tmpCalcAnnualBasis = 365 + (int) Helpers::isLeapYear($endYear); } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { if (Helpers::isLeapYear($startYear)) { $tmpCalcAnnualBasis = 365 + (int) ($startMonthDay <= 229); } elseif (Helpers::isLeapYear($endYear)) { $tmpCalcAnnualBasis = 365 + (int) ($endMonthDay >= 229); } else { $tmpCalcAnnualBasis = 365; } } else { $tmpCalcAnnualBasis = 0; for ($year = $startYear; $year <= $endYear; ++$year) { $tmpCalcAnnualBasis += 365 + (int) Helpers::isLeapYear($year); } $tmpCalcAnnualBasis /= $years; } return $days / $tmpCalcAnnualBasis; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentHelper.php ================================================ indexStart = (int) array_shift($keys); $this->rows = $this->rows($arguments); $this->columns = $this->columns($arguments); $this->argumentCount = count($arguments); $this->arguments = $this->flattenSingleCellArrays($arguments, $this->rows, $this->columns); $this->rows = $this->rows($arguments); $this->columns = $this->columns($arguments); if ($this->arrayArguments() > 2) { throw new Exception('Formulae with more than two array arguments are not supported'); } } /** @return mixed[] */ public function arguments(): array { return $this->arguments; } public function hasArrayArgument(): bool { return $this->arrayArguments() > 0; } public function getFirstArrayArgumentNumber(): int { $rowArrays = $this->filterArray($this->rows); $columnArrays = $this->filterArray($this->columns); for ($index = $this->indexStart; $index < $this->argumentCount; ++$index) { if (isset($rowArrays[$index]) || isset($columnArrays[$index])) { return ++$index; } } return 0; } public function getSingleRowVector(): ?int { $rowVectors = $this->getRowVectors(); return count($rowVectors) === 1 ? array_pop($rowVectors) : null; } /** @return int[] */ private function getRowVectors(): array { $rowVectors = []; for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { if ($this->rows[$index] === 1 && $this->columns[$index] > 1) { $rowVectors[] = $index; } } return $rowVectors; } public function getSingleColumnVector(): ?int { $columnVectors = $this->getColumnVectors(); return count($columnVectors) === 1 ? array_pop($columnVectors) : null; } /** @return int[] */ private function getColumnVectors(): array { $columnVectors = []; for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { if ($this->rows[$index] > 1 && $this->columns[$index] === 1) { $columnVectors[] = $index; } } return $columnVectors; } /** @return int[] */ public function getMatrixPair(): array { for ($i = $this->indexStart; $i < ($this->indexStart + $this->argumentCount - 1); ++$i) { for ($j = $i + 1; $j < $this->argumentCount; ++$j) { if (isset($this->rows[$i], $this->rows[$j])) { return [$i, $j]; } } } return []; } public function isVector(int $argument): bool { return $this->rows[$argument] === 1 || $this->columns[$argument] === 1; } public function isRowVector(int $argument): bool { return $this->rows[$argument] === 1; } public function isColumnVector(int $argument): bool { return $this->columns[$argument] === 1; } public function rowCount(int $argument): int { return $this->rows[$argument]; } public function columnCount(int $argument): int { return $this->columns[$argument]; } /** * @param mixed[] $arguments * * @return int[] */ private function rows(array $arguments): array { return array_map( fn ($argument): int => is_countable($argument) ? count($argument) : 1, $arguments ); } /** * @param mixed[] $arguments * * @return int[] */ private function columns(array $arguments): array { return array_map( fn (mixed $argument): int => is_array($argument) && is_array($argument[array_keys($argument)[0]]) ? count($argument[array_keys($argument)[0]]) : 1, $arguments ); } public function arrayArguments(): int { $count = 0; foreach (array_keys($this->arguments) as $argument) { if ($this->rows[$argument] > 1 || $this->columns[$argument] > 1) { ++$count; } } return $count; } /** * @param mixed[] $arguments * @param int[] $rows * @param int[] $columns * * @return mixed[] */ private function flattenSingleCellArrays(array $arguments, array $rows, array $columns): array { foreach ($arguments as $index => $argument) { if ($rows[$index] === 1 && $columns[$index] === 1) { while (is_array($argument)) { $argument = array_pop($argument); } $arguments[$index] = $argument; } } return $arguments; } /** * @param mixed[] $array * * @return mixed[] */ private function filterArray(array $array): array { return array_filter( $array, fn ($value): bool => $value > 1 ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentProcessor.php ================================================ hasArrayArgument() === false) { return [$method(...$arguments)]; } if (self::$arrayArgumentHelper->arrayArguments() === 1) { $nthArgument = self::$arrayArgumentHelper->getFirstArrayArgumentNumber(); return self::evaluateNthArgumentAsArray($method, $nthArgument, ...$arguments); } $singleRowVectorIndex = self::$arrayArgumentHelper->getSingleRowVector(); $singleColumnVectorIndex = self::$arrayArgumentHelper->getSingleColumnVector(); if ($singleRowVectorIndex !== null && $singleColumnVectorIndex !== null) { // Basic logic for a single row vector and a single column vector return self::evaluateVectorPair($method, $singleRowVectorIndex, $singleColumnVectorIndex, ...$arguments); } $matrixPair = self::$arrayArgumentHelper->getMatrixPair(); if ($matrixPair !== []) { if ( (self::$arrayArgumentHelper->isVector($matrixPair[0]) === true && self::$arrayArgumentHelper->isVector($matrixPair[1]) === false) || (self::$arrayArgumentHelper->isVector($matrixPair[0]) === false && self::$arrayArgumentHelper->isVector($matrixPair[1]) === true) ) { // Logic for a matrix and a vector (row or column) return self::evaluateVectorMatrixPair($method, $matrixPair, ...$arguments); } // Logic for matrix/matrix, column vector/column vector or row vector/row vector return self::evaluateMatrixPair($method, $matrixPair, ...$arguments); } // Still need to work out the logic for more than two array arguments, // For the moment, we're throwing an Exception when we initialise the ArrayArgumentHelper return ['#VALUE!']; } /** * @param int[] $matrixIndexes * * @return mixed[] */ private static function evaluateVectorMatrixPair(callable $method, array $matrixIndexes, mixed ...$arguments): array { $matrix2 = array_pop($matrixIndexes) ?? throw new Exception('empty array 2'); /** @var mixed[][] $matrixValues2 */ $matrixValues2 = $arguments[$matrix2]; $matrix1 = array_pop($matrixIndexes) ?? throw new Exception('empty array 1'); /** @var mixed[][] $matrixValues1 */ $matrixValues1 = $arguments[$matrix1]; /** @var non-empty-array */ $matrix12 = [$matrix1, $matrix2]; $rows = min(array_map(self::$arrayArgumentHelper->rowCount(...), $matrix12)); $columns = min(array_map(self::$arrayArgumentHelper->columnCount(...), $matrix12)); if ($rows === 1) { $rows = max(array_map(self::$arrayArgumentHelper->rowCount(...), $matrix12)); } if ($columns === 1) { $columns = max(array_map(self::$arrayArgumentHelper->columnCount(...), $matrix12)); } $result = []; for ($rowIndex = 0; $rowIndex < $rows; ++$rowIndex) { for ($columnIndex = 0; $columnIndex < $columns; ++$columnIndex) { $rowIndex1 = self::$arrayArgumentHelper->isRowVector($matrix1) ? 0 : $rowIndex; $columnIndex1 = self::$arrayArgumentHelper->isColumnVector($matrix1) ? 0 : $columnIndex; $value1 = $matrixValues1[$rowIndex1][$columnIndex1]; $rowIndex2 = self::$arrayArgumentHelper->isRowVector($matrix2) ? 0 : $rowIndex; $columnIndex2 = self::$arrayArgumentHelper->isColumnVector($matrix2) ? 0 : $columnIndex; $value2 = $matrixValues2[$rowIndex2][$columnIndex2]; $arguments[$matrix1] = $value1; $arguments[$matrix2] = $value2; $result[$rowIndex][$columnIndex] = $method(...$arguments); } } return $result; } /** * @param array $matrixIndexes * * @return mixed[] */ private static function evaluateMatrixPair(callable $method, array $matrixIndexes, mixed ...$arguments): array { $matrix2 = array_pop($matrixIndexes); /** @var mixed[][] $matrixValues2 */ $matrixValues2 = $arguments[$matrix2]; $matrix1 = array_pop($matrixIndexes); /** @var mixed[][] $matrixValues1 */ $matrixValues1 = $arguments[$matrix1]; $result = []; foreach ($matrixValues1 as $rowIndex => $row) { foreach ($row as $columnIndex => $value1) { if (isset($matrixValues2[$rowIndex][$columnIndex]) === false) { continue; } $value2 = $matrixValues2[$rowIndex][$columnIndex]; $arguments[$matrix1] = $value1; $arguments[$matrix2] = $value2; $result[$rowIndex][$columnIndex] = $method(...$arguments); } } return $result; } /** @return mixed[] */ private static function evaluateVectorPair(callable $method, int $rowIndex, int $columnIndex, mixed ...$arguments): array { $rowVector = Functions::flattenArray($arguments[$rowIndex]); $columnVector = Functions::flattenArray($arguments[$columnIndex]); $result = []; foreach ($columnVector as $column) { $rowResults = []; foreach ($rowVector as $row) { $arguments[$rowIndex] = $row; $arguments[$columnIndex] = $column; $rowResults[] = $method(...$arguments); } $result[] = $rowResults; } return $result; } /** * Note, offset is from 1 (for the first argument) rather than from 0. * * @return mixed[] */ private static function evaluateNthArgumentAsArray(callable $method, int $nthArgument, mixed ...$arguments): array { $values = array_slice($arguments, $nthArgument - 1, 1); /** @var mixed[] $values */ $values = array_pop($values); $result = []; foreach ($values as $value) { $arguments[$nthArgument - 1] = $value; $result[] = $method(...$arguments); } return $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php ================================================ branchPruningEnabled = $branchPruningEnabled; } public function clearBranchStore(): void { $this->branchStoreKeyCounter = 0; } public function initialiseForLoop(): void { $this->currentCondition = null; $this->currentOnlyIf = null; $this->currentOnlyIfNot = null; $this->previousStoreKey = null; $this->pendingStoreKey = empty($this->storeKeysStack) ? null : end($this->storeKeysStack); if ($this->branchPruningEnabled) { $this->initialiseCondition(); $this->initialiseThen(); $this->initialiseElse(); } } private function initialiseCondition(): void { if (isset($this->pendingStoreKey, $this->conditionMap[$this->pendingStoreKey]) && $this->conditionMap[$this->pendingStoreKey]) { $this->currentCondition = $this->pendingStoreKey; $stackDepth = count($this->storeKeysStack); if ($stackDepth > 1) { // nested if $this->previousStoreKey = $this->storeKeysStack[$stackDepth - 2]; } } } private function initialiseThen(): void { if (isset($this->pendingStoreKey, $this->thenMap[$this->pendingStoreKey]) && $this->thenMap[$this->pendingStoreKey]) { $this->currentOnlyIf = $this->pendingStoreKey; } elseif ( isset($this->previousStoreKey, $this->thenMap[$this->previousStoreKey]) && $this->thenMap[$this->previousStoreKey] ) { $this->currentOnlyIf = $this->previousStoreKey; } } private function initialiseElse(): void { if (isset($this->pendingStoreKey, $this->elseMap[$this->pendingStoreKey]) && $this->elseMap[$this->pendingStoreKey]) { $this->currentOnlyIfNot = $this->pendingStoreKey; } elseif ( isset($this->previousStoreKey, $this->elseMap[$this->previousStoreKey]) && $this->elseMap[$this->previousStoreKey] ) { $this->currentOnlyIfNot = $this->previousStoreKey; } } public function decrementDepth(): void { if (!empty($this->pendingStoreKey)) { --$this->braceDepthMap[$this->pendingStoreKey]; } } public function incrementDepth(): void { if (!empty($this->pendingStoreKey)) { ++$this->braceDepthMap[$this->pendingStoreKey]; } } public function functionCall(string $functionName): void { if ($this->branchPruningEnabled && ($functionName === 'IF(')) { // we handle a new if $this->pendingStoreKey = $this->getUnusedBranchStoreKey(); $this->storeKeysStack[] = $this->pendingStoreKey; $this->conditionMap[$this->pendingStoreKey] = true; $this->braceDepthMap[$this->pendingStoreKey] = 0; } elseif (!empty($this->pendingStoreKey) && array_key_exists($this->pendingStoreKey, $this->braceDepthMap)) { // this is not an if but we go deeper ++$this->braceDepthMap[$this->pendingStoreKey]; } } public function argumentSeparator(): void { if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === 0) { // We must go to the IF next argument if ($this->conditionMap[$this->pendingStoreKey]) { $this->conditionMap[$this->pendingStoreKey] = false; $this->thenMap[$this->pendingStoreKey] = true; } elseif ($this->thenMap[$this->pendingStoreKey]) { $this->thenMap[$this->pendingStoreKey] = false; $this->elseMap[$this->pendingStoreKey] = true; } elseif ($this->elseMap[$this->pendingStoreKey]) { throw new Exception('Reaching fourth argument of an IF'); } } } public function closingBrace(mixed $value): void { if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === -1) { // we are closing an IF( if ($value !== 'IF(') { throw new Exception('Parser bug we should be in an "IF("'); } if ($this->conditionMap[$this->pendingStoreKey]) { throw new Exception('We should not be expecting a condition'); } $this->thenMap[$this->pendingStoreKey] = false; $this->elseMap[$this->pendingStoreKey] = false; --$this->braceDepthMap[$this->pendingStoreKey]; array_pop($this->storeKeysStack); $this->pendingStoreKey = null; } } public function currentCondition(): ?string { return $this->currentCondition; } public function currentOnlyIf(): ?string { return $this->currentOnlyIf; } public function currentOnlyIfNot(): ?string { return $this->currentOnlyIfNot; } private function getUnusedBranchStoreKey(): string { $storeKeyValue = 'storeKey-' . $this->branchStoreKeyCounter; ++$this->branchStoreKeyCounter; return $storeKeyValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php ================================================ stack); } /** * Push a new entry onto the stack. * * @param int|string $value The value to test */ public function push($value): void { $this->stack[$value] = $value; } /** * Pop the last entry from the stack. */ public function pop(): mixed { return array_pop($this->stack); } /** * Test to see if a specified entry exists on the stack. * * @param int|string $value The value to test */ public function onStack($value): bool { return isset($this->stack[$value]); } /** * Clear the stack. */ public function clear(): void { $this->stack = []; } /** * Return an array of all entries on the stack. * * @return mixed[] */ public function showStack(): array { return $this->stack; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php ================================================ [-+])? *\% *(?[-+])? *(?[0-9]+\.?[0-9*]*(?:E[-+]?[0-9]*)?) *)|(?: *(?[-+])? *(?[0-9]+\.?[0-9]*(?:E[-+]?[0-9]*)?) *\% *))$~i'; // preg_quoted string for major currency symbols, with a %s for locale currency private const CURRENCY_CONVERSION_LIST = '\$€£¥%s'; /** * Identify whether a string contains a formatted numeric value, * and convert it to a numeric if it is. * * @param float|string $operand string value to test */ public static function convertToNumberIfFormatted(float|string &$operand): bool { return self::convertToNumberIfNumeric($operand) || self::convertToNumberIfFraction($operand) || self::convertToNumberIfPercent($operand) || self::convertToNumberIfCurrency($operand); } /** * Identify whether a string contains a numeric value, * and convert it to a numeric if it is. * * @param float|string $operand string value to test */ public static function convertToNumberIfNumeric(float|string &$operand): bool { $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace(['/(\d)' . $thousandsSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1$2', '$1$2'], trim("$operand")); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); $value = preg_replace(['/(\d)' . $decimalSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1.$2', '$1$2'], $value ?? ''); if (is_numeric($value)) { $operand = (float) $value; return true; } return false; } /** * Identify whether a string contains a fractional numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfFraction(float|string &$operand): bool { if (is_string($operand) && preg_match(self::STRING_REGEXP_FRACTION, $operand, $match)) { $sign = ($match[1] === '-') ? '-' : '+'; $wholePart = ($match[3] === '') ? '' : ($sign . $match[3]); $fractionFormula = '=' . $wholePart . $sign . $match[4]; /** @var string */ $operandx = Calculation::getInstance()->_calculateFormulaValue($fractionFormula); $operand = $operandx; return true; } return false; } /** * Identify whether a string contains a percentage, and if so, * convert it to a numeric. * * @param float|string $operand string value to test */ public static function convertToNumberIfPercent(float|string &$operand): bool { $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', trim("$operand")); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); $value = preg_replace(['/(\d)' . $decimalSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1.$2', '$1$2'], $value ?? ''); $match = []; if ($value !== null && preg_match(self::STRING_REGEXP_PERCENT, $value, $match, PREG_UNMATCHED_AS_NULL)) { //Calculate the percentage $sign = ($match['PrefixedSign'] ?? $match['PrefixedSign2'] ?? $match['PostfixedSign']) ?? ''; $operand = (float) ($sign . ($match['PostfixedValue'] ?? $match['PrefixedValue'])) / 100; return true; } return false; } /** * Identify whether a string contains a currency value, and if so, * convert it to a numeric. * * @param float|string $operand string value to test */ public static function convertToNumberIfCurrency(float|string &$operand): bool { $currencyRegexp = self::currencyMatcherRegexp(); $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', "$operand"); $match = []; if ($value !== null && preg_match($currencyRegexp, $value, $match, PREG_UNMATCHED_AS_NULL)) { //Determine the sign $sign = ($match['PrefixedSign'] ?? $match['PrefixedSign2'] ?? $match['PostfixedSign']) ?? ''; $decimalSeparator = StringHelper::getDecimalSeparator(); //Cast to a float $intermediate = (string) ($match['PostfixedValue'] ?? $match['PrefixedValue']); $intermediate = str_replace($decimalSeparator, '.', $intermediate); if (is_numeric($intermediate)) { $operand = (float) ($sign . str_replace($decimalSeparator, '.', $intermediate)); return true; } } return false; } public static function currencyMatcherRegexp(): string { $currencyCodes = sprintf(self::CURRENCY_CONVERSION_LIST, preg_quote(StringHelper::getCurrencyCode(), '/')); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); return '~^(?:(?: *(?[-+])? *(?[' . $currencyCodes . ']) *(?[-+])? *(?[0-9]+[' . $decimalSeparator . ']?[0-9*]*(?:E[-+]?[0-9]*)?) *)|(?: *(?[-+])? *(?[0-9]+' . $decimalSeparator . '?[0-9]*(?:E[-+]?[0-9]*)?) *(?[' . $currencyCodes . ']) *))$~ui'; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/Logger.php ================================================ cellStack = $stack; } /** * Enable/Disable Calculation engine logging. */ public function setWriteDebugLog(bool $writeDebugLog): void { $this->writeDebugLog = $writeDebugLog; } /** * Return whether calculation engine logging is enabled or disabled. */ public function getWriteDebugLog(): bool { return $this->writeDebugLog; } /** * Enable/Disable echoing of debug log information. */ public function setEchoDebugLog(bool $echoDebugLog): void { $this->echoDebugLog = $echoDebugLog; } /** * Return whether echoing of debug log information is enabled or disabled. */ public function getEchoDebugLog(): bool { return $this->echoDebugLog; } /** * Write an entry to the calculation engine debug log. */ public function writeDebugLog(string $message, mixed ...$args): void { // Only write the debug log if logging is enabled if ($this->writeDebugLog) { $message = sprintf($message, ...$args); //* @phpstan-ignore-line $cellReference = implode(' -> ', $this->cellStack->showStack()); if ($this->echoDebugLog) { echo $cellReference, ($this->cellStack->count() > 0 ? ' => ' : ''), $message, PHP_EOL; } $this->debugLog[] = $cellReference . ($this->cellStack->count() > 0 ? ' => ' : '') . $message; } } /** * Write a series of entries to the calculation engine debug log. * * @param string[] $args */ public function mergeDebugLog(array $args): void { if ($this->writeDebugLog) { foreach ($args as $entry) { $this->writeDebugLog($entry); } } } /** * Clear the calculation engine debug log. */ public function clearLog(): void { $this->debugLog = []; } /** * Return the calculation engine debug log. * * @return string[] */ public function getLog(): array { return $this->debugLog; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engine/Operands/Operand.php ================================================ value = $structuredReference; } /** @param string[] $matches */ public static function fromParser(string $formula, int $index, array $matches): self { $val = $matches[0]; $srCount = substr_count($val, self::OPEN_BRACE) - substr_count($val, self::CLOSE_BRACE); while ($srCount > 0) { $srIndex = strlen($val); $srStringRemainder = substr($formula, $index + $srIndex); $closingPos = strpos($srStringRemainder, self::CLOSE_BRACE); if ($closingPos === false) { throw new Exception("Formula Error: No closing ']' to match opening '['"); } $srStringRemainder = substr($srStringRemainder, 0, $closingPos + 1); --$srCount; if (str_contains($srStringRemainder, self::OPEN_BRACE)) { ++$srCount; } $val .= $srStringRemainder; } return new self($val); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ public function parse(Cell $cell): string { $this->getTableStructure($cell); $cellRange = ($this->isRowReference()) ? $this->getRowReference($cell) : $this->getColumnReference(); $sheetName = ''; $worksheet = $this->table->getWorksheet(); if ($worksheet !== null && $worksheet !== $cell->getWorksheet()) { $sheetName = "'" . $worksheet->getTitle() . "'!"; } return $sheetName . $cellRange; } private function isRowReference(): bool { return str_contains($this->value, '[@') || str_contains($this->value, '[' . self::ITEM_SPECIFIER_THIS_ROW . ']'); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableStructure(Cell $cell): void { preg_match(self::TABLE_REFERENCE, $this->value, $matches); $this->tableName = $matches[1]; $this->table = ($this->tableName === '') ? $this->getTableForCell($cell) : $this->getTableByName($cell); $this->reference = $matches[2]; $tableRange = Coordinate::getRangeBoundaries($this->table->getRange()); $this->headersRow = ($this->table->getShowHeaderRow()) ? (int) $tableRange[0][1] : null; $this->firstDataRow = ($this->table->getShowHeaderRow()) ? (int) $tableRange[0][1] + 1 : $tableRange[0][1]; $this->totalsRow = ($this->table->getShowTotalsRow()) ? (int) $tableRange[1][1] : null; $this->lastDataRow = ($this->table->getShowTotalsRow()) ? (int) $tableRange[1][1] - 1 : $tableRange[1][1]; $cellParam = $cell; $worksheet = $this->table->getWorksheet(); if ($worksheet !== null && $worksheet !== $cell->getWorksheet()) { $cellParam = $worksheet->getCell('A1'); } $this->columns = $this->getColumns($cellParam, $tableRange); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableForCell(Cell $cell): Table { $tables = $cell->getWorksheet()->getTableCollection(); foreach ($tables as $table) { /** @var Table $table */ $range = $table->getRange(); if ($cell->isInRange($range) === true) { $this->tableName = $table->getName(); return $table; } } throw new Exception('Table for Structured Reference cannot be identified'); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableByName(Cell $cell): Table { $table = $cell->getWorksheet()->getTableByName($this->tableName); if ($table === null) { $spreadsheet = $cell->getWorksheet()->getParent(); if ($spreadsheet !== null) { $table = $spreadsheet->getTableByName($this->tableName); } } if ($table === null) { throw new Exception("Table {$this->tableName} for Structured Reference cannot be located"); } return $table; } /** * @param array{array{string, int}, array{string, int}} $tableRange * * @return mixed[] */ private function getColumns(Cell $cell, array $tableRange): array { $worksheet = $cell->getWorksheet(); $cellReference = $cell->getCoordinate(); $columns = []; $lastColumn = StringHelper::stringIncrement($tableRange[1][0]); for ($column = $tableRange[0][0]; $column !== $lastColumn; StringHelper::stringIncrement($column)) { /** @var string $column */ $columns[$column] = $worksheet ->getCell($column . ($this->headersRow ?? ($this->firstDataRow - 1))) ->getCalculatedValue(); } $worksheet->getCell($cellReference); return $columns; } private function getRowReference(Cell $cell): string { $reference = str_replace("\u{a0}", ' ', $this->reference); /** @var string $reference */ $reference = str_replace('[' . self::ITEM_SPECIFIER_THIS_ROW . '],', '', $reference); foreach ($this->columns as $columnId => $columnName) { $columnName = str_replace("\u{a0}", ' ', $columnName); //* @phpstan-ignore-line $reference = $this->adjustRowReference($columnName, $reference, $cell, $columnId); } return $this->validateParsedReference(trim($reference, '[]@, ')); } private function adjustRowReference(string $columnName, string $reference, Cell $cell, string $columnId): string { if ($columnName !== '') { $cellReference = $columnId . $cell->getRow(); $pattern1 = '/\[' . preg_quote($columnName, '/') . '\]/miu'; $pattern2 = '/@' . preg_quote($columnName, '/') . '/miu'; if (preg_match($pattern1, $reference) === 1) { $reference = preg_replace($pattern1, $cellReference, $reference); } elseif (preg_match($pattern2, $reference) === 1) { $reference = preg_replace($pattern2, $cellReference, $reference); } /** @var string $reference */ } return $reference; } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getColumnReference(): string { $reference = str_replace("\u{a0}", ' ', $this->reference); $startRow = ($this->totalsRow === null) ? $this->lastDataRow : $this->totalsRow; $endRow = ($this->headersRow === null) ? $this->firstDataRow : $this->headersRow; [$startRow, $endRow] = $this->getRowsForColumnReference($reference, $startRow, $endRow); $reference = $this->getColumnsForColumnReference($reference, $startRow, $endRow); $reference = trim($reference, '[]@, '); if (substr_count($reference, ':') > 1) { $cells = explode(':', $reference); $firstCell = array_shift($cells); $lastCell = array_pop($cells); $reference = "{$firstCell}:{$lastCell}"; } return $this->validateParsedReference($reference); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function validateParsedReference(string $reference): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . ':' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $reference) !== 1) { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $reference) !== 1) { throw new Exception( "Invalid Structured Reference {$this->reference} {$reference}", Exception::CALCULATION_ENGINE_PUSH_TO_STACK ); } } return $reference; } private function fullData(int $startRow, int $endRow): string { $columns = array_keys($this->columns); $firstColumn = array_shift($columns); $lastColumn = (empty($columns)) ? $firstColumn : array_pop($columns); return "{$firstColumn}{$startRow}:{$lastColumn}{$endRow}"; } private function getMinimumRow(string $reference): int { return match ($reference) { self::ITEM_SPECIFIER_ALL, self::ITEM_SPECIFIER_HEADERS => $this->headersRow ?? $this->firstDataRow, self::ITEM_SPECIFIER_DATA => $this->firstDataRow, self::ITEM_SPECIFIER_TOTALS => $this->totalsRow ?? $this->lastDataRow, default => $this->headersRow ?? $this->firstDataRow, }; } private function getMaximumRow(string $reference): int { return match ($reference) { self::ITEM_SPECIFIER_HEADERS => $this->headersRow ?? $this->firstDataRow, self::ITEM_SPECIFIER_DATA => $this->lastDataRow, self::ITEM_SPECIFIER_ALL, self::ITEM_SPECIFIER_TOTALS => $this->totalsRow ?? $this->lastDataRow, default => $this->totalsRow ?? $this->lastDataRow, }; } public function value(): string { return $this->value; } /** * @return array */ private function getRowsForColumnReference(string &$reference, int $startRow, int $endRow): array { $rowsSelected = false; foreach (self::ITEM_SPECIFIER_ROWS_SET as $rowReference) { $pattern = '/\[' . $rowReference . '\]/mui'; if (preg_match($pattern, $reference) === 1) { if (($rowReference === self::ITEM_SPECIFIER_HEADERS) && ($this->table->getShowHeaderRow() === false)) { throw new Exception( 'Table Headers are Hidden, and should not be Referenced', Exception::CALCULATION_ENGINE_PUSH_TO_STACK ); } $rowsSelected = true; $startRow = min($startRow, $this->getMinimumRow($rowReference)); $endRow = max($endRow, $this->getMaximumRow($rowReference)); $reference = preg_replace($pattern, '', $reference) ?? ''; } } if ($rowsSelected === false) { // If there isn't any Special Item Identifier specified, then the selection defaults to data rows only. $startRow = $this->firstDataRow; $endRow = $this->lastDataRow; } return [$startRow, $endRow]; } private function getColumnsForColumnReference(string $reference, int $startRow, int $endRow): string { $columnsSelected = false; foreach ($this->columns as $columnId => $columnName) { $columnName = str_replace("\u{a0}", ' ', $columnName ?? ''); //* @phpstan-ignore-line $cellFrom = "{$columnId}{$startRow}"; $cellTo = "{$columnId}{$endRow}"; $cellReference = ($cellFrom === $cellTo) ? $cellFrom : "{$cellFrom}:{$cellTo}"; $pattern = '/\[' . preg_quote($columnName, '/') . '\]/mui'; if (preg_match($pattern, $reference) === 1) { $columnsSelected = true; $reference = preg_replace($pattern, $cellReference, $reference); } /** @var string $reference */ } if ($columnsSelected === false) { return $this->fullData($startRow, $endRow); } return $reference; } public function __toString(): string { return $this->value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/BesselI.php ================================================ |float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELI(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if ($ord < 0) { return ExcelError::NAN(); } $fResult = self::calculate($x, $ord); return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselI0($x), 1 => self::besselI1($x), default => self::besselI2($x, $ord), }; } private static function besselI0(float $x): float { $ax = abs($x); if ($ax < 3.75) { $y = $x / 3.75; $y = $y * $y; return 1.0 + $y * (3.5156229 + $y * (3.0899424 + $y * (1.2067492 + $y * (0.2659732 + $y * (0.360768e-1 + $y * 0.45813e-2))))); } $y = 3.75 / $ax; return (exp($ax) / sqrt($ax)) * (0.39894228 + $y * (0.1328592e-1 + $y * (0.225319e-2 + $y * (-0.157565e-2 + $y * (0.916281e-2 + $y * (-0.2057706e-1 + $y * (0.2635537e-1 + $y * (-0.1647633e-1 + $y * 0.392377e-2)))))))); } private static function besselI1(float $x): float { $ax = abs($x); if ($ax < 3.75) { $y = $x / 3.75; $y = $y * $y; $ans = $ax * (0.5 + $y * (0.87890594 + $y * (0.51498869 + $y * (0.15084934 + $y * (0.2658733e-1 + $y * (0.301532e-2 + $y * 0.32411e-3)))))); return ($x < 0.0) ? -$ans : $ans; } $y = 3.75 / $ax; $ans = 0.2282967e-1 + $y * (-0.2895312e-1 + $y * (0.1787654e-1 - $y * 0.420059e-2)); $ans = 0.39894228 + $y * (-0.3988024e-1 + $y * (-0.362018e-2 + $y * (0.163801e-2 + $y * (-0.1031555e-1 + $y * $ans)))); $ans *= exp($ax) / sqrt($ax); return ($x < 0.0) ? -$ans : $ans; } private static function besselI2(float $x, int $ord): float { if ($x === 0.0) { return 0.0; } $tox = 2.0 / abs($x); $bip = 0; $ans = 0.0; $bi = 1.0; for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { $bim = $bip + $j * $tox * $bi; $bip = $bi; $bi = $bim; if (abs($bi) > 1.0e+12) { $ans *= 1.0e-12; $bi *= 1.0e-12; $bip *= 1.0e-12; } if ($j === $ord) { $ans = $bip; } } $ans *= self::besselI0($x) / $bi; return ($x < 0.0 && (($ord % 2) === 1)) ? -$ans : $ans; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php ================================================ 8. This code provides a more accurate calculation * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. * If $ord < 0, BESSELJ returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELJ(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if ($ord < 0) { return ExcelError::NAN(); } $fResult = self::calculate($x, $ord); return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselJ0($x), 1 => self::besselJ1($x), default => self::besselJ2($x, $ord), }; } private static function besselJ0(float $x): float { $ax = abs($x); if ($ax < 8.0) { $y = $x * $x; $ans1 = 57568490574.0 + $y * (-13362590354.0 + $y * (651619640.7 + $y * (-11214424.18 + $y * (77392.33017 + $y * (-184.9052456))))); $ans2 = 57568490411.0 + $y * (1029532985.0 + $y * (9494680.718 + $y * (59272.64853 + $y * (267.8532712 + $y * 1.0)))); return $ans1 / $ans2; } $z = 8.0 / $ax; $y = $z * $z; $xx = $ax - 0.785398164; $ans1 = 1.0 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 - $y * 0.934935152e-7))); return sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); } private static function besselJ1(float $x): float { $ax = abs($x); if ($ax < 8.0) { $y = $x * $x; $ans1 = $x * (72362614232.0 + $y * (-7895059235.0 + $y * (242396853.1 + $y * (-2972611.439 + $y * (15704.48260 + $y * (-30.16036606)))))); $ans2 = 144725228442.0 + $y * (2300535178.0 + $y * (18583304.74 + $y * (99447.43394 + $y * (376.9991397 + $y * 1.0)))); return $ans1 / $ans2; } $z = 8.0 / $ax; $y = $z * $z; $xx = $ax - 2.356194491; $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6))); $ans = sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); return ($x < 0.0) ? -$ans : $ans; } private static function besselJ2(float $x, int $ord): float { $ax = abs($x); if ($ax === 0.0) { return 0.0; } if ($ax > $ord) { return self::besselj2a($ax, $ord, $x); } return self::besselj2b($ax, $ord, $x); } private static function besselj2a(float $ax, int $ord, float $x): float { $tox = 2.0 / $ax; $bjm = self::besselJ0($ax); $bj = self::besselJ1($ax); for ($j = 1; $j < $ord; ++$j) { $bjp = $j * $tox * $bj - $bjm; $bjm = $bj; $bj = $bjp; } $ans = $bj; return ($x < 0.0 && ($ord % 2) == 1) ? -$ans : $ans; } private static function besselj2b(float $ax, int $ord, float $x): float { $tox = 2.0 / $ax; $jsum = false; $bjp = $ans = $sum = 0.0; $bj = 1.0; for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { $bjm = $j * $tox * $bj - $bjp; $bjp = $bj; $bj = $bjm; if (abs($bj) > 1.0e+10) { $bj *= 1.0e-10; $bjp *= 1.0e-10; $ans *= 1.0e-10; $sum *= 1.0e-10; } if ($jsum === true) { $sum += $bj; } $jsum = $jsum === false; if ($j === $ord) { $ans = $bjp; } } $sum = 2.0 * $sum - $bj; $ans /= $sum; return ($x < 0.0 && ($ord % 2) === 1) ? -$ans : $ans; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/BesselK.php ================================================ |float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELK(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if (($ord < 0) || ($x <= 0.0)) { return ExcelError::NAN(); } $fBk = self::calculate($x, $ord); return (is_nan($fBk)) ? ExcelError::NAN() : $fBk; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselK0($x), 1 => self::besselK1($x), default => self::besselK2($x, $ord), }; } /** * Mollify Phpstan. * * @codeCoverageIgnore */ private static function callBesselI(float $x, int $ord): float { $rslt = BesselI::BESSELI($x, $ord); if (!is_float($rslt)) { throw new Exception('Unexpected array or string'); } return $rslt; } private static function besselK0(float $x): float { if ($x <= 2) { $fNum2 = $x * 0.5; $y = ($fNum2 * $fNum2); return -log($fNum2) * self::callBesselI($x, 0) + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * (0.10750e-3 + $y * 0.74e-5)))))); } $y = 2 / $x; return exp(-$x) / sqrt($x) * (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); } private static function besselK1(float $x): float { if ($x <= 2) { $fNum2 = $x * 0.5; $y = ($fNum2 * $fNum2); return log($fNum2) * self::callBesselI($x, 1) + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * (-0.110404e-2 + $y * (-0.4686e-4))))))) / $x; } $y = 2 / $x; return exp(-$x) / sqrt($x) * (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * (0.325614e-2 + $y * (-0.68245e-3))))))); } private static function besselK2(float $x, int $ord): float { $fTox = 2 / $x; $fBkm = self::besselK0($x); $fBk = self::besselK1($x); for ($n = 1; $n < $ord; ++$n) { $fBkp = $fBkm + $n * $fTox * $fBk; $fBkm = $fBk; $fBk = $fBkp; } return $fBk; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/BesselY.php ================================================ |float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELY(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if (($ord < 0) || ($x <= 0.0)) { return ExcelError::NAN(); } $fBy = self::calculate($x, $ord); return (is_nan($fBy)) ? ExcelError::NAN() : $fBy; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselY0($x), 1 => self::besselY1($x), default => self::besselY2($x, $ord), }; } /** * Mollify Phpstan. * * @codeCoverageIgnore */ private static function callBesselJ(float $x, int $ord): float { $rslt = BesselJ::BESSELJ($x, $ord); if (!is_float($rslt)) { throw new Exception('Unexpected array or string'); } return $rslt; } private static function besselY0(float $x): float { if ($x < 8.0) { $y = ($x * $x); $ans1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); $ans2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); return $ans1 / $ans2 + 0.636619772 * self::callBesselJ($x, 0) * log($x); } $z = 8.0 / $x; $y = ($z * $z); $xx = $x - 0.785398164; $ans1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); } private static function besselY1(float $x): float { if ($x < 8.0) { $y = ($x * $x); $ans1 = $x * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * (-0.4237922726e7 + $y * 0.8511937935e4))))); $ans2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); return ($ans1 / $ans2) + 0.636619772 * (self::callBesselJ($x, 1) * log($x) - 1 / $x); } $z = 8.0 / $x; $y = $z * $z; $xx = $x - 2.356194491; $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6))); return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); } private static function besselY2(float $x, int $ord): float { $fTox = 2.0 / $x; $fBym = self::besselY0($x); $fBy = self::besselY1($x); for ($n = 1; $n < $ord; ++$n) { $fByp = $n * $fTox * $fBy - $fBym; $fBym = $fBy; $fBy = $fByp; } return $fBy; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/BitWise.php ================================================ |bool|float|int|string $number1 Or can be an array of values * @param null|array|bool|float|int|string $number2 Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITAND(null|array|bool|float|int|string $number1, null|array|bool|float|int|string $number2): array|string|int|float { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] & $split2[0]) + ($split1[1] & $split2[1]); } /** * BITOR. * * Returns the bitwise OR of two integer values. * * Excel Function: * BITOR(number1, number2) * * @param null|array|bool|float|int|string $number1 Or can be an array of values * @param null|array|bool|float|int|string $number2 Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITOR(null|array|bool|float|int|string $number1, null|array|bool|float|int|string $number2): array|string|int|float { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] | $split2[0]) + ($split1[1] | $split2[1]); } /** * BITXOR. * * Returns the bitwise XOR of two integer values. * * Excel Function: * BITXOR(number1, number2) * * @param null|array|bool|float|int|string $number1 Or can be an array of values * @param null|array|bool|float|int|string $number2 Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITXOR(null|array|bool|float|int|string $number1, null|array|bool|float|int|string $number2): array|string|int|float { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] ^ $split2[0]) + ($split1[1] ^ $split2[1]); } /** * BITLSHIFT. * * Returns the number value shifted left by shift_amount bits. * * Excel Function: * BITLSHIFT(number, shift_amount) * * @param null|array|bool|float|int|string $number Or can be an array of values * @param null|array|bool|float|int|string $shiftAmount Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITLSHIFT(null|array|bool|float|int|string $number, null|array|bool|float|int|string $shiftAmount): array|string|float { if (is_array($number) || is_array($shiftAmount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); } try { $number = self::validateBitwiseArgument($number); $shiftAmount = self::validateShiftAmount($shiftAmount); } catch (Exception $e) { return $e->getMessage(); } $result = floor($number * (2 ** $shiftAmount)); if ($result > 2 ** 48 - 1) { return ExcelError::NAN(); } return $result; } /** * BITRSHIFT. * * Returns the number value shifted right by shift_amount bits. * * Excel Function: * BITRSHIFT(number, shift_amount) * * @param null|array|bool|float|int|string $number Or can be an array of values * @param null|array|bool|float|int|string $shiftAmount Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITRSHIFT(null|array|bool|float|int|string $number, null|array|bool|float|int|string $shiftAmount): array|string|float { if (is_array($number) || is_array($shiftAmount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); } try { $number = self::validateBitwiseArgument($number); $shiftAmount = self::validateShiftAmount($shiftAmount); } catch (Exception $e) { return $e->getMessage(); } $result = floor($number / (2 ** $shiftAmount)); if ($result > 2 ** 48 - 1) { // possible because shiftAmount can be negative return ExcelError::NAN(); } return $result; } /** * Validate arguments passed to the bitwise functions. */ private static function validateBitwiseArgument(mixed $value): float { $value = self::nullFalseTrueToNumber($value); if (is_numeric($value)) { $value = (float) $value; if ($value == floor($value)) { if (($value > 2 ** 48 - 1) || ($value < 0)) { throw new Exception(ExcelError::NAN()); } return floor($value); } throw new Exception(ExcelError::NAN()); } throw new Exception(ExcelError::VALUE()); } /** * Validate arguments passed to the bitwise functions. */ private static function validateShiftAmount(mixed $value): int { $value = self::nullFalseTrueToNumber($value); if (is_numeric($value)) { if (abs($value + 0) > 53) { throw new Exception(ExcelError::NAN()); } return (int) $value; } throw new Exception(ExcelError::VALUE()); } /** * Many functions accept null/false/true argument treated as 0/0/1. */ private static function nullFalseTrueToNumber(mixed &$number): mixed { if ($number === null) { $number = 0; } elseif (is_bool($number)) { $number = (int) $number; } return $number; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/Compare.php ================================================ |bool|float|int|string $a the first number * Or can be an array of values * @param array|bool|float|int|string $b The second number. If omitted, b is assumed to be zero. * Or can be an array of values * * @return array|int|string (string in the event of an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function DELTA(array|float|bool|string|int $a, array|float|bool|string|int $b = 0.0): array|string|int { if (is_array($a) || is_array($b)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $a, $b); } try { $a = EngineeringValidations::validateFloat($a); $b = EngineeringValidations::validateFloat($b); } catch (Exception $e) { return $e->getMessage(); } return (int) (abs($a - $b) < 1.0e-15); } /** * GESTEP. * * Excel Function: * GESTEP(number[,step]) * * Returns 1 if number >= step; returns 0 (zero) otherwise * Use this function to filter a set of values. For example, by summing several GESTEP * functions you calculate the count of values that exceed a threshold. * * @param array|bool|float|int|string $number the value to test against step * Or can be an array of values * @param null|array|bool|float|int|string $step The threshold value. If you omit a value for step, GESTEP uses zero. * Or can be an array of values * * @return array|int|string (string in the event of an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function GESTEP(array|float|bool|string|int $number, $step = 0.0): array|string|int { if (is_array($number) || is_array($step)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $step); } try { $number = EngineeringValidations::validateFloat($number); $step = EngineeringValidations::validateFloat($step ?? 0.0); } catch (Exception $e) { return $e->getMessage(); } return (int) ($number >= $step); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/Complex.php ================================================ |string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function COMPLEX(mixed $realNumber = 0.0, mixed $imaginary = 0.0, mixed $suffix = 'i'): array|string { if (is_array($realNumber) || is_array($imaginary) || is_array($suffix)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $realNumber, $imaginary, $suffix); } $realNumber = $realNumber ?? 0.0; $imaginary = $imaginary ?? 0.0; $suffix = $suffix ?? 'i'; try { $realNumber = EngineeringValidations::validateFloat($realNumber); $imaginary = EngineeringValidations::validateFloat($imaginary); } catch (Exception $e) { return $e->getMessage(); } if (($suffix === 'i') || ($suffix === 'j') || ($suffix === '')) { $complex = new ComplexObject($realNumber, $imaginary, $suffix); return (string) $complex; } return ExcelError::VALUE(); } /** * IMAGINARY. * * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMAGINARY(complexNumber) * * @param array|string $complexNumber the complex number for which you want the imaginary * coefficient * Or can be an array of values * * @return array|float|string (string if an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMAGINARY($complexNumber): array|string|float { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return $complex->getImaginary(); } /** * IMREAL. * * Returns the real coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMREAL(complexNumber) * * @param array|string $complexNumber the complex number for which you want the real coefficient * Or can be an array of values * * @return array|float|string (string if an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMREAL($complexNumber): array|string|float { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return $complex->getReal(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php ================================================ |string $complexNumber the complex number for which you want the absolute value * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMABS(array|string $complexNumber): array|float|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return $complex->abs(); } /** * IMARGUMENT. * * Returns the argument theta of a complex number, i.e. the angle in radians from the real * axis to the representation of the number in polar coordinates. * * Excel Function: * IMARGUMENT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the argument theta * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMARGUMENT(array|string $complexNumber): array|float|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::DIV0(); } return $complex->argument(); } /** * IMCONJUGATE. * * Returns the complex conjugate of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCONJUGATE(complexNumber) * * @param array|string $complexNumber the complex number for which you want the conjugate * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCONJUGATE(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->conjugate(); } /** * IMCOS. * * Returns the cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOS(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cosine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOS(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->cos(); } /** * IMCOSH. * * Returns the hyperbolic cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOSH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOSH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->cosh(); } /** * IMCOT. * * Returns the cotangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cotangent * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOT(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->cot(); } /** * IMCSC. * * Returns the cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSC(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cosecant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCSC(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->csc(); } /** * IMCSCH. * * Returns the hyperbolic cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSCH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosecant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCSCH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->csch(); } /** * IMSIN. * * Returns the sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSIN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the sine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSIN(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sin(); } /** * IMSINH. * * Returns the hyperbolic sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSINH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic sine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSINH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sinh(); } /** * IMSEC. * * Returns the secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSEC(complexNumber) * * @param array|string $complexNumber the complex number for which you want the secant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSEC(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sec(); } /** * IMSECH. * * Returns the hyperbolic secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSECH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic secant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSECH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sech(); } /** * IMTAN. * * Returns the tangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMTAN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the tangent * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMTAN(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->tan(); } /** * IMSQRT. * * Returns the square root of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSQRT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the square root * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSQRT(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } $theta = self::IMARGUMENT($complexNumber); if ($theta === ExcelError::DIV0()) { return '0'; } return (string) $complex->sqrt(); } /** * IMLN. * * Returns the natural logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the natural logarithm * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLN(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->ln(); } /** * IMLOG10. * * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG10(complexNumber) * * @param array|string $complexNumber the complex number for which you want the common logarithm * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLOG10(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->log10(); } /** * IMLOG2. * * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG2(complexNumber) * * @param array|string $complexNumber the complex number for which you want the base-2 logarithm * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLOG2(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->log2(); } /** * IMEXP. * * Returns the exponential of a complex number in x + yi or x + yj text format. * * Excel Function: * IMEXP(complexNumber) * * @param array|string $complexNumber the complex number for which you want the exponential * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMEXP(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->exp(); } /** * IMPOWER. * * Returns a complex number in x + yi or x + yj text format raised to a power. * * Excel Function: * IMPOWER(complexNumber,realNumber) * * @param array|string $complexNumber the complex number you want to raise to a power * Or can be an array of values * @param array|float|int|string $realNumber the power to which you want to raise the complex number * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMPOWER(array|string $complexNumber, array|float|int|string $realNumber): array|string { if (is_array($complexNumber) || is_array($realNumber)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber, $realNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if (!is_numeric($realNumber)) { return ExcelError::VALUE(); } return (string) $complex->pow((float) $realNumber); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php ================================================ |string $complexDividend the complex numerator or dividend * Or can be an array of values * @param array|string $complexDivisor the complex denominator or divisor * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMDIV(array|string $complexDividend, array|string $complexDivisor): array|string { if (is_array($complexDividend) || is_array($complexDivisor)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexDividend, $complexDivisor); } try { return (string) (new ComplexObject($complexDividend))->divideby(new ComplexObject($complexDivisor)); } catch (ComplexException) { return ExcelError::NAN(); } } /** * IMSUB. * * Returns the difference of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUB(complexNumber1,complexNumber2) * * @param array|string $complexNumber1 the complex number from which to subtract complexNumber2 * Or can be an array of values * @param array|string $complexNumber2 the complex number to subtract from complexNumber1 * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSUB(array|string $complexNumber1, array|string $complexNumber2): array|string { if (is_array($complexNumber1) || is_array($complexNumber2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber1, $complexNumber2); } try { return (string) (new ComplexObject($complexNumber1))->subtract(new ComplexObject($complexNumber2)); } catch (ComplexException) { return ExcelError::NAN(); } } /** * IMSUM. * * Returns the sum of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUM(complexNumber[,complexNumber[,...]]) * * @param string ...$complexNumbers Series of complex numbers to add */ public static function IMSUM(...$complexNumbers): string { // Return value $returnValue = new ComplexObject(0.0); $aArgs = Functions::flattenArray($complexNumbers); try { // Loop through the arguments foreach ($aArgs as $complex) { $returnValue = $returnValue->add(new ComplexObject($complex)); } } catch (ComplexException) { return ExcelError::NAN(); } return (string) $returnValue; } /** * IMPRODUCT. * * Returns the product of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMPRODUCT(complexNumber[,complexNumber[,...]]) * * @param string ...$complexNumbers Series of complex numbers to multiply */ public static function IMPRODUCT(...$complexNumbers): string { // Return value $returnValue = new ComplexObject(1.0); $aArgs = Functions::flattenArray($complexNumbers); try { // Loop through the arguments foreach ($aArgs as $complex) { $returnValue = $returnValue->multiply(new ComplexObject($complex)); } } catch (ComplexException) { return ExcelError::NAN(); } return (string) $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/Constants.php ================================================ 10) { throw new Exception(ExcelError::NAN()); } return (int) $places; } throw new Exception(ExcelError::VALUE()); } /** * Formats a number base string value with leading zeroes. * * @param string $value The "number" to pad * @param ?int $places The length that we want to pad this value * * @return string The padded "number" */ protected static function nbrConversionFormat(string $value, ?int $places): string { if ($places !== null) { if (strlen($value) <= $places) { return substr(str_pad($value, $places, '0', STR_PAD_LEFT), -10); } return ExcelError::NAN(); } return substr($value, -10); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php ================================================ |bool|float|int|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. * Or can be an array of values * * @return array|float|int|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateBinary($value); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { // Two's Complement $value = substr($value, -9); return -(512 - bindec($value)); } return bindec($value); } /** * toHex. * * Return a binary value as hex. * * Excel Function: * BIN2HEX(x[,places]) * * @param array|bool|float|int|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. * If places is negative, BIN2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateBinary($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { $high2 = substr($value, 0, 2); $low8 = substr($value, 2); $xarr = ['00' => '00000000', '01' => '00000001', '10' => 'FFFFFFFE', '11' => 'FFFFFFFF']; return $xarr[$high2] . strtoupper(substr('0' . dechex((int) bindec($low8)), -2)); } $hexVal = (string) strtoupper(dechex((int) bindec($value))); return self::nbrConversionFormat($hexVal, $places); } /** * toOctal. * * Return a binary value as octal. * * Excel Function: * BIN2OCT(x[,places]) * * @param array|bool|float|int|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. * If places is negative, BIN2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateBinary($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { // Two's Complement return str_repeat('7', 6) . strtoupper(decoct((int) bindec("11$value"))); } $octVal = (string) decoct((int) bindec($value)); return self::nbrConversionFormat($octVal, $places); } protected static function validateBinary(string $value): string { if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) { throw new Exception(ExcelError::NAN()); } return $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php ================================================ |bool|float|int|string $value The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character * (10-bit) binary number in which the most significant bit is the sign * bit. The remaining 9 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error * value. * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. * If places is zero or negative, DEC2BIN returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = (int) floor((float) $value); if ($value > self::LARGEST_BINARY_IN_DECIMAL || $value < self::SMALLEST_BINARY_IN_DECIMAL) { return ExcelError::NAN(); } $r = decbin($value); // Two's Complement $r = substr($r, -10); return self::nbrConversionFormat($r, $places); } /** * toHex. * * Return a decimal value as hex. * * Excel Function: * DEC2HEX(x[,places]) * * @param array|bool|float|int|string $value The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) * hexadecimal number in which the most significant bit is the sign * bit. The remaining 39 bits are magnitude bits. Negative numbers * are represented using two's-complement notation. * If number < -549,755,813,888 or if number > 549,755,813,887, * DEC2HEX returns the #NUM! error value. * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. * If places is zero or negative, DEC2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = floor((float) $value); if ($value > self::LARGEST_HEX_IN_DECIMAL || $value < self::SMALLEST_HEX_IN_DECIMAL) { return ExcelError::NAN(); } $r = strtoupper(dechex((int) $value)); $r = self::hex32bit($value, $r); return self::nbrConversionFormat($r, $places); } public static function hex32bit(float $value, string $hexstr, bool $force = false): string { if (PHP_INT_SIZE === 4 || $force) { if ($value >= 2 ** 32) { $quotient = (int) ($value / (2 ** 32)); return strtoupper(substr('0' . dechex($quotient), -2) . $hexstr); } if ($value < -(2 ** 32)) { $quotient = 256 - (int) ceil((-$value) / (2 ** 32)); return strtoupper(substr('0' . dechex($quotient), -2) . substr("00000000$hexstr", -8)); } if ($value < 0) { return "FF$hexstr"; } } return $hexstr; } /** * toOctal. * * Return a decimal value as octal. * * Excel Function: * DEC2OCT(x[,places]) * * @param array|bool|float|int|string $value The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) * octal number in which the most significant bit is the sign bit. * The remaining 29 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -536,870,912 or if number > 536,870,911, DEC2OCT * returns the #NUM! error value. * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. * If places is zero or negative, DEC2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = (int) floor((float) $value); if ($value > self::LARGEST_OCTAL_IN_DECIMAL || $value < self::SMALLEST_OCTAL_IN_DECIMAL) { return ExcelError::NAN(); } $r = decoct($value); $r = substr($r, -10); return self::nbrConversionFormat($r, $places); } protected static function validateDecimal(string $value): string { if (strlen($value) > preg_match_all('/[-0123456789.]/', $value)) { throw new Exception(ExcelError::VALUE()); } return $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php ================================================ |bool|float|string $value The hexadecimal number you want to convert. * Number cannot contain more than 10 characters. * The most significant bit of number is the sign bit (40th bit from the right). * The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is negative, HEX2BIN ignores places and returns a 10-character binary number. * If number is negative, it cannot be less than FFFFFFFE00, * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. * If places is negative, HEX2BIN returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateHex($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $dec = self::toDecimal($value); return ConvertDecimal::toBinary($dec, $places); } /** * toDecimal. * * Return a hex value as decimal. * * Excel Function: * HEX2DEC(x) * * @param array|bool|float|int|string $value The hexadecimal number you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant * bit of number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is not a valid hexadecimal number, HEX2DEC returns the * #NUM! error value. * Or can be an array of values * * @return array|float|int|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateHex($value); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) > 10) { return ExcelError::NAN(); } $binX = ''; foreach (mb_str_split($value, 1, 'UTF-8') as $char) { $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); } if (strlen($binX) == 40 && $binX[0] == '1') { for ($i = 0; $i < 40; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } return (bindec($binX) + 1) * -1; } return bindec($binX); } /** * toOctal. * * Return a hex value as octal. * * Excel Function: * HEX2OCT(x[,places]) * * @param array|bool|float|int|string $value The hexadecimal number you want to convert. Number cannot * contain more than 10 characters. The most significant bit of * number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is negative, HEX2OCT ignores places and returns a * 10-character octal number. * If number is negative, it cannot be less than FFE0000000, and * if number is positive, it cannot be greater than 1FFFFFFF. * If number is not a valid hexadecimal number, HEX2OCT returns * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2OCT returns the #VALUE! error * value. * If places is negative, HEX2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateHex($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $decimal = self::toDecimal($value); return ConvertDecimal::toOctal($decimal, $places); } protected static function validateHex(string $value): string { if (strlen($value) > preg_match_all('/[0123456789ABCDEF]/', $value)) { throw new Exception(ExcelError::NAN()); } return $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php ================================================ |bool|float|int|string $value The octal number you want to convert. Number may not * contain more than 10 characters. The most significant * bit of number is the sign bit. The remaining 29 bits * are magnitude bits. Negative numbers are represented * using two's-complement notation. * If number is negative, OCT2BIN ignores places and returns * a 10-character binary number. * If number is negative, it cannot be less than 7777777000, * and if number is positive, it cannot be greater than 777. * If number is not a valid octal number, OCT2BIN returns * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2BIN returns the #VALUE! * error value. * If places is negative, OCT2BIN returns the #NUM! error * value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateOctal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } return ConvertDecimal::toBinary(self::toDecimal($value), $places); } /** * toDecimal. * * Return an octal value as decimal. * * Excel Function: * OCT2DEC(x) * * @param array|bool|float|int|string $value The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is not a valid octal number, OCT2DEC returns the * #NUM! error value. * Or can be an array of values * * @return array|float|int|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateOctal($value); } catch (Exception $e) { return $e->getMessage(); } $binX = ''; foreach (mb_str_split($value, 1, 'UTF-8') as $char) { $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); } if (strlen($binX) == 30 && $binX[0] == '1') { for ($i = 0; $i < 30; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } return (bindec($binX) + 1) * -1; } return bindec($binX); } /** * toHex. * * Return an octal value as hex. * * Excel Function: * OCT2HEX(x[,places]) * * @param array|bool|float|int|string $value The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is negative, OCT2HEX ignores places and returns a * 10-character hexadecimal number. * If number is not a valid octal number, OCT2HEX returns the * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. * If places is negative, OCT2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateOctal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $hexVal = strtoupper(dechex((int) self::toDecimal($value))); $hexVal = (PHP_INT_SIZE === 4 && strlen($value) === 10 && $value[0] >= '4') ? "FF{$hexVal}" : $hexVal; return self::nbrConversionFormat($hexVal, $places); } protected static function validateOctal(string $value): string { $numDigits = (int) preg_match_all('/[01234567]/', $value); if (strlen($value) > $numDigits || $numDigits > 10) { throw new Exception(ExcelError::NAN()); } return $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php ================================================ */ private static array $conversionUnits = [ // Weight and Mass 'g' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Gram', 'AllowPrefix' => true], 'sg' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Slug', 'AllowPrefix' => false], 'lbm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], 'u' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'U (atomic mass unit)', 'AllowPrefix' => true], 'ozm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], 'grain' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Grain', 'AllowPrefix' => false], 'cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], 'shweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], 'uk_cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial hundredweight', 'AllowPrefix' => false], 'lcwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial hundredweight', 'AllowPrefix' => false], 'hweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial hundredweight', 'AllowPrefix' => false], 'stone' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Stone', 'AllowPrefix' => false], 'ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Ton', 'AllowPrefix' => false], 'uk_ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial ton', 'AllowPrefix' => false], 'LTON' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial ton', 'AllowPrefix' => false], 'brton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial ton', 'AllowPrefix' => false], // Distance 'm' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Meter', 'AllowPrefix' => true], 'mi' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Statute mile', 'AllowPrefix' => false], 'Nmi' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Nautical mile', 'AllowPrefix' => false], 'in' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Inch', 'AllowPrefix' => false], 'ft' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Foot', 'AllowPrefix' => false], 'yd' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Yard', 'AllowPrefix' => false], 'ang' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Angstrom', 'AllowPrefix' => true], 'ell' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Ell', 'AllowPrefix' => false], 'ly' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Light Year', 'AllowPrefix' => false], 'parsec' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Parsec', 'AllowPrefix' => false], 'pc' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Parsec', 'AllowPrefix' => false], 'Pica' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Pica (1/72 in)', 'AllowPrefix' => false], 'Picapt' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Pica (1/72 in)', 'AllowPrefix' => false], 'pica' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Pica (1/6 in)', 'AllowPrefix' => false], 'survey_mi' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'U.S survey mile (statute mile)', 'AllowPrefix' => false], // Time 'yr' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Year', 'AllowPrefix' => false], 'day' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Day', 'AllowPrefix' => false], 'd' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Day', 'AllowPrefix' => false], 'hr' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Hour', 'AllowPrefix' => false], 'mn' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Minute', 'AllowPrefix' => false], 'min' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Minute', 'AllowPrefix' => false], 'sec' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Second', 'AllowPrefix' => true], 's' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Second', 'AllowPrefix' => true], // Pressure 'Pa' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Pascal', 'AllowPrefix' => true], 'p' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Pascal', 'AllowPrefix' => true], 'atm' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Atmosphere', 'AllowPrefix' => true], 'at' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Atmosphere', 'AllowPrefix' => true], 'mmHg' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'mm of Mercury', 'AllowPrefix' => true], 'psi' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'PSI', 'AllowPrefix' => true], 'Torr' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Torr', 'AllowPrefix' => true], // Force 'N' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Newton', 'AllowPrefix' => true], 'dyn' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Dyne', 'AllowPrefix' => true], 'dy' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Dyne', 'AllowPrefix' => true], 'lbf' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Pound force', 'AllowPrefix' => false], 'pond' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Pond', 'AllowPrefix' => true], // Energy 'J' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Joule', 'AllowPrefix' => true], 'e' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Erg', 'AllowPrefix' => true], 'c' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Thermodynamic calorie', 'AllowPrefix' => true], 'cal' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'IT calorie', 'AllowPrefix' => true], 'eV' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Electron volt', 'AllowPrefix' => true], 'ev' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Electron volt', 'AllowPrefix' => true], 'HPh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Horsepower-hour', 'AllowPrefix' => false], 'hh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Horsepower-hour', 'AllowPrefix' => false], 'Wh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Watt-hour', 'AllowPrefix' => true], 'wh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Watt-hour', 'AllowPrefix' => true], 'flb' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Foot-pound', 'AllowPrefix' => false], 'BTU' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'BTU', 'AllowPrefix' => false], 'btu' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'BTU', 'AllowPrefix' => false], // Power 'HP' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Horsepower', 'AllowPrefix' => false], 'h' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Horsepower', 'AllowPrefix' => false], 'W' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Watt', 'AllowPrefix' => true], 'w' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Watt', 'AllowPrefix' => true], 'PS' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Pferdestärke', 'AllowPrefix' => false], // Magnetism 'T' => ['Group' => self::CATEGORY_MAGNETISM, 'UnitName' => 'Tesla', 'AllowPrefix' => true], 'ga' => ['Group' => self::CATEGORY_MAGNETISM, 'UnitName' => 'Gauss', 'AllowPrefix' => true], // Temperature 'C' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Celsius', 'AllowPrefix' => false], 'cel' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Celsius', 'AllowPrefix' => false], 'F' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Fahrenheit', 'AllowPrefix' => false], 'fah' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Fahrenheit', 'AllowPrefix' => false], 'K' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Kelvin', 'AllowPrefix' => false], 'kel' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Kelvin', 'AllowPrefix' => false], 'Rank' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Rankine', 'AllowPrefix' => false], 'Reau' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Réaumur', 'AllowPrefix' => false], // Volume 'l' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Litre', 'AllowPrefix' => true], 'L' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Litre', 'AllowPrefix' => true], 'lt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Litre', 'AllowPrefix' => true], 'tsp' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Teaspoon', 'AllowPrefix' => false], 'tspm' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Modern Teaspoon', 'AllowPrefix' => false], 'tbs' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Tablespoon', 'AllowPrefix' => false], 'oz' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Fluid Ounce', 'AllowPrefix' => false], 'cup' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cup', 'AllowPrefix' => false], 'pt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'U.S. Pint', 'AllowPrefix' => false], 'us_pt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'U.S. Pint', 'AllowPrefix' => false], 'uk_pt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'U.K. Pint', 'AllowPrefix' => false], 'qt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Quart', 'AllowPrefix' => false], 'uk_qt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Imperial Quart (UK)', 'AllowPrefix' => false], 'gal' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Gallon', 'AllowPrefix' => false], 'uk_gal' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Imperial Gallon (UK)', 'AllowPrefix' => false], 'ang3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Angstrom', 'AllowPrefix' => true], 'ang^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Angstrom', 'AllowPrefix' => true], 'barrel' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'US Oil Barrel', 'AllowPrefix' => false], 'bushel' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'US Bushel', 'AllowPrefix' => false], 'in3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Inch', 'AllowPrefix' => false], 'in^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Inch', 'AllowPrefix' => false], 'ft3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Foot', 'AllowPrefix' => false], 'ft^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Foot', 'AllowPrefix' => false], 'ly3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Light Year', 'AllowPrefix' => false], 'ly^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Light Year', 'AllowPrefix' => false], 'm3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Meter', 'AllowPrefix' => true], 'm^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Meter', 'AllowPrefix' => true], 'mi3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Mile', 'AllowPrefix' => false], 'mi^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Mile', 'AllowPrefix' => false], 'yd3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Yard', 'AllowPrefix' => false], 'yd^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Yard', 'AllowPrefix' => false], 'Nmi3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Nautical Mile', 'AllowPrefix' => false], 'Nmi^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Nautical Mile', 'AllowPrefix' => false], 'Pica3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'Pica^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'Picapt3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'Picapt^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'GRT' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Gross Registered Ton', 'AllowPrefix' => false], 'regton' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Gross Registered Ton', 'AllowPrefix' => false], 'MTON' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Measurement Ton (Freight Ton)', 'AllowPrefix' => false], // Area 'ha' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Hectare', 'AllowPrefix' => true], 'uk_acre' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'International Acre', 'AllowPrefix' => false], 'us_acre' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'US Survey/Statute Acre', 'AllowPrefix' => false], 'ang2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Angstrom', 'AllowPrefix' => true], 'ang^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Angstrom', 'AllowPrefix' => true], 'ar' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Are', 'AllowPrefix' => true], 'ft2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Feet', 'AllowPrefix' => false], 'ft^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Feet', 'AllowPrefix' => false], 'in2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Inches', 'AllowPrefix' => false], 'in^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Inches', 'AllowPrefix' => false], 'ly2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Light Years', 'AllowPrefix' => false], 'ly^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Light Years', 'AllowPrefix' => false], 'm2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Meters', 'AllowPrefix' => true], 'm^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Meters', 'AllowPrefix' => true], 'Morgen' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Morgen', 'AllowPrefix' => false], 'mi2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Miles', 'AllowPrefix' => false], 'mi^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Miles', 'AllowPrefix' => false], 'Nmi2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Nautical Miles', 'AllowPrefix' => false], 'Nmi^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Nautical Miles', 'AllowPrefix' => false], 'Pica2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'Pica^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'Picapt2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'Picapt^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'yd2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Yards', 'AllowPrefix' => false], 'yd^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Yards', 'AllowPrefix' => false], // Information 'byte' => ['Group' => self::CATEGORY_INFORMATION, 'UnitName' => 'Byte', 'AllowPrefix' => true], 'bit' => ['Group' => self::CATEGORY_INFORMATION, 'UnitName' => 'Bit', 'AllowPrefix' => true], // Speed 'm/s' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per second', 'AllowPrefix' => true], 'm/sec' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per second', 'AllowPrefix' => true], 'm/h' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per hour', 'AllowPrefix' => true], 'm/hr' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per hour', 'AllowPrefix' => true], 'mph' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Miles per hour', 'AllowPrefix' => false], 'admkn' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Admiralty Knot', 'AllowPrefix' => false], 'kn' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Knot', 'AllowPrefix' => false], ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @var array */ private static array $conversionMultipliers = [ 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], 'E' => ['multiplier' => 1E18, 'name' => 'exa'], 'P' => ['multiplier' => 1E15, 'name' => 'peta'], 'T' => ['multiplier' => 1E12, 'name' => 'tera'], 'G' => ['multiplier' => 1E9, 'name' => 'giga'], 'M' => ['multiplier' => 1E6, 'name' => 'mega'], 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], 'e' => ['multiplier' => 1E1, 'name' => 'dekao'], 'da' => ['multiplier' => 1E1, 'name' => 'dekao'], 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @var array */ private static array $binaryConversionMultipliers = [ 'Yi' => ['multiplier' => 2 ** 80, 'name' => 'yobi'], 'Zi' => ['multiplier' => 2 ** 70, 'name' => 'zebi'], 'Ei' => ['multiplier' => 2 ** 60, 'name' => 'exbi'], 'Pi' => ['multiplier' => 2 ** 50, 'name' => 'pebi'], 'Ti' => ['multiplier' => 2 ** 40, 'name' => 'tebi'], 'Gi' => ['multiplier' => 2 ** 30, 'name' => 'gibi'], 'Mi' => ['multiplier' => 2 ** 20, 'name' => 'mebi'], 'ki' => ['multiplier' => 2 ** 10, 'name' => 'kibi'], ]; /** * Details of the Units of measure conversion factors, organised by group. * * @var array> */ private static array $unitConversions = [ // Conversion uses gram (g) as an intermediate unit self::CATEGORY_WEIGHT_AND_MASS => [ 'g' => 1.0, 'sg' => 6.85217658567918E-05, 'lbm' => 2.20462262184878E-03, 'u' => 6.02214179421676E+23, 'ozm' => 3.52739619495804E-02, 'grain' => 1.54323583529414E+01, 'cwt' => 2.20462262184878E-05, 'shweight' => 2.20462262184878E-05, 'uk_cwt' => 1.96841305522212E-05, 'lcwt' => 1.96841305522212E-05, 'hweight' => 1.96841305522212E-05, 'stone' => 1.57473044417770E-04, 'ton' => 1.10231131092439E-06, 'uk_ton' => 9.84206527611061E-07, 'LTON' => 9.84206527611061E-07, 'brton' => 9.84206527611061E-07, ], // Conversion uses meter (m) as an intermediate unit self::CATEGORY_DISTANCE => [ 'm' => 1.0, 'mi' => 6.21371192237334E-04, 'Nmi' => 5.39956803455724E-04, 'in' => 3.93700787401575E+01, 'ft' => 3.28083989501312E+00, 'yd' => 1.09361329833771E+00, 'ang' => 1.0E+10, 'ell' => 8.74890638670166E-01, 'ly' => 1.05700083402462E-16, 'parsec' => 3.24077928966473E-17, 'pc' => 3.24077928966473E-17, 'Pica' => 2.83464566929134E+03, 'Picapt' => 2.83464566929134E+03, 'pica' => 2.36220472440945E+02, 'survey_mi' => 6.21369949494950E-04, ], // Conversion uses second (s) as an intermediate unit self::CATEGORY_TIME => [ 'yr' => 3.16880878140289E-08, 'day' => 1.15740740740741E-05, 'd' => 1.15740740740741E-05, 'hr' => 2.77777777777778E-04, 'mn' => 1.66666666666667E-02, 'min' => 1.66666666666667E-02, 'sec' => 1.0, 's' => 1.0, ], // Conversion uses Pascal (Pa) as an intermediate unit self::CATEGORY_PRESSURE => [ 'Pa' => 1.0, 'p' => 1.0, 'atm' => 9.86923266716013E-06, 'at' => 9.86923266716013E-06, 'mmHg' => 7.50063755419211E-03, 'psi' => 1.45037737730209E-04, 'Torr' => 7.50061682704170E-03, ], // Conversion uses Newton (N) as an intermediate unit self::CATEGORY_FORCE => [ 'N' => 1.0, 'dyn' => 1.0E+5, 'dy' => 1.0E+5, 'lbf' => 2.24808923655339E-01, 'pond' => 1.01971621297793E+02, ], // Conversion uses Joule (J) as an intermediate unit self::CATEGORY_ENERGY => [ 'J' => 1.0, 'e' => 9.99999519343231E+06, 'c' => 2.39006249473467E-01, 'cal' => 2.38846190642017E-01, 'eV' => 6.24145700000000E+18, 'ev' => 6.24145700000000E+18, 'HPh' => 3.72506430801000E-07, 'hh' => 3.72506430801000E-07, 'Wh' => 2.77777916238711E-04, 'wh' => 2.77777916238711E-04, 'flb' => 2.37304222192651E+01, 'BTU' => 9.47815067349015E-04, 'btu' => 9.47815067349015E-04, ], // Conversion uses Horsepower (HP) as an intermediate unit self::CATEGORY_POWER => [ 'HP' => 1.0, 'h' => 1.0, 'W' => 7.45699871582270E+02, 'w' => 7.45699871582270E+02, 'PS' => 1.01386966542400E+00, ], // Conversion uses Tesla (T) as an intermediate unit self::CATEGORY_MAGNETISM => [ 'T' => 1.0, 'ga' => 10000.0, ], // Conversion uses litre (l) as an intermediate unit self::CATEGORY_VOLUME => [ 'l' => 1.0, 'L' => 1.0, 'lt' => 1.0, 'tsp' => 2.02884136211058E+02, 'tspm' => 2.0E+02, 'tbs' => 6.76280454036860E+01, 'oz' => 3.38140227018430E+01, 'cup' => 4.22675283773038E+00, 'pt' => 2.11337641886519E+00, 'us_pt' => 2.11337641886519E+00, 'uk_pt' => 1.75975398639270E+00, 'qt' => 1.05668820943259E+00, 'uk_qt' => 8.79876993196351E-01, 'gal' => 2.64172052358148E-01, 'uk_gal' => 2.19969248299088E-01, 'ang3' => 1.0E+27, 'ang^3' => 1.0E+27, 'barrel' => 6.28981077043211E-03, 'bushel' => 2.83775932584017E-02, 'in3' => 6.10237440947323E+01, 'in^3' => 6.10237440947323E+01, 'ft3' => 3.53146667214886E-02, 'ft^3' => 3.53146667214886E-02, 'ly3' => 1.18093498844171E-51, 'ly^3' => 1.18093498844171E-51, 'm3' => 1.0E-03, 'm^3' => 1.0E-03, 'mi3' => 2.39912758578928E-13, 'mi^3' => 2.39912758578928E-13, 'yd3' => 1.30795061931439E-03, 'yd^3' => 1.30795061931439E-03, 'Nmi3' => 1.57426214685811E-13, 'Nmi^3' => 1.57426214685811E-13, 'Pica3' => 2.27769904358706E+07, 'Pica^3' => 2.27769904358706E+07, 'Picapt3' => 2.27769904358706E+07, 'Picapt^3' => 2.27769904358706E+07, 'GRT' => 3.53146667214886E-04, 'regton' => 3.53146667214886E-04, 'MTON' => 8.82866668037215E-04, ], // Conversion uses hectare (ha) as an intermediate unit self::CATEGORY_AREA => [ 'ha' => 1.0, 'uk_acre' => 2.47105381467165E+00, 'us_acre' => 2.47104393046628E+00, 'ang2' => 1.0E+24, 'ang^2' => 1.0E+24, 'ar' => 1.0E+02, 'ft2' => 1.07639104167097E+05, 'ft^2' => 1.07639104167097E+05, 'in2' => 1.55000310000620E+07, 'in^2' => 1.55000310000620E+07, 'ly2' => 1.11725076312873E-28, 'ly^2' => 1.11725076312873E-28, 'm2' => 1.0E+04, 'm^2' => 1.0E+04, 'Morgen' => 4.0E+00, 'mi2' => 3.86102158542446E-03, 'mi^2' => 3.86102158542446E-03, 'Nmi2' => 2.91553349598123E-03, 'Nmi^2' => 2.91553349598123E-03, 'Pica2' => 8.03521607043214E+10, 'Pica^2' => 8.03521607043214E+10, 'Picapt2' => 8.03521607043214E+10, 'Picapt^2' => 8.03521607043214E+10, 'yd2' => 1.19599004630108E+04, 'yd^2' => 1.19599004630108E+04, ], // Conversion uses bit (bit) as an intermediate unit self::CATEGORY_INFORMATION => [ 'bit' => 1.0, 'byte' => 0.125, ], // Conversion uses Meters per Second (m/s) as an intermediate unit self::CATEGORY_SPEED => [ 'm/s' => 1.0, 'm/sec' => 1.0, 'm/h' => 3.60E+03, 'm/hr' => 3.60E+03, 'mph' => 2.23693629205440E+00, 'admkn' => 1.94260256941567E+00, 'kn' => 1.94384449244060E+00, ], ]; /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions. * * @return string[] */ public static function getConversionCategories(): array { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit) { $conversionGroups[] = $conversionUnit['Group']; } return array_merge(array_unique($conversionGroups)); } /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups. * * @param ?string $category The group whose units of measure you want to retrieve * * @return string[][] */ public static function getConversionCategoryUnits(?string $category = null): array { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if (($category === null) || ($conversionGroup['Group'] == $category)) { $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; } } return $conversionGroups; } /** * getConversionGroupUnitDetails. * * @param ?string $category The group whose units of measure you want to retrieve * * @return array>> */ public static function getConversionCategoryUnitDetails(?string $category = null): array { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if (($category === null) || ($conversionGroup['Group'] == $category)) { $conversionGroups[$conversionGroup['Group']][] = [ 'unit' => $conversionUnit, 'description' => $conversionGroup['UnitName'], ]; } } return $conversionGroups; } /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @return array */ public static function getConversionMultipliers(): array { return self::$conversionMultipliers; } /** * getBinaryConversionMultipliers * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM(). * * @return array */ public static function getBinaryConversionMultipliers(): array { return self::$binaryConversionMultipliers; } /** * CONVERT. * * Converts a number from one measurement system to another. * For example, CONVERT can translate a table of distances in miles to a table of distances * in kilometers. * * Excel Function: * CONVERT(value,fromUOM,toUOM) * * @param array|float|int|string $value the value in fromUOM to convert * Or can be an array of values * @param string|string[] $fromUOM the units for value * Or can be an array of values * @param string|string[] $toUOM the units for the result * Or can be an array of values * * @return float|mixed[]|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONVERT($value, $fromUOM, $toUOM) { if (is_array($value) || is_array($fromUOM) || is_array($toUOM)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $fromUOM, $toUOM); } if (!is_numeric($value)) { return ExcelError::VALUE(); } try { [$fromUOM, $fromCategory, $fromMultiplier] = self::getUOMDetails($fromUOM); [$toUOM, $toCategory, $toMultiplier] = self::getUOMDetails($toUOM); } catch (Exception) { return ExcelError::NA(); } if ($fromCategory !== $toCategory) { return ExcelError::NA(); } // @var float $value $value *= $fromMultiplier; if (($fromUOM === $toUOM) && ($fromMultiplier === $toMultiplier)) { // We've already factored $fromMultiplier into the value, so we need // to reverse it again return $value / $fromMultiplier; } elseif ($fromUOM === $toUOM) { return $value / $toMultiplier; } elseif ($fromCategory === self::CATEGORY_TEMPERATURE) { return self::convertTemperature($fromUOM, $toUOM, $value); } $baseValue = $value * (1.0 / self::$unitConversions[$fromCategory][$fromUOM]); return ($baseValue * self::$unitConversions[$fromCategory][$toUOM]) / $toMultiplier; } /** @return array{0: string, 1: string, 2: float} */ private static function getUOMDetails(string $uom): array { if (isset(self::$conversionUnits[$uom])) { $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, 1.0]; } // Check 1-character standard metric multiplier prefixes $multiplierType = substr($uom, 0, 1); $uom = substr($uom, 1); if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; } $multiplierType .= substr($uom, 0, 1); $uom = substr($uom, 1); // Check 2-character standard metric multiplier prefixes if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; } // Check 2-character binary multiplier prefixes if (isset(self::$conversionUnits[$uom], self::$binaryConversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; if ($unitCategory !== 'Information') { throw new Exception('Binary Prefix is only allowed for Information UoM'); } return [$uom, $unitCategory, self::$binaryConversionMultipliers[$multiplierType]['multiplier']]; } throw new Exception('UoM Not Found'); } protected static function convertTemperature(string $fromUOM, string $toUOM, float|int $value): float|int { $fromUOM = self::resolveTemperatureSynonyms($fromUOM); $toUOM = self::resolveTemperatureSynonyms($toUOM); if ($fromUOM === $toUOM) { return $value; } // Convert to Kelvin switch ($fromUOM) { case 'F': $value = ($value - 32) / 1.8 + 273.15; break; case 'C': $value += 273.15; break; case 'Rank': $value /= 1.8; break; case 'Reau': $value = $value * 1.25 + 273.15; break; } // Convert from Kelvin switch ($toUOM) { case 'F': $value = ($value - 273.15) * 1.8 + 32.00; break; case 'C': $value -= 273.15; break; case 'Rank': $value *= 1.8; break; case 'Reau': $value = ($value - 273.15) * 0.80000; break; } return $value; } private static function resolveTemperatureSynonyms(string $uom): string { return match ($uom) { 'fah' => 'F', 'cel' => 'C', 'kel' => 'K', default => $uom, }; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERF(mixed $lower, mixed $upper = null): array|float|string { if (is_array($lower) || is_array($upper)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $lower, $upper); } if (is_numeric($lower)) { if ($upper === null) { return self::erfValue($lower); } if (is_numeric($upper)) { return self::erfValue($upper) - self::erfValue($lower); } } return ExcelError::VALUE(); } /** * ERFPRECISE. * * Returns the error function integrated between the lower and upper bound arguments. * * Excel Function: * ERF.PRECISE(limit) * * @param mixed $limit Float bound for integrating ERF, other bound is zero * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERFPRECISE(mixed $limit) { if (is_array($limit)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $limit); } return self::ERF($limit); } private static function makeFloat(mixed $value): float { return is_numeric($value) ? ((float) $value) : 0.0; } /** * Method to calculate the erf value. */ public static function erfValue(float|int|string $value): float { $value = (float) $value; if (abs($value) > 2.2) { return 1 - self::makeFloat(ErfC::ERFC($value)); } $sum = $term = $value; $xsqr = ($value * $value); $j = 1; do { $term *= $xsqr / $j; $sum -= $term / (2 * $j + 1); ++$j; $term *= $xsqr / $j; $sum += $term / (2 * $j + 1); ++$j; if ($sum == 0.0) { break; } } while (abs($term / $sum) > Functions::PRECISION); return self::TWO_SQRT_PI * $sum; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERFC(mixed $value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (is_numeric($value)) { return self::erfcValue($value); } return ExcelError::VALUE(); } private const ONE_SQRT_PI = 0.564189583547756287; /** * Method to calculate the erfc value. */ private static function erfcValue(float|int|string $value): float|int { $value = (float) $value; if (abs($value) < 2.2) { return 1 - Erf::erfValue($value); } if ($value < 0) { return 2 - self::erfcValue(-$value); } $a = $n = 1; $b = $c = $value; $d = ($value * $value) + 0.5; $q2 = $b / $d; do { $t = $a * $n + $b * $value; $a = $b; $b = $t; $t = $c * $n + $d * $value; $c = $d; $d = $t; $n += 0.5; $q1 = $q2; $q2 = $b / $d; } while ((abs($q1 - $q2) / $q2) > Functions::PRECISION); return self::ONE_SQRT_PI * exp(-$value * $value) * $q2; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Exception.php ================================================ line = $line; $e->file = $file; throw $e; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/ExceptionHandler.php ================================================ getMessage(); } $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); if (is_string($yearFracx)) { return $yearFracx; } /** @var float $yearFrac */ $yearFrac = $yearFracx; $amortiseCoeff = self::getAmortizationCoefficient($rate); $rate *= $amortiseCoeff; $rate = (float) (string) $rate; // ugly way to avoid rounding problem $fNRate = round($yearFrac * $rate * $cost, 0); $cost -= $fNRate; $fRest = $cost - $salvage; for ($n = 0; $n < $period; ++$n) { $fNRate = round($rate * $cost, 0); $fRest -= $fNRate; if ($fRest < 0.0) { return match ($period - $n) { 1 => round($cost * 0.5, 0), default => 0.0, }; } $cost -= $fNRate; } return $fNRate; } /** * AMORLINC. * * Returns the depreciation for each accounting period. * This function is provided for the French accounting system. If an asset is purchased in * the middle of the accounting period, the prorated depreciation is taken into account. * * Excel Function: * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * * @param mixed $cost The cost of the asset as a float * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period * @param mixed $salvage The salvage value at the end of the life of the asset * @param mixed $period The period as a float * @param mixed $rate Rate of depreciation as float * @param mixed $basis Integer indicating the type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string (string containing the error type if there is an error) */ public static function AMORLINC( mixed $cost, mixed $purchased, mixed $firstPeriod, mixed $salvage, mixed $period, mixed $rate, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $cost = Functions::flattenSingleValue($cost); $purchased = Functions::flattenSingleValue($purchased); $firstPeriod = Functions::flattenSingleValue($firstPeriod); $salvage = Functions::flattenSingleValue($salvage); $period = Functions::flattenSingleValue($period); $rate = Functions::flattenSingleValue($rate); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $cost = FinancialValidations::validateFloat($cost); $purchased = FinancialValidations::validateDate($purchased); $firstPeriod = FinancialValidations::validateDate($firstPeriod); $salvage = FinancialValidations::validateFloat($salvage); $period = FinancialValidations::validateFloat($period); $rate = FinancialValidations::validateFloat($rate); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $fOneRate = $cost * $rate; $fCostDelta = $cost - $salvage; // Note, quirky variation for leap years on the YEARFRAC for this function $purchasedYear = DateTimeExcel\DateParts::year($purchased); $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); if (is_string($yearFracx)) { return $yearFracx; } /** @var float $yearFrac */ $yearFrac = $yearFracx; if ( $basis == FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL && $yearFrac < 1 ) { $temp = Functions::scalar($purchasedYear); if (is_int($temp) || is_string($temp)) { if (DateTimeExcel\Helpers::isLeapYear($temp)) { $yearFrac *= 365 / 366; } } } $f0Rate = $yearFrac * $rate * $cost; $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); if ($period == 0) { return $f0Rate; } elseif ($period <= $nNumOfFullPeriods) { return $fOneRate; } elseif ($period == ($nNumOfFullPeriods + 1)) { return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; } return 0.0; } private static function getAmortizationCoefficient(float $rate): float { // The depreciation coefficients are: // Life of assets (1/rate) Depreciation coefficient // Less than 3 years 1 // Between 3 and 4 years 1.5 // Between 5 and 6 years 2 // More than 6 years 2.5 $fUsePer = 1.0 / $rate; if ($fUsePer < 3.0) { return 1.0; } elseif ($fUsePer < 4.0) { return 1.5; } elseif ($fUsePer <= 6.0) { return 2.0; } return 2.5; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php ================================================ getMessage(); } // Validate parameters if ($start < 1 || $start > $end) { return ExcelError::NAN(); } // Calculate $interest = 0; for ($per = $start; $per <= $end; ++$per) { $ipmt = Interest::payment($rate, $per, $periods, $presentValue, 0, $type); if (is_string($ipmt)) { return $ipmt; } $interest += $ipmt; } return $interest; } /** * CUMPRINC. * * Returns the cumulative principal paid on a loan between the start and end periods. * * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * * @param mixed $rate The Interest rate * @param mixed $periods The total number of payment periods as an integer * @param mixed $presentValue Present Value * @param mixed $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param mixed $end the last period in the calculation * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. */ public static function principal( mixed $rate, mixed $periods, mixed $presentValue, mixed $start, mixed $end, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float|int { $rate = Functions::flattenSingleValue($rate); $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $start = Functions::flattenSingleValue($start); $end = Functions::flattenSingleValue($end); $type = Functions::flattenSingleValue($type) ?? FinancialConstants::PAYMENT_END_OF_PERIOD; try { $rate = CashFlowValidations::validateRate($rate); $periods = CashFlowValidations::validateInt($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $start = CashFlowValidations::validateInt($start); $end = CashFlowValidations::validateInt($end); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($start < 1 || $start > $end) { return ExcelError::VALUE(); } // Calculate $principal = 0; for ($per = $start; $per <= $end; ++$per) { $ppmt = Payments::interestPayment($rate, $per, $periods, $presentValue, 0, $type); if (is_string($ppmt)) { return $ppmt; } $principal += $ppmt; } return $principal; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php ================================================ getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Calculate $interestAndPrincipal = new InterestAndPrincipal( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue, $type ); return $interestAndPrincipal->interest(); } /** * ISPMT. * * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. * * Excel Function: * =ISPMT(interest_rate, period, number_payments, pv) * * @param mixed $interestRate is the interest rate for the investment * @param mixed $period is the period to calculate the interest rate. It must be between 1 and number_payments. * @param mixed $numberOfPeriods is the number of payments for the annuity * @param mixed $principleRemaining is the loan amount or present value of the payments */ public static function schedulePayment(mixed $interestRate, mixed $period, mixed $numberOfPeriods, mixed $principleRemaining): string|float { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $principleRemaining = Functions::flattenSingleValue($principleRemaining); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $principleRemaining = CashFlowValidations::validateFloat($principleRemaining); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Return value $returnValue = 0; // Calculate $principlePayment = ($principleRemaining * 1.0) / ($numberOfPeriods * 1.0); for ($i = 0; $i <= $period; ++$i) { $returnValue = $interestRate * $principleRemaining * -1; $principleRemaining -= $principlePayment; // principle needs to be 0 after the last payment, don't let floating point screw it up if ($i == $numberOfPeriods) { $returnValue = 0.0; } } return $returnValue; } /** * RATE. * * Returns the interest rate per period of an annuity. * RATE is calculated by iteration and can have zero or more solutions. * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, * RATE returns the #NUM! error value. * * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * * @param mixed $numberOfPeriods The total number of payment periods in an annuity * @param mixed $payment The payment made each period and cannot change over the life of the annuity. * Typically, pmt includes principal and interest but no other fees or taxes. * @param mixed $presentValue The present value - the total amount that a series of future payments is worth now * @param mixed $futureValue The future value, or a cash balance you want to attain after the last payment is made. * If fv is omitted, it is assumed to be 0 (the future value of a loan, * for example, is 0). * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @param mixed $guess Your guess for what the rate will be. * If you omit guess, it is assumed to be 10 percent. */ public static function rate( mixed $numberOfPeriods, mixed $payment, mixed $presentValue, mixed $futureValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD, mixed $guess = 0.1 ): string|float { $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = Functions::flattenSingleValue($payment); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue) ?? 0.0; $type = Functions::flattenSingleValue($type) ?? FinancialConstants::PAYMENT_END_OF_PERIOD; $guess = Functions::flattenSingleValue($guess) ?? 0.1; try { $numberOfPeriods = CashFlowValidations::validateFloat($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); $guess = CashFlowValidations::validateFloat($guess); } catch (Exception $e) { return $e->getMessage(); } $rate = $guess; // rest of code adapted from python/numpy $close = false; $iter = 0; while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) { $nextdiff = self::rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type); if (!is_numeric($nextdiff)) { break; } $rate1 = $rate - $nextdiff; $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION; ++$iter; $rate = $rate1; } return $close ? $rate : ExcelError::NAN(); } private static function rateNextGuess(float $rate, float $numberOfPeriods, float $payment, float $presentValue, float $futureValue, int $type): string|float { if ($rate == 0.0) { return ExcelError::NAN(); } $tt1 = ($rate + 1) ** $numberOfPeriods; $tt2 = ($rate + 1) ** ($numberOfPeriods - 1); $numerator = $futureValue + $tt1 * $presentValue + $payment * ($tt1 - 1) * ($rate * $type + 1) / $rate; $denominator = $numberOfPeriods * $tt2 * $presentValue - $payment * ($tt1 - 1) * ($rate * $type + 1) / ($rate * $rate) + $numberOfPeriods * $payment * $tt2 * ($rate * $type + 1) / $rate + $payment * ($tt1 - 1) * $type / $rate; if ($denominator == 0) { return ExcelError::NAN(); } return $numerator / $denominator; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php ================================================ interest = $interest; $this->principal = $principal; } public function interest(): float { return $this->interest; } public function principal(): float { return $this->principal; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php ================================================ getMessage(); } // Calculate if ($interestRate != 0.0) { return (-$futureValue - $presentValue * (1 + $interestRate) ** $numberOfPeriods) / (1 + $interestRate * $type) / (((1 + $interestRate) ** $numberOfPeriods - 1) / $interestRate); } return (-$presentValue - $futureValue) / $numberOfPeriods; } /** * PPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * @param mixed $interestRate Interest rate per period * @param mixed $period Period for which we want to find the interest * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function interestPayment( mixed $interestRate, mixed $period, mixed $numberOfPeriods, mixed $presentValue, mixed $futureValue = 0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = Functions::flattenSingleValue($type) ?? FinancialConstants::PAYMENT_END_OF_PERIOD; try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Calculate $interestAndPrincipal = new InterestAndPrincipal( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue, $type ); return $interestAndPrincipal->principal(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic.php ================================================ getMessage(); } return self::calculateFutureValue($rate, $numberOfPeriods, $payment, $presentValue, $type); } /** * PV. * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). * * @param mixed $rate Interest rate per period * @param mixed $numberOfPeriods Number of periods as an integer * @param mixed $payment Periodic payment (annuity) * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function presentValue( mixed $rate, mixed $numberOfPeriods, mixed $payment = 0.0, mixed $futureValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $rate = Functions::flattenSingleValue($rate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = Functions::flattenSingleValue($payment) ?? 0.0; $futureValue = Functions::flattenSingleValue($futureValue) ?? 0.0; $type = Functions::flattenSingleValue($type) ?? FinancialConstants::PAYMENT_END_OF_PERIOD; try { $rate = CashFlowValidations::validateRate($rate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($numberOfPeriods < 0) { return ExcelError::NAN(); } return self::calculatePresentValue($rate, $numberOfPeriods, $payment, $futureValue, $type); } /** * NPER. * * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. * * @param mixed $rate Interest rate per period * @param mixed $payment Periodic payment (annuity) * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function periods( mixed $rate, mixed $payment, mixed $presentValue, mixed $futureValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $payment = Functions::flattenSingleValue($payment); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue) ?? 0.0; $type = Functions::flattenSingleValue($type) ?? FinancialConstants::PAYMENT_END_OF_PERIOD; try { $rate = CashFlowValidations::validateRate($rate); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($payment == 0.0) { return ExcelError::NAN(); } return self::calculatePeriods($rate, $payment, $presentValue, $futureValue, $type); } private static function calculateFutureValue( float $rate, int $numberOfPeriods, float $payment, float $presentValue, int $type ): float { if ($rate != 0) { return -$presentValue * (1 + $rate) ** $numberOfPeriods - $payment * (1 + $rate * $type) * ((1 + $rate) ** $numberOfPeriods - 1) / $rate; } return -$presentValue - $payment * $numberOfPeriods; } private static function calculatePresentValue( float $rate, int $numberOfPeriods, float $payment, float $futureValue, int $type ): float { if ($rate != 0.0) { return (-$payment * (1 + $rate * $type) * (((1 + $rate) ** $numberOfPeriods - 1) / $rate) - $futureValue) / (1 + $rate) ** $numberOfPeriods; } return -$futureValue - $payment * $numberOfPeriods; } private static function calculatePeriods( float $rate, float $payment, float $presentValue, float $futureValue, int $type ): string|float { if ($rate != 0.0) { if ($presentValue == 0.0) { return ExcelError::NAN(); } return log(($payment * (1 + $rate * $type) / $rate - $futureValue) / ($presentValue + $payment * (1 + $rate * $type) / $rate)) / log(1 + $rate); } return (-$presentValue - $futureValue) / $payment; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php ================================================ getMessage(); } return $principal; } /** * PDURATION. * * Calculates the number of periods required for an investment to reach a specified value. * * @param mixed $rate Interest rate per period * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * * @return float|string Result, or a string containing an error */ public static function periods(mixed $rate, mixed $presentValue, mixed $futureValue): string|float { $rate = Functions::flattenSingleValue($rate); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue); try { $rate = CashFlowValidations::validateRate($rate); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($rate <= 0.0 || $presentValue <= 0.0 || $futureValue <= 0.0) { return ExcelError::NAN(); } return (log($futureValue) - log($presentValue)) / log(1 + $rate); } /** * RRI. * * Calculates the interest rate required for an investment to grow to a specified future value . * * @param mixed $periods The number of periods over which the investment is made, expect array|float * @param mixed $presentValue Present Value, expect array|float * @param mixed $futureValue Future Value, expect array|float * * @return float|string Result, or a string containing an error */ public static function interestRate(mixed $periods = 0.0, mixed $presentValue = 0.0, mixed $futureValue = 0.0): string|float { $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue); try { $periods = CashFlowValidations::validateFloat($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($periods <= 0.0 || $presentValue <= 0.0 || $futureValue < 0.0) { return ExcelError::NAN(); } return ($futureValue / $presentValue) ** (1 / $periods) - 1; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php ================================================ $values A series of cash flow payments, expecting float[] * The series of values must contain at least one positive value & one negative value * @param array $dates A series of payment dates * The first payment date indicates the beginning of the schedule of payments * All other dates must be later than this date, but they may occur in any order * @param mixed $guess An optional guess at the expected answer */ public static function rate(mixed $values, $dates, mixed $guess = self::DEFAULT_GUESS): float|string { $rslt = self::xirrPart1($values, $dates); /** @var array $dates */ if ($rslt !== '') { return $rslt; } // create an initial range, with a root somewhere between 0 and guess $guess = Functions::flattenSingleValue($guess) ?? self::DEFAULT_GUESS; if (!is_numeric($guess)) { return ExcelError::VALUE(); } $guess = ($guess + 0.0) ?: self::DEFAULT_GUESS; $x1 = 0.0; $x2 = $guess + 0.0; $f1 = self::xnpvOrdered($x1, $values, $dates, false); $f2 = self::xnpvOrdered($x2, $values, $dates, false); $found = false; for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { if (!is_numeric($f1)) { return $f1; } if (!is_numeric($f2)) { return $f2; } $f1 = (float) $f1; $f2 = (float) $f2; if (($f1 * $f2) < 0.0) { $found = true; break; } elseif (abs($f1) < abs($f2)) { $x1 += 1.6 * ($x1 - $x2); $f1 = self::xnpvOrdered($x1, $values, $dates, false); } else { $x2 += 1.6 * ($x2 - $x1); $f2 = self::xnpvOrdered($x2, $values, $dates, false); } } if ($found) { return self::xirrPart3($values, $dates, $x1, $x2); } // Newton-Raphson didn't work - try bisection $x1 = $guess - 0.5; $x2 = $guess + 0.5; for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $f1 = self::xnpvOrdered($x1, $values, $dates, false, true); $f2 = self::xnpvOrdered($x2, $values, $dates, false, true); if (!is_numeric($f1) || !is_numeric($f2)) { break; } if ($f1 * $f2 <= 0) { $found = true; break; } $x1 -= 0.5; $x2 += 0.5; } if ($found) { /** @var array $dates */ return self::xirrBisection($values, $dates, $x1, $x2); } return ExcelError::NAN(); } /** * XNPV. * * Returns the net present value for a schedule of cash flows that is not necessarily periodic. * To calculate the net present value for a series of cash flows that is periodic, use the NPV function. * * Excel Function: * =XNPV(rate,values,dates) * * @param mixed $rate the discount rate to apply to the cash flows, expect array|float * @param array $values A series of cash flows that corresponds to a schedule of payments in dates, expecting float[]. * The first payment is optional and corresponds to a cost or payment that occurs * at the beginning of the investment. * If the first value is a cost or payment, it must be a negative value. * All succeeding payments are discounted based on a 365-day year. * The series of values must contain at least one positive value and one negative value. * @param mixed $dates A schedule of payment dates that corresponds to the cash flow payments, expecting mixed[]. * The first payment date indicates the beginning of the schedule of payments. * All other dates must be later than this date, but they may occur in any order. */ public static function presentValue(mixed $rate, mixed $values, mixed $dates): float|string { return self::xnpvOrdered($rate, $values, $dates, true); } private static function bothNegAndPos(bool $neg, bool $pos): bool { return $neg && $pos; } /** @param array $values */ private static function xirrPart1(mixed &$values, mixed &$dates): string { /** @var array */ $temp = Functions::flattenArray($values); $values = $temp; $dates = Functions::flattenArray($dates); $valuesIsArray = count($values) > 1; $datesIsArray = count($dates) > 1; if (!$valuesIsArray && !$datesIsArray) { return ExcelError::NA(); } if (count($values) != count($dates)) { return ExcelError::NAN(); } $datesCount = count($dates); for ($i = 0; $i < $datesCount; ++$i) { try { $dates[$i] = DateTimeExcel\Helpers::getDateValue($dates[$i]); } catch (Exception $e) { return $e->getMessage(); } } return self::xirrPart2($values); } /** @param array $values */ private static function xirrPart2(array &$values): string { $valCount = count($values); $foundpos = false; $foundneg = false; for ($i = 0; $i < $valCount; ++$i) { $fld = $values[$i]; if (!is_numeric($fld)) { //* @phpstan-ignore-line return ExcelError::VALUE(); } elseif ($fld > 0) { $foundpos = true; } elseif ($fld < 0) { $foundneg = true; } } if (!self::bothNegAndPos($foundneg, $foundpos)) { return ExcelError::NAN(); } return ''; } /** * @param array $values * @param array $dates */ private static function xirrPart3(array $values, array $dates, float $x1, float $x2): float|string { $f = self::xnpvOrdered($x1, $values, $dates, false); if ($f < 0.0) { $rtb = $x1; $dx = $x2 - $x1; } else { $rtb = $x2; $dx = $x1 - $x2; } $rslt = ExcelError::VALUE(); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $dx *= 0.5; $x_mid = $rtb + $dx; $f_mid = (float) self::xnpvOrdered($x_mid, $values, $dates, false); if ($f_mid <= 0.0) { $rtb = $x_mid; } if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { $rslt = $x_mid; break; } } return $rslt; } /** * @param array $values * @param array $dates */ private static function xirrBisection(array $values, array $dates, float $x1, float $x2): string|float { $rslt = ExcelError::NAN(); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $rslt = ExcelError::NAN(); $f1 = self::xnpvOrdered($x1, $values, $dates, false, true); $f2 = self::xnpvOrdered($x2, $values, $dates, false, true); if (!is_numeric($f1) || !is_numeric($f2)) { break; } $f1 = (float) $f1; $f2 = (float) $f2; if (abs($f1) < self::FINANCIAL_PRECISION && abs($f2) < self::FINANCIAL_PRECISION) { break; } if ($f1 * $f2 > 0) { break; } $rslt = ($x1 + $x2) / 2; $f3 = self::xnpvOrdered($rslt, $values, $dates, false, true); if (!is_float($f3)) { break; } if ($f3 * $f1 < 0) { $x2 = $rslt; } else { $x1 = $rslt; } if (abs($f3) < self::FINANCIAL_PRECISION) { break; } } return $rslt; } /** @param array $values> */ private static function xnpvOrdered(mixed $rate, mixed $values, mixed $dates, bool $ordered = true, bool $capAtNegative1 = false): float|string { $rate = Functions::flattenSingleValue($rate); if (!is_numeric($rate)) { return ExcelError::VALUE(); } $values = Functions::flattenArray($values); $dates = Functions::flattenArray($dates); $valCount = count($values); try { self::validateXnpv($rate, $values, $dates); if ($capAtNegative1 && $rate <= -1) { $rate = -1.0 + 1.0E-10; } $date0 = DateTimeExcel\Helpers::getDateValue($dates[0]); } catch (Exception $e) { return $e->getMessage(); } $xnpv = 0.0; for ($i = 0; $i < $valCount; ++$i) { if (!is_numeric($values[$i])) { return ExcelError::VALUE(); } try { $datei = DateTimeExcel\Helpers::getDateValue($dates[$i]); } catch (Exception $e) { return $e->getMessage(); } if ($date0 > $datei) { $dif = $ordered ? ExcelError::NAN() : -((int) DateTimeExcel\Difference::interval($datei, $date0, 'd')); } else { $dif = Functions::scalar(DateTimeExcel\Difference::interval($date0, $datei, 'd')); } if (!is_numeric($dif)) { return StringHelper::convertToString($dif); } if ($rate <= -1.0) { $xnpv += -abs($values[$i] + 0) / (-1 - $rate) ** ($dif / 365); } else { $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365); } } return is_finite($xnpv) ? $xnpv : ExcelError::VALUE(); } /** * @param mixed[] $values * @param mixed[] $dates */ private static function validateXnpv(mixed $rate, array $values, array $dates): void { if (!is_numeric($rate)) { throw new Exception(ExcelError::VALUE()); } $valCount = count($values); if ($valCount != count($dates)) { throw new Exception(ExcelError::NAN()); } if (count($values) > 1 && ((min($values) > 0) || (max($values) < 0))) { throw new Exception(ExcelError::NAN()); } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php ================================================ 0.0) { return ExcelError::VALUE(); } $f = self::presentValue($x1, $values); if ($f < 0.0) { $rtb = $x1; $dx = $x2 - $x1; } else { $rtb = $x2; $dx = $x1 - $x2; } for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $dx *= 0.5; $x_mid = $rtb + $dx; $f_mid = self::presentValue($x_mid, $values); if ($f_mid <= 0.0) { $rtb = $x_mid; } if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { return $x_mid; } } return ExcelError::VALUE(); } /** * MIRR. * * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both * the cost of the investment and the interest received on reinvestment of cash. * * Excel Function: * MIRR(values,finance_rate, reinvestment_rate) * * @param mixed $values An array or a reference to cells that contain a series of payments and * income occurring at regular intervals. * Payments are negative value, income is positive values. * @param mixed $financeRate The interest rate you pay on the money used in the cash flows * @param mixed $reinvestmentRate The interest rate you receive on the cash flows as you reinvest them * * @return float|string Result, or a string containing an error */ public static function modifiedRate(mixed $values, mixed $financeRate, mixed $reinvestmentRate): string|float { if (!is_array($values)) { return ExcelError::DIV0(); } $values = Functions::flattenArray($values); /** @var float */ $financeRate = Functions::flattenSingleValue($financeRate); /** @var float */ $reinvestmentRate = Functions::flattenSingleValue($reinvestmentRate); $n = count($values); $rr = 1.0 + $reinvestmentRate; $fr = 1.0 + $financeRate; $npvPos = $npvNeg = 0.0; foreach ($values as $i => $v) { /** @var float $v */ if ($v >= 0) { $npvPos += $v / $rr ** $i; } else { $npvNeg += $v / $fr ** $i; } } if ($npvNeg === 0.0 || $npvPos === 0.0) { return ExcelError::DIV0(); } $mirr = ((-$npvPos * $rr ** $n) / ($npvNeg * ($rr))) ** (1.0 / ($n - 1)) - 1.0; return is_finite($mirr) ? $mirr : ExcelError::NAN(); } /** * NPV. * * Returns the Net Present Value of a cash flow series given a discount rate. * * @param array $args */ public static function presentValue(mixed $rate, ...$args): int|float { $returnValue = 0; /** @var float */ $rate = Functions::flattenSingleValue($rate); $aArgs = Functions::flattenArray($args); // Calculate $countArgs = count($aArgs); for ($i = 1; $i <= $countArgs; ++$i) { // Is it a numeric value? if (is_numeric($aArgs[$i - 1])) { $returnValue += $aArgs[$i - 1] / (1 + $rate) ** $i; } } return $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Constants.php ================================================ getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (is_string($daysPerYear)) { return ExcelError::VALUE(); } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) { return abs((float) DateTimeExcel\Days::between($prev, $settlement)); } return (float) DateTimeExcel\YearFrac::fraction($prev, $settlement, $basis) * $daysPerYear; } /** * COUPDAYS. * * Returns the number of days in the coupon period that contains the settlement date. * * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function COUPDAYS( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|int|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } switch ($basis) { case FinancialConstants::BASIS_DAYS_PER_YEAR_365: // Actual/365 return 365 / $frequency; case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: // Actual/actual if ($frequency == FinancialConstants::FREQUENCY_ANNUAL) { $daysPerYear = (int) Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); return $daysPerYear / $frequency; } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); return $next - $prev; default: // US (NASD) 30/360, Actual/360 or European 30/360 return 360 / $frequency; } } /** * COUPDAYSNC. * * Returns the number of days from the settlement date to the next coupon date. * * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int) . * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function COUPDAYSNC( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } /** @var int $daysPerYear */ $daysPerYear = Helpers::daysPerYear(Functions::Scalar(DateTimeExcel\DateParts::year($settlement)), $basis); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_NASD) { $settlementDate = Date::excelToDateTimeObject($settlement); $settlementEoM = Helpers::isLastDayOfMonth($settlementDate); if ($settlementEoM) { ++$settlement; } } return (float) DateTimeExcel\YearFrac::fraction($settlement, $next, $basis) * $daysPerYear; } /** * COUPNCD. * * Returns the next coupon date after the settlement date. * * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Excel date/time serial value or error message */ public static function COUPNCD( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); } /** * COUPNUM. * * Returns the number of coupons payable between the settlement date and maturity date, * rounded up to the nearest whole coupon. * * Excel Function: * COUPNUM(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function COUPNUM( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|int { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $yearsBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction( $settlement, $maturity, FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ); return (int) ceil((float) $yearsBetweenSettlementAndMaturity * $frequency); } /** * COUPPCD. * * Returns the previous coupon date before the settlement date. * * Excel Function: * COUPPCD(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Excel date/time serial value or error message */ public static function COUPPCD( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); } private static function monthsDiff(DateTime $result, int $months, string $plusOrMinus, int $day, bool $lastDayFlag): void { $result->setDate((int) $result->format('Y'), (int) $result->format('m'), 1); $result->modify("$plusOrMinus $months months"); $daysInMonth = (int) $result->format('t'); $result->setDate((int) $result->format('Y'), (int) $result->format('m'), $lastDayFlag ? $daysInMonth : min($day, $daysInMonth)); } private static function couponFirstPeriodDate(float $settlement, float $maturity, int $frequency, bool $next): float { $months = 12 / $frequency; $result = Date::excelToDateTimeObject($maturity); $day = (int) $result->format('d'); $lastDayFlag = Helpers::isLastDayOfMonth($result); while ($settlement < Date::PHPToExcel($result)) { self::monthsDiff($result, $months, '-', $day, $lastDayFlag); } if ($next === true) { self::monthsDiff($result, $months, '+', $day, $lastDayFlag); } return (float) Date::PHPToExcel($result); } private static function validateCouponPeriod(float $settlement, float $maturity): void { if ($settlement >= $maturity) { throw new Exception(ExcelError::NAN()); } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php ================================================ getMessage(); } if ($cost === self::$zeroPointZero) { return 0.0; } // Set Fixed Depreciation Rate $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); $fixedDepreciationRate = round($fixedDepreciationRate, 3); // Loop through each period calculating the depreciation // TODO Handle period value between 0 and 1 (e.g. 0.5) $previousDepreciation = 0; $depreciation = 0; for ($per = 1; $per <= $period; ++$per) { if ($per == 1) { $depreciation = $cost * $fixedDepreciationRate * $month / 12; } elseif ($per == ($life + 1)) { $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; } else { $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; } $previousDepreciation += $depreciation; } return $depreciation; } /** * DDB. * * Returns the depreciation of an asset for a specified period using the * double-declining balance method or some other method you specify. * * Excel Function: * DDB(cost,salvage,life,period[,factor]) * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param mixed $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param mixed $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param mixed $factor The rate at which the balance declines. * If factor is omitted, it is assumed to be 2 (the * double-declining balance method). */ public static function DDB(mixed $cost, mixed $salvage, mixed $life, mixed $period, mixed $factor = 2.0): float|string { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); $factor = Functions::flattenSingleValue($factor); try { $cost = self::validateCost($cost); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); $factor = self::validateFactor($factor); } catch (Exception $e) { return $e->getMessage(); } if ($period > $life) { return ExcelError::NAN(); } // Loop through each period calculating the depreciation // TODO Handling for fractional $period values $previousDepreciation = 0; $depreciation = 0; for ($per = 1; $per <= $period; ++$per) { $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) ); $previousDepreciation += $depreciation; } return $depreciation; } /** * SLN. * * Returns the straight-line depreciation of an asset for one period * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * * @return float|string Result, or a string containing an error */ public static function SLN(mixed $cost, mixed $salvage, mixed $life): string|float { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); try { $cost = self::validateCost($cost, true); $salvage = self::validateSalvage($salvage, true); $life = self::validateLife($life, true); } catch (Exception $e) { return $e->getMessage(); } if ($life === self::$zeroPointZero) { return ExcelError::DIV0(); } return ($cost - $salvage) / $life; } /** * SYD. * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * @param mixed $period Period * * @return float|string Result, or a string containing an error */ public static function SYD(mixed $cost, mixed $salvage, mixed $life, mixed $period): string|float { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); try { $cost = self::validateCost($cost, true); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); } catch (Exception $e) { return $e->getMessage(); } if ($period > $life) { return ExcelError::NAN(); } $syd = (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); return $syd; } private static function validateCost(mixed $cost, bool $negativeValueAllowed = false): float { $cost = FinancialValidations::validateFloat($cost); if ($cost < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $cost; } private static function validateSalvage(mixed $salvage, bool $negativeValueAllowed = false): float { $salvage = FinancialValidations::validateFloat($salvage); if ($salvage < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $salvage; } private static function validateLife(mixed $life, bool $negativeValueAllowed = false): float { $life = FinancialValidations::validateFloat($life); if ($life < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $life; } private static function validatePeriod(mixed $period, bool $negativeValueAllowed = false): float { $period = FinancialValidations::validateFloat($period); if ($period <= 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $period; } private static function validateMonth(mixed $month): int { $month = FinancialValidations::validateInt($month); if ($month < 1) { throw new Exception(ExcelError::NAN()); } return $month; } private static function validateFactor(mixed $factor): float { $factor = FinancialValidations::validateFloat($factor); if ($factor <= 0.0) { throw new Exception(ExcelError::NAN()); } return $factor; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Dollar.php ================================================ |string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function format(mixed $number, mixed $precision = 2) { return Format::DOLLAR($number, $precision); } /** * DOLLARDE. * * Converts a dollar price expressed as an integer part and a fraction * part into a dollar price expressed as a decimal number. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARDE(fractional_dollar,fraction) * * @param mixed $fractionalDollar Fractional Dollar * Or can be an array of values * @param mixed $fraction Fraction * Or can be an array of values * * @return array|float|string */ public static function decimal(mixed $fractionalDollar = null, mixed $fraction = 0): array|string|float { if (is_array($fractionalDollar) || is_array($fraction)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $fractionalDollar, $fraction); } try { $fractionalDollar = FinancialValidations::validateFloat( Functions::flattenSingleValue($fractionalDollar) ?? 0.0 ); $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); } catch (Exception $e) { return $e->getMessage(); } // Additional parameter validations if ($fraction < 0) { return ExcelError::NAN(); } if ($fraction == 0) { return ExcelError::DIV0(); } $dollars = ($fractionalDollar < 0) ? ceil($fractionalDollar) : floor($fractionalDollar); $cents = fmod($fractionalDollar, 1.0); $cents /= $fraction; $cents *= 10 ** ceil(log10($fraction)); return $dollars + $cents; } /** * DOLLARFR. * * Converts a dollar price expressed as a decimal number into a dollar price * expressed as a fraction. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARFR(decimal_dollar,fraction) * * @param mixed $decimalDollar Decimal Dollar * Or can be an array of values * @param mixed $fraction Fraction * Or can be an array of values * * @return array|float|string */ public static function fractional(mixed $decimalDollar = null, mixed $fraction = 0): array|string|float { if (is_array($decimalDollar) || is_array($fraction)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $decimalDollar, $fraction); } try { $decimalDollar = FinancialValidations::validateFloat( Functions::flattenSingleValue($decimalDollar) ?? 0.0 ); $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); } catch (Exception $e) { return $e->getMessage(); } // Additional parameter validations if ($fraction < 0) { return ExcelError::NAN(); } if ($fraction == 0) { return ExcelError::DIV0(); } $dollars = ($decimalDollar < 0.0) ? ceil($decimalDollar) : floor($decimalDollar); $cents = fmod($decimalDollar, 1); $cents *= $fraction; $cents *= 10 ** (-ceil(log10($fraction))); return $dollars + $cents; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/FinancialValidations.php ================================================ 4)) { throw new Exception(ExcelError::NAN()); } return $basis; } public static function validatePrice(mixed $price): float { $price = self::validateFloat($price); if ($price < 0.0) { throw new Exception(ExcelError::NAN()); } return $price; } public static function validateParValue(mixed $parValue): float { $parValue = self::validateFloat($parValue); if ($parValue < 0.0) { throw new Exception(ExcelError::NAN()); } return $parValue; } public static function validateYield(mixed $yield): float { $yield = self::validateFloat($yield); if ($yield < 0.0) { throw new Exception(ExcelError::NAN()); } return $yield; } public static function validateDiscount(mixed $discount): float { $discount = self::validateFloat($discount); if ($discount <= 0.0) { throw new Exception(ExcelError::NAN()); } return $discount; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Helpers.php ================================================ format('d') === $date->format('t'); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/InterestRate.php ================================================ getMessage(); } if ($nominalRate <= 0 || $periodsPerYear < 1) { return ExcelError::NAN(); } return ((1 + $nominalRate / $periodsPerYear) ** $periodsPerYear) - 1; } /** * NOMINAL. * * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. * * @param mixed $effectiveRate Effective interest rate as a float * @param mixed $periodsPerYear Integer number of compounding payments per year * * @return float|string Result, or a string containing an error */ public static function nominal(mixed $effectiveRate = 0, mixed $periodsPerYear = 0): string|float { $effectiveRate = Functions::flattenSingleValue($effectiveRate); $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); try { $effectiveRate = FinancialValidations::validateFloat($effectiveRate); $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); } catch (Exception $e) { return $e->getMessage(); } if ($effectiveRate <= 0 || $periodsPerYear < 1) { return ExcelError::NAN(); } // Calculate return $periodsPerYear * (($effectiveRate + 1) ** (1 / $periodsPerYear) - 1); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php ================================================ getMessage(); } $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return StringHelper::convertToString($daysBetweenIssueAndSettlement); } $daysBetweenFirstInterestAndSettlement = Functions::scalar(YearFrac::fraction($firstInterest, $settlement, $basis)); if (!is_numeric($daysBetweenFirstInterestAndSettlement)) { // return date error return StringHelper::convertToString($daysBetweenFirstInterestAndSettlement); } return $parValue * $rate * $daysBetweenIssueAndSettlement; } /** * ACCRINTM. * * Returns the accrued interest for a security that pays interest at maturity. * * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * * @param mixed $issue The security's issue date * @param mixed $settlement The security's settlement (or maturity) date * @param mixed $rate The security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit parValue, ACCRINT uses $1,000. * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function atMaturity( mixed $issue, mixed $settlement, mixed $rate, mixed $parValue = 1000, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $issue = Functions::flattenSingleValue($issue); $settlement = Functions::flattenSingleValue($settlement); $rate = Functions::flattenSingleValue($rate); $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $issue = SecurityValidations::validateIssueDate($issue); $settlement = SecurityValidations::validateSettlementDate($settlement); SecurityValidations::validateSecurityPeriod($issue, $settlement); $rate = SecurityValidations::validateRate($rate); $parValue = SecurityValidations::validateParValue($parValue); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return StringHelper::convertToString($daysBetweenIssueAndSettlement); } return $parValue * $rate * $daysBetweenIssueAndSettlement; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php ================================================ getMessage(); } $dsc = (float) Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); $e = (float) Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); $n = (int) Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); $a = (float) Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); $baseYF = 1.0 + ($yield / $frequency); $rfp = 100 * ($rate / $frequency); $de = $dsc / $e; $result = $redemption / $baseYF ** (--$n + $de); for ($k = 0; $k <= $n; ++$k) { $result += $rfp / ($baseYF ** ($k + $de)); } $result -= $rfp * ($a / $e); return $result; } /** * PRICEDISC. * * Returns the price per $100 face value of a discounted security. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $discount The security's discount rate * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function priceDiscounted( mixed $settlement, mixed $maturity, mixed $discount, mixed $redemption, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); $redemption = Functions::flattenSingleValue($redemption); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $discount = SecurityValidations::validateDiscount($discount); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenSettlementAndMaturity); } return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); } /** * PRICEMAT. * * Returns the price per $100 face value of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the * security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $yield The security's annual yield * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function priceAtMaturity( mixed $settlement, mixed $maturity, mixed $issue, mixed $rate, mixed $yield, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $issue = Functions::flattenSingleValue($issue); $rate = Functions::flattenSingleValue($rate); $yield = Functions::flattenSingleValue($yield); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $issue = SecurityValidations::validateIssueDate($issue); $rate = SecurityValidations::validateRate($rate); $yield = SecurityValidations::validateYield($yield); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return StringHelper::convertToString($daysBetweenIssueAndSettlement); } $daysBetweenIssueAndSettlement *= $daysPerYear; $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); if (!is_numeric($daysBetweenIssueAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenIssueAndMaturity); } $daysBetweenIssueAndMaturity *= $daysPerYear; $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenSettlementAndMaturity); } $daysBetweenSettlementAndMaturity *= $daysPerYear; return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); } /** * RECEIVED. * * Returns the amount received at maturity for a fully invested Security. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment The amount invested in the security * @param mixed $discount The security's discount rate * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function received( mixed $settlement, mixed $maturity, mixed $investment, mixed $discount, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $investment = Functions::flattenSingleValue($investment); $discount = Functions::flattenSingleValue($discount); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $investment = SecurityValidations::validateFloat($investment); $discount = SecurityValidations::validateDiscount($discount); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($investment <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString(Functions::scalar($daysBetweenSettlementAndMaturity)); } return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php ================================================ getMessage(); } if ($price <= 0.0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenSettlementAndMaturity); } return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; } /** * INTRATE. * * Returns the interest rate for a fully invested security. * * Excel Function: * INTRATE(settlement,maturity,investment,redemption[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment the amount invested in the security * @param mixed $redemption the amount to be received at maturity * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function interest( mixed $settlement, mixed $maturity, mixed $investment, mixed $redemption, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): float|string { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $investment = Functions::flattenSingleValue($investment); $redemption = Functions::flattenSingleValue($redemption); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $investment = SecurityValidations::validateFloat($investment); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($investment <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenSettlementAndMaturity); } return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php ================================================ = $maturity) { throw new Exception(ExcelError::NAN()); } } public static function validateRedemption(mixed $redemption): float { $redemption = self::validateFloat($redemption); if ($redemption <= 0.0) { throw new Exception(ExcelError::NAN()); } return $redemption; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php ================================================ getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenSettlementAndMaturity); } $daysBetweenSettlementAndMaturity *= $daysPerYear; return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } /** * YIELDMAT. * * Returns the annual yield of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $price The security's price per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function yieldAtMaturity( mixed $settlement, mixed $maturity, mixed $issue, mixed $rate, mixed $price, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $issue = Functions::flattenSingleValue($issue); $rate = Functions::flattenSingleValue($rate); $price = Functions::flattenSingleValue($price); $basis = Functions::flattenSingleValue($basis) ?? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD; try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $issue = SecurityValidations::validateIssueDate($issue); $rate = SecurityValidations::validateRate($rate); $price = SecurityValidations::validatePrice($price); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return StringHelper::convertToString($daysBetweenIssueAndSettlement); } $daysBetweenIssueAndSettlement *= $daysPerYear; $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); if (!is_numeric($daysBetweenIssueAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenIssueAndMaturity); } $daysBetweenIssueAndMaturity *= $daysPerYear; $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return StringHelper::convertToString($daysBetweenSettlementAndMaturity); } $daysBetweenSettlementAndMaturity *= $daysPerYear; return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php ================================================ getMessage(); } if ($discount <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); } /** * TBILLPRICE. * * Returns the price per $100 face value for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function price(mixed $settlement, mixed $maturity, mixed $discount): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $discount = FinancialValidations::validateFloat($discount); } catch (Exception $e) { return $e->getMessage(); } if ($discount <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); if ($price < 0.0) { return ExcelError::NAN(); } return $price; } /** * TBILLYIELD. * * Returns the yield for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date when * the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param float|string $price The Treasury bill's price per $100 face value */ public static function yield(mixed $settlement, mixed $maturity, $price): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $price = FinancialValidations::validatePrice($price); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/FormulaParser.php ================================================ <'; const OPERATORS_POSTFIX = '%'; /** * Formula. */ private string $formula; /** * Tokens. * * @var FormulaToken[] */ private array $tokens = []; /** * Create a new FormulaParser. * * @param ?string $formula Formula to parse */ public function __construct(?string $formula = '') { // Check parameters if ($formula === null) { throw new Exception('Invalid parameter passed: formula'); } // Initialise values $this->formula = trim($formula); // Parse! $this->parseToTokens(); } /** * Get Formula. */ public function getFormula(): string { return $this->formula; } /** * Get Token. * * @param int $id Token id */ public function getToken(int $id = 0): FormulaToken { if (isset($this->tokens[$id])) { return $this->tokens[$id]; } throw new Exception("Token with id $id does not exist."); } /** * Get Token count. */ public function getTokenCount(): int { return count($this->tokens); } /** * Get Tokens. * * @return FormulaToken[] */ public function getTokens(): array { return $this->tokens; } /** * Parse to tokens. */ private function parseToTokens(): void { // No attempt is made to verify formulas; assumes formulas are derived from Excel, where // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. // Check if the formula has a valid starting = $formulaLength = strlen($this->formula); if ($formulaLength < 2 || $this->formula[0] != '=') { return; } // Helper variables $tokens1 = $tokens2 = $stack = []; $inString = $inPath = $inRange = $inError = false; $nextToken = null; //$token = $previousToken = null; $index = 1; $value = ''; $ERRORS = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A']; $COMPARATORS_MULTI = ['>=', '<=', '<>']; while ($index < $formulaLength) { // state-dependent character evaluation (order is important) // double-quoted strings // embeds are doubled // end marks token if ($inString) { if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_DOUBLE)) { $value .= self::QUOTE_DOUBLE; ++$index; } else { $inString = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT); $value = ''; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // single-quoted strings (links) // embeds are double // end does not mark a token if ($inPath) { if ($this->formula[$index] == self::QUOTE_SINGLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_SINGLE)) { $value .= self::QUOTE_SINGLE; ++$index; } else { $inPath = false; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // bracked strings (R1C1 range index or linked workbook name) // no embeds (changed to "()" by Excel) // end does not mark a token if ($inRange) { if ($this->formula[$index] == self::BRACKET_CLOSE) { $inRange = false; } $value .= $this->formula[$index]; ++$index; continue; } // error values // end marks a token, determined from absolute list of values if ($inError) { $value .= $this->formula[$index]; ++$index; if (in_array($value, $ERRORS)) { $inError = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR); $value = ''; } continue; } // scientific notation check if (str_contains(self::OPERATORS_SN, $this->formula[$index])) { if (strlen($value) > 1) { if (preg_match('/^[1-9]{1}(\.\d+)?E{1}$/', $this->formula[$index]) != 0) { $value .= $this->formula[$index]; ++$index; continue; } } } // independent character evaluation (order not important) // establish state-dependent character evaluations if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inString = true; ++$index; continue; } if ($this->formula[$index] == self::QUOTE_SINGLE) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inPath = true; ++$index; continue; } if ($this->formula[$index] == self::BRACKET_OPEN) { $inRange = true; $value .= self::BRACKET_OPEN; ++$index; continue; } if ($this->formula[$index] == self::ERROR_START) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inError = true; $value .= self::ERROR_START; ++$index; continue; } // mark start and end of arrays and array rows if ($this->formula[$index] == self::BRACE_OPEN) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $tmp = new FormulaToken('ARRAY', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::SEMICOLON) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; $tmp = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); $tokens1[] = $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::BRACE_CLOSE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // trim white-space if ($this->formula[$index] == self::WHITESPACE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken('', FormulaToken::TOKEN_TYPE_WHITESPACE); ++$index; while (($this->formula[$index] == self::WHITESPACE) && ($index < $formulaLength)) { ++$index; } continue; } // multi-character comparators if (($index + 2) <= $formulaLength) { if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken(substr($this->formula, $index, 2), FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_LOGICAL); $index += 2; continue; } } // standard infix operators if (str_contains(self::OPERATORS_INFIX, $this->formula[$index])) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORINFIX); ++$index; continue; } // standard postfix operators (only one) if (str_contains(self::OPERATORS_POSTFIX, $this->formula[$index])) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); ++$index; continue; } // start subexpression or function if ($this->formula[$index] == self::PAREN_OPEN) { if ($value !== '') { $tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $value = ''; } else { $tmp = new FormulaToken('', FormulaToken::TOKEN_TYPE_SUBEXPRESSION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; } ++$index; continue; } // function, subexpression, or array parameters, or operand unions if ($this->formula[$index] == self::COMMA) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $stack[] = $tmp; if ($tmp->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_UNION); } else { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); } ++$index; continue; } // stop subexpression if ($this->formula[$index] == self::PAREN_CLOSE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // token accumulation $value .= $this->formula[$index]; ++$index; } // dump remaining accumulation if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); } // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections $tokenCount = count($tokens1); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens1[$i]; $previousToken = $tokens1[$i - 1] ?? null; $nextToken = $tokens1[$i + 1] ?? null; if ($token->getTokenType() != FormulaToken::TOKEN_TYPE_WHITESPACE) { $tokens2[] = $token; continue; } if ($previousToken === null) { continue; } if ( !( (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } if ($nextToken === null) { continue; } if ( !( (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || ($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } $tokens2[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_INTERSECTION); } // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names $this->tokens = []; $tokenCount = count($tokens2); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens2[$i]; $previousToken = $tokens2[$i - 1] ?? null; if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') { if ($i == 0) { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } elseif ( (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') { if ($i == 0) { continue; } elseif ( (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { continue; } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (str_contains('<>=', substr($token->getValue(), 0, 1))) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } elseif ($token->getValue() == '&') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (!is_numeric($token->getValue())) { if (strtoupper($token->getValue()) == 'TRUE' || strtoupper($token->getValue()) == 'FALSE') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE); } } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_NUMBER); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if ($token->getValue() !== '') { if (str_starts_with($token->getValue(), '@')) { $token->setValue(substr($token->getValue(), 1)); } } } $this->tokens[] = $token; } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/FormulaToken.php ================================================ value = $value; $this->tokenType = $tokenType; $this->tokenSubType = $tokenSubType; } /** * Get Value. */ public function getValue(): string { return $this->value; } /** * Set Value. */ public function setValue(string $value): void { $this->value = $value; } /** * Get Token Type (represented by TOKEN_TYPE_*). */ public function getTokenType(): string { return $this->tokenType; } /** * Set Token Type (represented by TOKEN_TYPE_*). */ public function setTokenType(string $value): void { $this->tokenType = $value; } /** * Get Token SubType (represented by TOKEN_SUBTYPE_*). */ public function getTokenSubType(): string { return $this->tokenSubType; } /** * Set Token SubType (represented by TOKEN_SUBTYPE_*). */ public function setTokenSubType(string $value): void { $this->tokenSubType = $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/FunctionArray.php ================================================ */ protected static array $phpSpreadsheetFunctions = [ 'ABS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Absolute::class, 'evaluate'], 'argumentCount' => '1', ], 'ACCRINT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'], 'argumentCount' => '4-8', ], 'ACCRINTM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'], 'argumentCount' => '3-5', ], 'ACOS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'], 'argumentCount' => '1', ], 'ACOSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'], 'argumentCount' => '1', ], 'ACOT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'], 'argumentCount' => '1', ], 'ACOTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'], 'argumentCount' => '1', ], 'ADDRESS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Address::class, 'cell'], 'argumentCount' => '2-5', ], 'AGGREGATE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3+', ], 'AMORDEGRC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'], 'argumentCount' => '6,7', ], 'AMORLINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORLINC'], 'argumentCount' => '6,7', ], 'ANCHORARRAY' => [ 'category' => Category::CATEGORY_MICROSOFT_INTERNAL, 'functionCall' => [Internal\ExcelArrayPseudoFunctions::class, 'anchorArray'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'AND' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalAnd'], 'argumentCount' => '1+', ], 'ARABIC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Arabic::class, 'evaluate'], 'argumentCount' => '1', ], 'AREAS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ARRAYTOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'fromArray'], 'argumentCount' => '1,2', ], 'ASC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ASIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'], 'argumentCount' => '1', ], 'ASINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'], 'argumentCount' => '1', ], 'ATAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'], 'argumentCount' => '1', ], 'ATAN2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'], 'argumentCount' => '2', ], 'ATANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'], 'argumentCount' => '1', ], 'AVEDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageDeviations'], 'argumentCount' => '1+', ], 'AVERAGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'average'], 'argumentCount' => '1+', ], 'AVERAGEA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageA'], 'argumentCount' => '1+', ], 'AVERAGEIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'], 'argumentCount' => '2,3', ], 'AVERAGEIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'], 'argumentCount' => '3+', ], 'BAHTTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Thai::class, 'getBahtText'], 'argumentCount' => '1', ], 'BASE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Base::class, 'evaluate'], 'argumentCount' => '2,3', ], 'BESSELI' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselI::class, 'BESSELI'], 'argumentCount' => '2', ], 'BESSELJ' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'], 'argumentCount' => '2', ], 'BESSELK' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselK::class, 'BESSELK'], 'argumentCount' => '2', ], 'BESSELY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselY::class, 'BESSELY'], 'argumentCount' => '2', ], 'BETADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'], 'argumentCount' => '3-5', ], 'BETA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4-6', ], 'BETAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BETA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BIN2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'], 'argumentCount' => '1', ], 'BIN2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'], 'argumentCount' => '1,2', ], 'BIN2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'], 'argumentCount' => '1,2', ], 'BINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST.RANGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'], 'argumentCount' => '3,4', ], 'BINOM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'BITAND' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITAND'], 'argumentCount' => '2', ], 'BITOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITOR'], 'argumentCount' => '2', ], 'BITXOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITXOR'], 'argumentCount' => '2', ], 'BITLSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'], 'argumentCount' => '2', ], 'BITRSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'], 'argumentCount' => '2', ], 'BYCOL' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'BYROW' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], 'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric ], 'CEILING.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'math'], 'argumentCount' => '1-3', ], // pseudo-function to help with Ods 'CEILING.ODS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'mathOds'], 'argumentCount' => '1-3', ], 'CEILING.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'precise'], 'argumentCount' => '1,2', ], // pseudo-function implemented in Ods 'CEILING.XCL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], 'argumentCount' => '2', ], 'CELL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'CHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'CHIDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHISQ.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'], 'argumentCount' => '3', ], 'CHISQ.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHIINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHISQ.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'], 'argumentCount' => '2', ], 'CHISQ.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHITEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHISQ.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHOOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'], 'argumentCount' => '2+', ], 'CHOOSECOLS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'chooseCols'], 'argumentCount' => '2+', ], 'CHOOSEROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'chooseRows'], 'argumentCount' => '2+', ], 'CLEAN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'nonPrintable'], 'argumentCount' => '1', ], 'CODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'COLUMN' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'COLUMNS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'], 'argumentCount' => '1', ], 'COMBIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'], 'argumentCount' => '2', ], 'COMBINA' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'], 'argumentCount' => '2', ], 'COMPLEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'COMPLEX'], 'argumentCount' => '2,3', ], 'CONCAT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONCATENATE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'actualCONCATENATE'], 'argumentCount' => '1+', 'passCellReference' => true, ], 'CONFIDENCE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.NORM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'CONVERT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'], 'argumentCount' => '3', ], 'CORREL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'COS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'], 'argumentCount' => '1', ], 'COSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'], 'argumentCount' => '1', ], 'COT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'], 'argumentCount' => '1', ], 'COTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'], 'argumentCount' => '1', ], 'COUNT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNT'], 'argumentCount' => '1+', ], 'COUNTA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTA'], 'argumentCount' => '1+', ], 'COUNTBLANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'], 'argumentCount' => '1', ], 'COUNTIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'], 'argumentCount' => '2', ], 'COUNTIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'], 'argumentCount' => '2+', ], 'COUPDAYBS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'], 'argumentCount' => '3,4', ], 'COUPDAYS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'], 'argumentCount' => '3,4', ], 'COUPDAYSNC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'], 'argumentCount' => '3,4', ], 'COUPNCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNCD'], 'argumentCount' => '3,4', ], 'COUPNUM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNUM'], 'argumentCount' => '3,4', ], 'COUPPCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPPCD'], 'argumentCount' => '3,4', ], 'COVAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'CRITBINOM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'CSC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'], 'argumentCount' => '1', ], 'CSCH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'], 'argumentCount' => '1', ], 'CUBEKPIMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBERPROPERTY' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBERANKEDMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESET' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESETCOUNT' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEVALUE' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUMIPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'], 'argumentCount' => '6', ], 'CUMPRINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'], 'argumentCount' => '6', ], 'DATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'], 'argumentCount' => '3', ], 'DATEDIF' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Difference::class, 'interval'], 'argumentCount' => '2,3', ], 'DATESTRING' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'DATEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'], 'argumentCount' => '1', ], 'DAVERAGE' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DAverage::class, 'evaluate'], 'argumentCount' => '3', ], 'DAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'day'], 'argumentCount' => '1', ], 'DAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days::class, 'between'], 'argumentCount' => '2', ], 'DAYS360' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days360::class, 'between'], 'argumentCount' => '2,3', ], 'DB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DB'], 'argumentCount' => '4,5', ], 'DBCS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'DCOUNT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCount::class, 'evaluate'], 'argumentCount' => '3', ], 'DCOUNTA' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCountA::class, 'evaluate'], 'argumentCount' => '3', ], 'DDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DDB'], 'argumentCount' => '4,5', ], 'DEC2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'DEC2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'], 'argumentCount' => '1,2', ], 'DEC2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'], 'argumentCount' => '1,2', ], 'DECIMAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'DEGREES' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toDegrees'], 'argumentCount' => '1', ], 'DELTA' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'DELTA'], 'argumentCount' => '1,2', ], 'DEVSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'sumSquares'], 'argumentCount' => '1+', ], 'DGET' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DGet::class, 'evaluate'], 'argumentCount' => '3', ], 'DISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'discount'], 'argumentCount' => '4,5', ], 'DMAX' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMax::class, 'evaluate'], 'argumentCount' => '3', ], 'DMIN' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMin::class, 'evaluate'], 'argumentCount' => '3', ], 'DOLLAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'DOLLAR'], 'argumentCount' => '1,2', ], 'DOLLARDE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'decimal'], 'argumentCount' => '2', ], 'DOLLARFR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'fractional'], 'argumentCount' => '2', ], 'DPRODUCT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DProduct::class, 'evaluate'], 'argumentCount' => '3', ], 'DROP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'drop'], 'argumentCount' => '2-3', ], 'DSTDEV' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDev::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEVP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDevP::class, 'evaluate'], 'argumentCount' => '3', ], 'DSUM' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DSum::class, 'evaluate'], 'argumentCount' => '3', ], 'DURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'DVAR' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVar::class, 'evaluate'], 'argumentCount' => '3', ], 'DVARP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVarP::class, 'evaluate'], 'argumentCount' => '3', ], 'ECMA.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'EDATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'adjust'], 'argumentCount' => '2', ], 'EFFECT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'effective'], 'argumentCount' => '2', ], 'ENCODEURL' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'urlEncode'], 'argumentCount' => '1', ], 'EOMONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'], 'argumentCount' => '2', ], 'ERF' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERF'], 'argumentCount' => '1,2', ], 'ERF.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'], 'argumentCount' => '1', ], 'ERFC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERFC.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERROR.TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ExcelError::class, 'type'], 'argumentCount' => '1', ], 'EVEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'even'], 'argumentCount' => '1', ], 'EXACT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'exact'], 'argumentCount' => '2', ], 'EXP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Exp::class, 'evaluate'], 'argumentCount' => '1', ], 'EXPAND' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'expand'], 'argumentCount' => '2-4', ], 'EXPONDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'EXPON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'FACT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'fact'], 'argumentCount' => '1', ], 'FACTDOUBLE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'factDouble'], 'argumentCount' => '1', ], 'FALSE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Boolean::class, 'FALSE'], 'argumentCount' => '0', ], 'FDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\F::class, 'distribution'], 'argumentCount' => '4', ], 'F.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'FILTER' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Filter::class, 'filter'], 'argumentCount' => '2-3', ], 'FILTERXML' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FIND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'FISHER' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'], 'argumentCount' => '1', ], 'FISHERINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'], 'argumentCount' => '1', ], 'FIXED' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'], 'argumentCount' => '1-3', ], 'FLOOR' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'floor'], 'argumentCount' => '1-2', // Excel requires 2, Ods/Gnumeric 1-2 ], 'FLOOR.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'math'], 'argumentCount' => '1-3', ], // pseudo-function to help with Ods 'FLOOR.ODS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'mathOds'], 'argumentCount' => '1-3', ], 'FLOOR.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'precise'], 'argumentCount' => '1-2', ], // pseudo-function implemented in Ods 'FLOOR.XCL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'floor'], 'argumentCount' => '2', ], 'FORECAST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORECAST.ETS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.ETS.CONFINT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.ETS.SEASONALITY' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'FORECAST.ETS.STAT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.LINEAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORMULATEXT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Formula::class, 'text'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'FREQUENCY' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'F.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'], 'argumentCount' => '3-5', ], 'FVSCHEDULE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'], 'argumentCount' => '2', ], 'GAMMA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'], 'argumentCount' => '1', ], 'GAMMADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMALN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAMMALN.PRECISE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAUSS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'], 'argumentCount' => '1', ], 'GCD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Gcd::class, 'evaluate'], 'argumentCount' => '1+', ], 'GEOMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'geometric'], 'argumentCount' => '1+', ], 'GESTEP' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'GESTEP'], 'argumentCount' => '1,2', ], 'GETPIVOTDATA' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'GROUPBY' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-7', ], 'GROWTH' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'GROWTH'], 'argumentCount' => '1-4', ], 'HARMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'], 'argumentCount' => '1+', ], 'HEX2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toBinary'], 'argumentCount' => '1,2', ], 'HEX2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'], 'argumentCount' => '1', ], 'HEX2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toOctal'], 'argumentCount' => '1,2', ], 'HLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\HLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'HOUR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'], 'argumentCount' => '1', ], 'HSTACK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Hstack::class, 'hstack'], 'argumentCount' => '1+', ], 'HYPERLINK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Hyperlink::class, 'set'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'HYPGEOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'], 'argumentCount' => '4', ], 'HYPGEOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5', ], 'IF' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'statementIf'], 'argumentCount' => '2-3', ], 'IFERROR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFERROR'], 'argumentCount' => '2', ], 'IFNA' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFNA'], 'argumentCount' => '2', ], 'IFS' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFS'], 'argumentCount' => '2+', ], 'IMABS' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'], 'argumentCount' => '1', ], 'IMAGINARY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'IMAGINARY'], 'argumentCount' => '1', ], 'IMARGUMENT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'], 'argumentCount' => '1', ], 'IMCONJUGATE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'], 'argumentCount' => '1', ], 'IMCOS' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'], 'argumentCount' => '1', ], 'IMCOSH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'], 'argumentCount' => '1', ], 'IMCOT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'], 'argumentCount' => '1', ], 'IMCSC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'], 'argumentCount' => '1', ], 'IMCSCH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'], 'argumentCount' => '1', ], 'IMDIV' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'], 'argumentCount' => '2', ], 'IMEXP' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'], 'argumentCount' => '1', ], 'IMLN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'], 'argumentCount' => '1', ], 'IMLOG10' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'], 'argumentCount' => '1', ], 'IMLOG2' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'], 'argumentCount' => '1', ], 'IMPOWER' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'], 'argumentCount' => '2', ], 'IMPRODUCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'], 'argumentCount' => '1+', ], 'IMREAL' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'IMREAL'], 'argumentCount' => '1', ], 'IMSEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'], 'argumentCount' => '1', ], 'IMSECH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'], 'argumentCount' => '1', ], 'IMSIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'], 'argumentCount' => '1', ], 'IMSINH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'], 'argumentCount' => '1', ], 'IMSQRT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'], 'argumentCount' => '1', ], 'IMSUB' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'], 'argumentCount' => '2', ], 'IMSUM' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'], 'argumentCount' => '1+', ], 'IMTAN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'], 'argumentCount' => '1', ], 'INDEX' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Matrix::class, 'index'], 'argumentCount' => '2-4', ], 'INDIRECT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'INFO' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Info::class, 'getInfo'], 'argumentCount' => '1', 'passCellReference' => true, ], 'INT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\IntClass::class, 'evaluate'], 'argumentCount' => '1', ], 'INTERCEPT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'INTERCEPT'], 'argumentCount' => '2', ], 'INTRATE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'interest'], 'argumentCount' => '4,5', ], 'IPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'], 'argumentCount' => '4-6', ], 'IRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'], 'argumentCount' => '1,2', ], 'ISBLANK' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isBlank'], 'argumentCount' => '1', ], 'ISERR' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isErr'], 'argumentCount' => '1', ], 'ISERROR' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isError'], 'argumentCount' => '1', ], 'ISEVEN' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isEven'], 'argumentCount' => '1', ], 'ISFORMULA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isFormula'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISLOGICAL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isLogical'], 'argumentCount' => '1', ], 'ISNA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isNa'], 'argumentCount' => '1', ], 'ISNONTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isNonText'], 'argumentCount' => '1', ], 'ISNUMBER' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isNumber'], 'argumentCount' => '1', ], 'ISO.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'ISODD' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isOdd'], 'argumentCount' => '1', ], 'ISOMITTED' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'ISOWEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'], 'argumentCount' => '1', ], 'ISPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'], 'argumentCount' => '4', ], 'ISREF' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isRef'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isText'], 'argumentCount' => '1', ], 'ISTHAIDIGIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'JIS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'KURT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'kurtosis'], 'argumentCount' => '1+', ], 'LAMBDA' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'LARGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Size::class, 'large'], 'argumentCount' => '2', ], 'LCM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Lcm::class, 'evaluate'], 'argumentCount' => '1+', ], 'LEFT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEFTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LENB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LET' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'LINEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'LINEST'], 'argumentCount' => '1-4', ], 'LN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'natural'], 'argumentCount' => '1', ], 'LOG' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'withBase'], 'argumentCount' => '1,2', ], 'LOG10' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'base10'], 'argumentCount' => '1', ], 'LOGEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'LOGEST'], 'argumentCount' => '1-4', ], 'LOGINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOGNORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'], 'argumentCount' => '3', ], 'LOGNORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'], 'argumentCount' => '4', ], 'LOGNORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Lookup::class, 'lookup'], 'argumentCount' => '2,3', ], 'LOWER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'lower'], 'argumentCount' => '1', ], 'MAKEARRAY' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'MAP' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'MATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'], 'argumentCount' => '2,3', ], 'MAX' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Maximum::class, 'max'], 'argumentCount' => '1+', ], 'MAXA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Maximum::class, 'maxA'], 'argumentCount' => '1+', ], 'MAXIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'MAXIFS'], 'argumentCount' => '3+', ], 'MDETERM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'], 'argumentCount' => '1', ], 'MDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'MEDIAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'median'], 'argumentCount' => '1+', ], 'MEDIANIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'MID' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Minimum::class, 'min'], 'argumentCount' => '1+', ], 'MINA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Minimum::class, 'minA'], 'argumentCount' => '1+', ], 'MINIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'MINIFS'], 'argumentCount' => '3+', ], 'MINUTE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'], 'argumentCount' => '1', ], 'MINVERSE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'], 'argumentCount' => '1', ], 'MIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'], 'argumentCount' => '3', ], 'MMULT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'], 'argumentCount' => '2', ], 'MOD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'mod'], 'argumentCount' => '2', ], 'MODE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MODE.MULT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'MODE.SNGL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'month'], 'argumentCount' => '1', ], 'MROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'multiple'], 'argumentCount' => '2', ], 'MULTINOMIAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'multinomial'], 'argumentCount' => '1+', ], 'MUNIT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'], 'argumentCount' => '1', ], 'N' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'asNumber'], 'argumentCount' => '1', ], 'NA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ExcelError::class, 'NA'], 'argumentCount' => '0', ], 'NEGBINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'], 'argumentCount' => '3', ], 'NEGBINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'NETWORKDAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'], 'argumentCount' => '2-3', ], 'NETWORKDAYS.INTL' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'NOMINAL' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'nominal'], 'argumentCount' => '2', ], 'NORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORMINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORMSDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'], 'argumentCount' => '1', ], 'NORM.S.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'], 'argumentCount' => '1,2', ], 'NORMSINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NORM.S.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NOT' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'NOT'], 'argumentCount' => '1', ], 'NOW' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Current::class, 'now'], 'argumentCount' => '0', ], 'NPER' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'], 'argumentCount' => '3-5', ], 'NPV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'presentValue'], 'argumentCount' => '2+', ], 'NUMBERSTRING' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'NUMBERVALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'NUMBERVALUE'], 'argumentCount' => '1+', ], 'OCT2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'OCT2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'], 'argumentCount' => '1', ], 'OCT2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toHex'], 'argumentCount' => '1,2', ], 'ODD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'odd'], 'argumentCount' => '1', ], 'ODDFPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '8,9', ], 'ODDFYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '8,9', ], 'ODDLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '7,8', ], 'ODDLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '7,8', ], 'OFFSET' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Offset::class, 'OFFSET'], 'argumentCount' => '3-5', 'passCellReference' => true, 'passByReference' => [true], ], 'OR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalOr'], 'argumentCount' => '1+', ], 'PDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'periods'], 'argumentCount' => '3', ], 'PEARSON' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'PERCENTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTILE.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'PERCENTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTRANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERCENTRANK.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'PERCENTRANK.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERMUT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Permutations::class, 'PERMUT'], 'argumentCount' => '2', ], 'PERMUTATIONA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'], 'argumentCount' => '2', ], 'PHONETIC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'PHI' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'PI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'pi', 'argumentCount' => '0', ], 'PMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'], 'argumentCount' => '3-5', ], 'POISSON' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POISSON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POWER' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'power'], 'argumentCount' => '2', ], 'PPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'], 'argumentCount' => '4-6', ], 'PRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'price'], 'argumentCount' => '6,7', ], 'PRICEDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'], 'argumentCount' => '4,5', ], 'PRICEMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'], 'argumentCount' => '5,6', ], 'PROB' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3,4', ], 'PRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'product'], 'argumentCount' => '1+', ], 'PROPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'proper'], 'argumentCount' => '1', ], 'PV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'], 'argumentCount' => '3-5', ], 'QUARTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUARTILE.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'QUARTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUOTIENT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'quotient'], 'argumentCount' => '2', ], 'RADIANS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toRadians'], 'argumentCount' => '1', ], 'RAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'rand'], 'argumentCount' => '0', ], 'RANDARRAY' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'randArray'], 'argumentCount' => '0-5', ], 'RANDBETWEEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'randBetween'], 'argumentCount' => '2', ], 'RANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RANK.AVG' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'RANK.EQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RATE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'], 'argumentCount' => '3-6', ], 'RECEIVED' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'received'], 'argumentCount' => '4-5', ], 'REDUCE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'REPLACE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPLACEB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'builtinREPT'], 'argumentCount' => '2', ], 'RIGHT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'RIGHTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'ROMAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Roman::class, 'evaluate'], 'argumentCount' => '1,2', ], 'ROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'round'], 'argumentCount' => '2', ], 'ROUNDBAHTDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'ROUNDBAHTUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'ROUNDDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'down'], 'argumentCount' => '2', ], 'ROUNDUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'up'], 'argumentCount' => '2', ], 'ROW' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'ROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'], 'argumentCount' => '1', ], 'RRI' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'], 'argumentCount' => '3', ], 'RSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'RSQ'], 'argumentCount' => '2', ], 'RTD' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SEARCH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SCAN' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'SEARCHB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Secant::class, 'sec'], 'argumentCount' => '1', ], 'SECH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Secant::class, 'sech'], 'argumentCount' => '1', ], 'SECOND' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'second'], 'argumentCount' => '1', ], 'SEQUENCE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'sequence'], 'argumentCount' => '1-4', ], 'SERIESSUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'], 'argumentCount' => '4', ], 'SHEET' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '0,1', ], 'SHEETS' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '0,1', ], 'SIGN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sign::class, 'evaluate'], 'argumentCount' => '1', ], 'SIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'sin'], 'argumentCount' => '1', ], 'SINGLE' => [ 'category' => Category::CATEGORY_MICROSOFT_INTERNAL, 'functionCall' => [Internal\ExcelArrayPseudoFunctions::class, 'single'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'SINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'], 'argumentCount' => '1', ], 'SKEW' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'skew'], 'argumentCount' => '1+', ], 'SKEW.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SLN' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'SLN'], 'argumentCount' => '3', ], 'SLOPE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'SLOPE'], 'argumentCount' => '2', ], 'SMALL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Size::class, 'small'], 'argumentCount' => '2', ], 'SORT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Sort::class, 'sort'], 'argumentCount' => '1-4', ], 'SORTBY' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Sort::class, 'sortBy'], 'argumentCount' => '2+', ], 'SQRT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sqrt::class, 'sqrt'], 'argumentCount' => '1', ], 'SQRTPI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sqrt::class, 'pi'], 'argumentCount' => '1', ], 'STANDARDIZE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Standardize::class, 'execute'], 'argumentCount' => '3', ], 'STDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'], 'argumentCount' => '1+', ], 'STDEVP' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVPA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'], 'argumentCount' => '1+', ], 'STEYX' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'STEYX'], 'argumentCount' => '2', ], 'SUBSTITUTE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'substitute'], 'argumentCount' => '3,4', ], 'SUBTOTAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Subtotal::class, 'evaluate'], 'argumentCount' => '2+', 'passCellReference' => true, ], 'SUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'], 'argumentCount' => '1+', ], 'SUMIF' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Statistical\Conditional::class, 'SUMIF'], 'argumentCount' => '2,3', ], 'SUMIFS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Statistical\Conditional::class, 'SUMIFS'], 'argumentCount' => '3+', ], 'SUMPRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sum::class, 'product'], 'argumentCount' => '1+', ], 'SUMSQ' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'], 'argumentCount' => '1+', ], 'SUMX2MY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'], 'argumentCount' => '2', ], 'SUMX2PY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'], 'argumentCount' => '2', ], 'SUMXMY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'], 'argumentCount' => '2', ], 'SWITCH' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'statementSwitch'], 'argumentCount' => '3+', ], 'SYD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'SYD'], 'argumentCount' => '4', ], 'T' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'test'], 'argumentCount' => '1', ], 'TAKE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'take'], 'argumentCount' => '2-3', ], 'TAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'], 'argumentCount' => '1', ], 'TANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'], 'argumentCount' => '1', ], 'TBILLEQ' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'], 'argumentCount' => '3', ], 'TBILLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'price'], 'argumentCount' => '3', ], 'TBILLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'yield'], 'argumentCount' => '3', ], 'TDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'], 'argumentCount' => '3', ], 'T.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'tDotDist'], 'argumentCount' => '3', ], 'T.DIST.2T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'tDotDistDot2T'], 'argumentCount' => '2', ], 'T.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'tDotDistDotRT'], 'argumentCount' => '2', ], 'TEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'TEXTFORMAT'], 'argumentCount' => '2', ], 'TEXTAFTER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'after'], 'argumentCount' => '2-6', ], 'TEXTBEFORE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'before'], 'argumentCount' => '2-6', ], 'TEXTJOIN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'], 'argumentCount' => '3+', ], 'TEXTSPLIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'split'], 'argumentCount' => '2-6', ], 'THAIDAYOFWEEK' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIDIGIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIMONTHOFYEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAINUMSOUND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAINUMSTRING' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAISTRINGLENGTH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIYEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'TIME' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'], 'argumentCount' => '3', ], 'TIMEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'], 'argumentCount' => '1', ], 'TINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'tDotInv'], 'argumentCount' => '2', ], 'T.INV.2T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'TODAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Current::class, 'today'], 'argumentCount' => '0', ], 'TOCOL' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\TorowTocol::class, 'tocol'], 'argumentCount' => '1-3', ], 'TOROW' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\TorowTocol::class, 'torow'], 'argumentCount' => '1-3', ], 'TRANSPOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Matrix::class, 'transpose'], 'argumentCount' => '1', ], 'TREND' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'TREND'], 'argumentCount' => '1-4', ], 'TRIM' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'spaces'], 'argumentCount' => '1', ], 'TRIMMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'trim'], 'argumentCount' => '2', ], 'TRUE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Boolean::class, 'TRUE'], 'argumentCount' => '0', ], 'TRUNC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trunc::class, 'evaluate'], 'argumentCount' => '1,2', ], 'TTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'T.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'type'], 'argumentCount' => '1', ], 'UNICHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'characterUnicode'], 'argumentCount' => '1', ], 'UNICODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'codeUnicode'], 'argumentCount' => '1', ], 'UNIQUE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Unique::class, 'unique'], 'argumentCount' => '1+', ], 'UPPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'upper'], 'argumentCount' => '1', ], 'USDOLLAR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'format'], 'argumentCount' => '2', ], 'VALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'VALUE'], 'argumentCount' => '1', ], 'VALUETOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'valueToText'], 'argumentCount' => '1,2', ], 'VAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VAR.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VAR.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VARA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARA'], 'argumentCount' => '1+', ], 'VARP' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VARPA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARPA'], 'argumentCount' => '1+', ], 'VDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5-7', ], 'VLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\VLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'VSTACK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Vstack::class, 'vstack'], 'argumentCount' => '1+', ], 'WEBSERVICE' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'webService'], 'argumentCount' => '1', 'passCellReference' => true, ], 'WEEKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'day'], 'argumentCount' => '1,2', ], 'WEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'number'], 'argumentCount' => '1,2', ], 'WEIBULL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WEIBULL.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WORKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\WorkDay::class, 'date'], 'argumentCount' => '2-3', ], 'WORKDAY.INTL' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'WRAPCOLS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'WRAPROWS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'XIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'], 'argumentCount' => '2,3', ], 'XLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'XNPV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'], 'argumentCount' => '3', ], 'XMATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'XOR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalXor'], 'argumentCount' => '1+', ], 'YEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'year'], 'argumentCount' => '1', ], 'YEARFRAC' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'], 'argumentCount' => '2,3', ], 'YIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '6,7', ], 'YIELDDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'], 'argumentCount' => '4,5', ], 'YIELDMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'], 'argumentCount' => '5,6', ], 'ZTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], 'Z.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], ]; } ================================================ FILE: src/PhpSpreadsheet/Calculation/Functions.php ================================================ 0); } public static function isValue(mixed $idx): bool { $idx = StringHelper::convertToString($idx); return substr_count($idx, '.') === 0; } public static function isCellValue(mixed $idx): bool { $idx = StringHelper::convertToString($idx); return substr_count($idx, '.') > 1; } public static function ifCondition(mixed $condition): string { $condition = self::flattenSingleValue($condition); if ($condition === '' || $condition === null) { return '=""'; } if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='], true)) { $condition = self::operandSpecialHandling($condition); if (is_bool($condition)) { return '=' . ($condition ? 'TRUE' : 'FALSE'); } if (!is_numeric($condition)) { if ($condition !== '""') { // Not an empty string // Escape any quotes in the string value $condition = (string) preg_replace('/"/ui', '""', $condition); } $condition = Calculation::wrapResult(strtoupper($condition)); } return str_replace('""""', '""', '=' . StringHelper::convertToString($condition)); } $operator = $operand = ''; if (1 === preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches)) { [, $operator, $operand] = $matches; } $operand = (string) self::operandSpecialHandling($operand); if (is_numeric(trim($operand, '"'))) { $operand = trim($operand, '"'); } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') { $operand = str_replace('"', '""', $operand); $operand = Calculation::wrapResult(strtoupper($operand)); $operand = StringHelper::convertToString($operand); } return str_replace('""""', '""', $operator . $operand); } private static function operandSpecialHandling(mixed $operand): bool|float|int|string { if (is_numeric($operand) || is_bool($operand)) { return $operand; } $operand = StringHelper::convertToString($operand); if (strtoupper($operand) === Calculation::getTRUE() || strtoupper($operand) === Calculation::getFALSE()) { return strtoupper($operand); } // Check for percentage if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $operand)) { return ((float) rtrim($operand, '%')) / 100; } // Check for dates if (($dateValueOperand = Date::stringToExcel($operand)) !== false) { return $dateValueOperand; } return $operand; } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * * @param mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArray(mixed $array): array { if (!is_array($array)) { return (array) $array; } $flattened = []; $stack = array_values($array); while (!empty($stack)) { $value = array_shift($stack); if (is_array($value)) { array_unshift($stack, ...array_values($value)); } else { $flattened[] = $value; } } return $flattened; } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * Same as above but argument is specified in ... format. * * @param mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArray2(mixed ...$array): array { $flattened = []; $stack = array_values($array); while (!empty($stack)) { $value = array_shift($stack); if (is_array($value)) { array_unshift($stack, ...array_values($value)); } else { $flattened[] = $value; } } return $flattened; } public static function scalar(mixed $value): mixed { if (!is_array($value)) { return $value; } do { $value = array_pop($value); } while (is_array($value)); return $value; } /** * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing. * * @param array|mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArrayIndexed($array): array { if (!is_array($array)) { return (array) $array; } $arrayValues = []; foreach ($array as $k1 => $value) { if (is_array($value)) { foreach ($value as $k2 => $val) { if (is_array($val)) { foreach ($val as $k3 => $v) { $arrayValues[$k1 . '.' . $k2 . '.' . $k3] = $v; } } else { $arrayValues[$k1 . '.' . $k2] = $val; } } } else { $arrayValues[$k1] = $value; } } return $arrayValues; } /** * Convert an array to a single scalar value by extracting the first element. * * @param mixed $value Array or scalar value */ public static function flattenSingleValue(mixed $value): mixed { while (is_array($value)) { $value = array_shift($value); } return $value; } public static function expandDefinedName(string $coordinate, Cell $cell): string { $worksheet = $cell->getWorksheet(); $spreadsheet = $worksheet->getParentOrThrow(); // Uppercase coordinate $pCoordinatex = strtoupper($coordinate); // Eliminate leading equal sign $pCoordinatex = (string) preg_replace('/^=/', '', $pCoordinatex); $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet); if ($defined !== null) { $worksheet2 = $defined->getWorkSheet(); if (!$defined->isFormula() && $worksheet2 !== null) { $coordinate = "'" . $worksheet2->getTitle() . "'!" . (string) preg_replace('/^=/', '', str_replace('$', '', $defined->getValue())); } } return $coordinate; } public static function trimTrailingRange(string $coordinate): string { return (string) preg_replace('/:[\w\$]+$/', '', $coordinate); } public static function trimSheetFromCellReference(string $coordinate): string { if (str_contains($coordinate, '!')) { $coordinate = substr($coordinate, strrpos($coordinate, '!') + 1); } return $coordinate; } /** @param mixed[] $array */ public static function convertArrayToCellRange(array $array): string { $retVal = ''; $lastRow = $lastColumn = $firstRow = $firstColumn = 0; foreach ($array as $rowkey => $row) { if (!is_array($row) || !is_int($rowkey) || $rowkey < 1) { $firstRow = 0; break; } if ($firstRow > $rowkey || $firstRow === 0) { $firstRow = $rowkey; } if ($lastRow < $rowkey) { $lastRow = $rowkey; } foreach ($row as $colkey => $cellValue) { if (!preg_match('/^[A-Z]{1,3}$/', $colkey)) { $firstRow = 0; break 2; } $column = Coordinate::columnIndexFromString($colkey); if ($firstColumn > $column || $firstColumn === 0) { $firstColumn = $column; } if ($lastColumn < $column) { $lastColumn = $column; } } } if ($firstRow > 0 && $firstColumn > 0 && ($firstRow !== $lastRow || $firstColumn !== $lastColumn)) { $retVal = Coordinate::stringFromColumnIndex($firstColumn) . $firstRow . ':' . Coordinate::stringFromColumnIndex($lastColumn) . $lastRow; } return $retVal; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Information/ErrorValue.php ================================================ |bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isErr(mixed $value = ''): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return self::isError($value) && (!self::isNa(($value))); } /** * IS_ERROR. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isError(mixed $value = '', bool $tryNotImplemented = false): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_string($value)) { return false; } if ($tryNotImplemented && $value === Functions::NOT_YET_IMPLEMENTED) { return true; } return in_array($value, ExcelError::ERROR_CODES, true); } /** * IS_NA. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNa(mixed $value = ''): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return $value === ExcelError::NA(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Information/ExcelError.php ================================================ */ public const ERROR_CODES = [ 'null' => '#NULL!', // 1 'divisionbyzero' => '#DIV/0!', // 2 'value' => '#VALUE!', // 3 'reference' => '#REF!', // 4 'name' => '#NAME?', // 5 'num' => '#NUM!', // 6 'na' => '#N/A', // 7 'gettingdata' => '#GETTING_DATA', // 8 'spill' => '#SPILL!', // 9 'connect' => '#CONNECT!', //10 'blocked' => '#BLOCKED!', //11 'unknown' => '#UNKNOWN!', //12 'field' => '#FIELD!', //13 'calculation' => '#CALC!', //14 ]; public static function throwError(mixed $value): string { return in_array($value, self::ERROR_CODES, true) ? $value : self::ERROR_CODES['value']; } /** * ERROR_TYPE. * * @param mixed $value Value to check * * @return array|int|string */ public static function type(mixed $value = ''): array|int|string { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } $i = 1; foreach (self::ERROR_CODES as $errorCode) { if ($value === $errorCode) { return $i; } ++$i; } return self::NA(); } /** * NULL. * * Returns the error value #NULL! * * @return string #NULL! */ public static function null(): string { return self::ERROR_CODES['null']; } /** * NaN. * * Returns the error value #NUM! * * @return string #NUM! */ public static function NAN(): string { return self::ERROR_CODES['num']; } /** * REF. * * Returns the error value #REF! * * @return string #REF! */ public static function REF(): string { return self::ERROR_CODES['reference']; } /** * NA. * * Excel Function: * =NA() * * Returns the error value #N/A * #N/A is the error value that means "no value is available." * * @return string #N/A! */ public static function NA(): string { return self::ERROR_CODES['na']; } /** * VALUE. * * Returns the error value #VALUE! * * @return string #VALUE! */ public static function VALUE(): string { return self::ERROR_CODES['value']; } /** * NAME. * * Returns the error value #NAME? * * @return string #NAME? */ public static function NAME(): string { return self::ERROR_CODES['name']; } /** * DIV0. * * @return string #DIV/0! */ public static function DIV0(): string { return self::ERROR_CODES['divisionbyzero']; } /** * CALC. * * @return string #CALC! */ public static function CALC(): string { return self::ERROR_CODES['calculation']; } /** * SPILL. * * @return string #SPILL! */ public static function SPILL(): string { return self::ERROR_CODES['spill']; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Information/Info.php ================================================ '/', 'numfile' => $cell?->getWorksheetOrNull()?->getParent()?->getSheetCount() ?? 1, 'origin' => '$A:$A$1', 'osversion' => 'PHP ' . PHP_VERSION, 'recalc' => 'Automatic', 'release' => PHP_VERSION, 'system' => 'PHP', 'memavail', 'memused', 'totmem' => ExcelError::NA(), default => ExcelError::VALUE(), }; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Information/Value.php ================================================ |bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isBlank(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return $value === null; } /** * IS_REF. * * @param mixed $value Value to check */ public static function isRef(mixed $value, ?Cell $cell = null): bool { if ($cell === null) { return false; } $value = StringHelper::convertToString($value); $cellValue = Functions::trimTrailingRange($value); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/ui', $cellValue) === 1) { [$worksheet, $cellValue] = Worksheet::extractSheetTitle($cellValue, true, true); if (!empty($worksheet) && $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheet) === null) { return false; } try { [$column, $row] = Coordinate::indexesFromString($cellValue ?? ''); } catch (SpreadsheetException) { return false; } return true; } $namedRange = $cell->getWorksheet()->getParentOrThrow()->getNamedRange($value); return $namedRange instanceof NamedRange; } /** * IS_EVEN. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isEven(mixed $value = null): array|string|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if ($value === null) { return ExcelError::NAME(); } if (!is_numeric($value)) { return ExcelError::VALUE(); } return ((int) fmod($value + 0, 2)) === 0; } /** * IS_ODD. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isOdd(mixed $value = null): array|string|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if ($value === null) { return ExcelError::NAME(); } if (!is_numeric($value)) { return ExcelError::VALUE(); } return ((int) fmod($value + 0, 2)) !== 0; } /** * IS_NUMBER. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNumber(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (is_string($value)) { return false; } return is_numeric($value); } /** * IS_LOGICAL. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isLogical(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return is_bool($value); } /** * IS_TEXT. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isText(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return is_string($value) && !ErrorValue::isError($value); } /** * IS_NONTEXT. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNonText(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return !self::isText($value); } /** * ISFORMULA. * * @param mixed $cellReference The cell to check * @param ?Cell $cell The current cell (containing this formula) * * @return array|bool|string */ public static function isFormula(mixed $cellReference = '', ?Cell $cell = null): array|bool|string { if ($cell === null) { return ExcelError::REF(); } $cellReference = StringHelper::convertToString($cellReference); $fullCellReference = Functions::expandDefinedName($cellReference, $cell); if (str_contains($cellReference, '!')) { $cellReference = Functions::trimSheetFromCellReference($cellReference); $cellReferences = Coordinate::extractAllCellReferencesInRange($cellReference); if (count($cellReferences) > 1) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $cellReferences, $cell); } } $fullCellReference = Functions::trimTrailingRange($fullCellReference); $worksheetName = ''; if (1 == preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $fullCellReference, $matches)) { $fullCellReference = $matches[6] . $matches[7]; $worksheetName = str_replace("''", "'", trim($matches[2], "'")); } $worksheet = (!empty($worksheetName)) ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); if ($worksheet === null) { return ExcelError::REF(); } try { return $worksheet->getCell($fullCellReference)->isFormula(); } catch (SpreadsheetException) { return true; } } /** * N. * * Returns a value converted to a number * * @param null|mixed $value The value you want converted * * @return number|string N converts values listed in the following table * If value is or refers to N returns * A number That number value * A date The Excel serialized number of that date * TRUE 1 * FALSE 0 * An error value The error value * Anything else 0 */ public static function asNumber($value = null) { while (is_array($value)) { $value = array_shift($value); } if (is_float($value) || is_int($value)) { return $value; } if (is_bool($value)) { return (int) $value; } if (is_string($value) && str_starts_with($value, '#')) { return $value; } return 0; } /** * TYPE. * * Returns a number that identifies the type of a value * * @param null|mixed $value The value you want tested * * @return int N converts values listed in the following table * If value is or refers to N returns * A number 1 * Text 2 * Logical Value 4 * An error value 16 * Array or Matrix 64 */ public static function type($value = null): int { $value = Functions::flattenArrayIndexed($value); if (count($value) > 1) { end($value); $a = key($value); // Range of cells is an error if (Functions::isCellValue($a)) { return 16; // Test for Matrix } elseif (Functions::isMatrixValue($a)) { return 64; } } elseif (empty($value)) { // Empty Cell return 1; } $value = Functions::flattenSingleValue($value); if (($value === null) || (is_float($value)) || (is_int($value))) { return 1; } elseif (is_bool($value)) { return 4; } elseif (is_array($value)) { return 64; } elseif (is_string($value)) { // Errors if (($value !== '') && ($value[0] == '#')) { return 16; } return 2; } return 0; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Internal/ExcelArrayPseudoFunctions.php ================================================ getWorksheet(); [$referenceWorksheetName, $referenceCellCoordinate] = Worksheet::extractSheetTitle($cellReference, true, true); if (preg_match('/^([$]?[a-z]{1,3})([$]?([0-9]{1,7})):([$]?[a-z]{1,3})([$]?([0-9]{1,7}))$/i', "$referenceCellCoordinate", $matches) === 1) { $ourRow = $cell->getRow(); $firstRow = (int) $matches[3]; $lastRow = (int) $matches[6]; if ($ourRow < $firstRow || $ourRow > $lastRow || $matches[1] !== $matches[4]) { return ExcelError::VALUE(); } $referenceCellCoordinate = $matches[1] . $ourRow; } $referenceCell = ($referenceWorksheetName === '') ? $worksheet->getCell((string) $referenceCellCoordinate) : $worksheet->getParentOrThrow() ->getSheetByNameOrThrow((string) $referenceWorksheetName) ->getCell((string) $referenceCellCoordinate); $result = $referenceCell->getCalculatedValue(); while (is_array($result)) { $result = array_shift($result); } return $result; } /** @return array|string */ public static function anchorArray(string $cellReference, Cell $cell): array|string { //$coordinate = $cell->getCoordinate(); $worksheet = $cell->getWorksheet(); [$referenceWorksheetName, $referenceCellCoordinate] = Worksheet::extractSheetTitle($cellReference, true, true); $referenceCell = ($referenceWorksheetName === '') ? $worksheet->getCell((string) $referenceCellCoordinate) : $worksheet->getParentOrThrow() ->getSheetByNameOrThrow((string) $referenceWorksheetName) ->getCell((string) $referenceCellCoordinate); // We should always use the sizing for the array formula range from the referenced cell formula //$referenceRange = null; /*if ($referenceCell->isFormula() && $referenceCell->isArrayFormula()) { $referenceRange = $referenceCell->arrayFormulaRange(); }*/ $calcEngine = Calculation::getInstance($worksheet->getParent()); $result = $calcEngine->calculateCellValue($referenceCell, false); if (!is_array($result)) { $result = ExcelError::REF(); } // Ensure that our array result dimensions match the specified array formula range dimensions, // from the referenced cell, expanding or shrinking it as necessary. /*$result = Functions::resizeMatrix( $result, ...Coordinate::rangeDimension($referenceRange ?? $coordinate) );*/ // Set the result for our target cell (with spillage) // But if we do write it, we get problems with #SPILL! Errors if the spreadsheet is saved // TODO How are we going to identify and handle a #SPILL! or a #CALC! error? // IOFactory::setLoading(true); // $worksheet->fromArray( // $result, // null, // $coordinate, // true // ); // IOFactory::setLoading(true); // Calculate the array formula range that we should set for our target, based on our target cell coordinate // [$col, $row] = Coordinate::indexesFromString($coordinate); // $row += count($result) - 1; // $col = Coordinate::stringFromColumnIndex($col + count($result[0]) - 1); // $arrayFormulaRange = "{$coordinate}:{$col}{$row}"; // $formulaAttributes = ['t' => 'array', 'ref' => $arrayFormulaRange]; // Using fromArray() would reset the value for this cell with the calculation result // as well as updating the spillage cells, // so we need to restore this cell to its formula value, attributes, and datatype // $cell = $worksheet->getCell($coordinate); // $cell->setValueExplicit($value, DataType::TYPE_FORMULA, true, $arrayFormulaRange); // $cell->setFormulaAttributes($formulaAttributes); // $cell->updateInCollection(); return $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php ================================================ 0) { $targetValue = Functions::flattenSingleValue($arguments[0]); $argc = count($arguments) - 1; $switchCount = floor($argc / 2); $hasDefaultClause = $argc % 2 !== 0; $defaultClause = $argc % 2 === 0 ? null : $arguments[$argc]; $switchSatisfied = false; if ($switchCount > 0) { for ($index = 0; $index < $switchCount; ++$index) { if ($targetValue == Functions::flattenSingleValue($arguments[$index * 2 + 1])) { $result = $arguments[$index * 2 + 2]; $switchSatisfied = true; break; } } } if ($switchSatisfied !== true) { $result = $hasDefaultClause ? $defaultClause : ExcelError::NA(); } } return $result; } /** * IFERROR. * * Excel Function: * =IFERROR(testValue,errorpart) * * @param mixed $testValue Value to check, is also the value returned when no error * Or can be an array of values * @param mixed $errorpart Value to return when testValue is an error condition * Note that this can be an array value to be returned * * @return mixed The value of errorpart or testValue determined by error condition * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function IFERROR(mixed $testValue = '', mixed $errorpart = ''): mixed { if (is_array($testValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $errorpart); } $errorpart = $errorpart ?? ''; $testValue = $testValue ?? 0; // this is how Excel handles empty cell return self::statementIf(ErrorValue::isError($testValue), $errorpart, $testValue); } /** * IFNA. * * Excel Function: * =IFNA(testValue,napart) * * @param mixed $testValue Value to check, is also the value returned when not an NA * Or can be an array of values * @param mixed $napart Value to return when testValue is an NA condition * Note that this can be an array value to be returned * * @return mixed The value of errorpart or testValue determined by error condition * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function IFNA(mixed $testValue = '', mixed $napart = ''): mixed { if (is_array($testValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $napart); } $napart = $napart ?? ''; $testValue = $testValue ?? 0; // this is how Excel handles empty cell return self::statementIf(ErrorValue::isNa($testValue), $napart, $testValue); } /** * IFS. * * Excel Function: * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) * * testValue1 ... testValue_n * Conditions to Evaluate * returnIfTrue1 ... returnIfTrue_n * Value returned if corresponding testValue (nth) was true * * @param mixed ...$arguments Statement arguments * Note that this can be an array value to be returned * * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true */ public static function IFS(mixed ...$arguments) { $argumentCount = count($arguments); if ($argumentCount % 2 != 0) { return ExcelError::NA(); } // We use instance of Exception as a falseValue in order to prevent string collision with value in cell $falseValueException = new Exception(); for ($i = 0; $i < $argumentCount; $i += 2) { $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]); $returnIfTrue = ($arguments[$i + 1] === null) ? '' : $arguments[$i + 1]; $result = self::statementIf($testValue, $returnIfTrue, $falseValueException); if ($result !== $falseValueException) { return $result; } } return ExcelError::NA(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Logical/Operations.php ================================================ $trueValueCount === $count); } /** * LOGICAL_OR. * * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. * * Excel Function: * =OR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $args Data values * * @return bool|string the logical OR of the arguments */ public static function logicalOr(mixed ...$args) { return self::countTrueValues($args, fn (int $trueValueCount): bool => $trueValueCount > 0); } /** * LOGICAL_XOR. * * Returns the Exclusive Or logical operation for one or more supplied conditions. * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, * and FALSE otherwise. * * Excel Function: * =XOR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $args Data values * * @return bool|string the logical XOR of the arguments */ public static function logicalXor(mixed ...$args) { return self::countTrueValues($args, fn (int $trueValueCount): bool => $trueValueCount % 2 === 1); } /** * NOT. * * Returns the boolean inverse of the argument. * * Excel Function: * =NOT(logical) * * The argument must evaluate to a logical value such as TRUE or FALSE * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * Or can be an array of values * * @return array|bool|string the boolean inverse of the argument * If an array of values is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function NOT(mixed $logical = false): array|bool|string { if (is_array($logical)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $logical); } if (is_string($logical)) { $logical = mb_strtoupper($logical, 'UTF-8'); if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { return false; } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { return true; } return ExcelError::VALUE(); } return !$logical; } /** * @param mixed[] $args * @param callable(int, int): bool $func */ private static function countTrueValues(array $args, callable $func): bool|string { $trueValueCount = 0; $count = 0; $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { ++$count; // Is it a boolean value? if (is_bool($arg)) { $trueValueCount += $arg; } elseif (is_string($arg)) { $isLiteral = !Functions::isCellValue($k); $arg = mb_strtoupper($arg, 'UTF-8'); if ($isLiteral && ($arg == 'TRUE' || $arg == Calculation::getTRUE())) { ++$trueValueCount; } elseif ($isLiteral && ($arg == 'FALSE' || $arg == Calculation::getFALSE())) { //$trueValueCount += 0; } else { --$count; } } elseif (is_int($arg) || is_float($arg)) { $trueValueCount += (int) ($arg != 0); } else { --$count; } } return ($count === 0) ? ExcelError::VALUE() : $func($trueValueCount, $count); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Address.php ================================================ '') { if (str_contains($sheetName, ' ') || str_contains($sheetName, '[')) { $sheetName = "'{$sheetName}'"; } $sheetName .= '!'; } return $sheetName; } private static function formatAsA1(int $row, int $column, int $relativity, string $sheetName): string { $rowRelative = $columnRelative = '$'; if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $columnRelative = ''; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $rowRelative = ''; } $column = Coordinate::stringFromColumnIndex($column); return "{$sheetName}{$columnRelative}{$column}{$rowRelative}{$row}"; } private static function formatAsR1C1(int $row, int $column, int $relativity, string $sheetName): string { if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $column = "[{$column}]"; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $row = "[{$row}]"; } [$rowChar, $colChar] = AddressHelper::getRowAndColumnChars(); return "{$sheetName}$rowChar{$row}$colChar{$column}"; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/ChooseRowsEtc.php ================================================ [$x]) : null, ...$array)); // @phpstan-ignore-line } /** @return mixed[] */ private static function arrayValues(mixed $array): array { return is_array($array) ? array_values($array) : [$array]; } /** * CHOOSECOLS. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function chooseCols(mixed $input, mixed ...$args): array|string { if (!is_array($input)) { $input = [[$input]]; } $retval = self::chooseRows(self::transpose($input), ...$args); return is_array($retval) ? self::transpose($retval) : $retval; } /** * CHOOSEROWS. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function chooseRows(mixed $input, mixed ...$args): array|string { if (!is_array($input)) { $input = [[$input]]; } $inputArray = [[]]; // no row 0 $numRows = 0; foreach ($input as $inputRow) { $inputArray[] = self::arrayValues($inputRow); ++$numRows; } $outputArray = []; foreach (Functions::flattenArray2(...$args) as $arg) { if (!is_numeric($arg)) { return ExcelError::VALUE(); } $index = (int) $arg; if ($index < 0) { $index += $numRows + 1; } if ($index <= 0 || $index > $numRows) { return ExcelError::VALUE(); } $outputArray[] = $inputArray[$index]; } return $outputArray; } /** * @param mixed[] $array * * @return mixed[]|string */ private static function dropRows(array $array, mixed $offset): array|string { if ($offset === null) { return $array; } if (!is_numeric($offset)) { return ExcelError::VALUE(); } $offset = (int) $offset; $count = count($array); if (abs($offset) >= $count) { // In theory, this should be #CALC!, but Excel treats // #CALC! as corrupt, and it's not worth figuring out why return ExcelError::VALUE(); } if ($offset === 0) { return $array; } if ($offset > 0) { return array_slice($array, $offset); } return array_slice($array, 0, $count + $offset); } /** * DROP. * * @param mixed $input expect two-dimensional array * * @return mixed[]|string */ public static function drop(mixed $input, mixed $rows = null, mixed $columns = null): array|string { if (!is_array($input)) { $input = [[$input]]; } $inputArray = []; // no row 0 foreach ($input as $inputRow) { $inputArray[] = self::arrayValues($inputRow); } $outputArray1 = self::dropRows($inputArray, $rows); if (is_string($outputArray1)) { return $outputArray1; } $outputArray2 = self::transpose($outputArray1); $outputArray3 = self::dropRows($outputArray2, $columns); if (is_string($outputArray3)) { return $outputArray3; } return self::transpose($outputArray3); } /** * @param mixed[] $array * * @return mixed[]|string */ private static function takeRows(array $array, mixed $offset): array|string { if ($offset === null) { return $array; } if (!is_numeric($offset)) { return ExcelError::VALUE(); } $offset = (int) $offset; if ($offset === 0) { // should be #CALC! - see above return ExcelError::VALUE(); } $count = count($array); if (abs($offset) >= $count) { return $array; } if ($offset > 0) { return array_slice($array, 0, $offset); } return array_slice($array, $count + $offset); } /** * TAKE. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function take(mixed $input, mixed $rows, mixed $columns = null): array|string { if (!is_array($input)) { $input = [[$input]]; } if ($rows === null && $columns === null) { return $input; } $inputArray = []; foreach ($input as $inputRow) { $inputArray[] = self::arrayValues($inputRow); } $outputArray1 = self::takeRows($inputArray, $rows); if (is_string($outputArray1)) { return $outputArray1; } $outputArray2 = self::transpose($outputArray1); $outputArray3 = self::takeRows($outputArray2, $columns); if (is_string($outputArray3)) { return $outputArray3; } return self::transpose($outputArray3); } /** * EXPAND. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function expand(mixed $input, mixed $rows, mixed $columns = null, mixed $pad = '#N/A'): array|string { if (!is_array($input)) { $input = [[$input]]; } if ($rows === null && $columns === null) { return $input; } $numRows = count($input); $rows ??= $numRows; if (!is_numeric($rows)) { return ExcelError::VALUE(); } $rows = (int) $rows; if ($rows < count($input)) { return ExcelError::VALUE(); } $numCols = 0; foreach ($input as $inputRow) { $numCols = max($numCols, is_array($inputRow) ? count($inputRow) : 1); } $columns ??= $numCols; if (!is_numeric($columns)) { return ExcelError::VALUE(); } $columns = (int) $columns; if ($columns < $numCols) { return ExcelError::VALUE(); } $inputArray = []; foreach ($input as $inputRow) { $inputArray[] = array_pad(self::arrayValues($inputRow), $columns, $pad); } $outputArray = []; $padRow = array_pad([], $columns, $pad); for ($count = 0; $count < $rows; ++$count) { $outputArray[] = ($count >= $numRows) ? $padRow : $inputArray[$count]; } return $outputArray; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php ================================================ |float|int|string The relative position of the found item */ public static function MATCH(mixed $lookupValue, mixed $lookupArray, mixed $matchType = self::MATCHTYPE_LARGEST_VALUE): array|string|int|float { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $matchType); } $lookupArray = Functions::flattenArray($lookupArray); try { // Input validation self::validateLookupValue($lookupValue); $matchType = self::validateMatchType($matchType); self::validateLookupArray($lookupArray); $keySet = array_keys($lookupArray); if ($matchType == self::MATCHTYPE_LARGEST_VALUE) { // If match_type is 1 the list has to be processed from last to first $lookupArray = array_reverse($lookupArray); $keySet = array_reverse($keySet); } $lookupArray = self::prepareLookupArray($lookupArray, $matchType); } catch (Exception $e) { return $e->getMessage(); } // MATCH() is not case-sensitive, so we convert lookup value to be lower cased if it's a string type. if (is_string($lookupValue)) { $lookupValue = StringHelper::strToLower($lookupValue); } $valueKey = match ($matchType) { self::MATCHTYPE_LARGEST_VALUE => self::matchLargestValue($lookupArray, $lookupValue, $keySet), self::MATCHTYPE_FIRST_VALUE => self::matchFirstValue($lookupArray, $lookupValue), default => self::matchSmallestValue($lookupArray, $lookupValue), }; if ($valueKey !== null) { return ++$valueKey; //* @phpstan-ignore-line } // Unsuccessful in finding a match, return #N/A error value return ExcelError::NA(); } /** @param mixed[] $lookupArray */ private static function matchFirstValue(array $lookupArray, mixed $lookupValue): int|string|null { if (is_string($lookupValue)) { $valueIsString = true; $wildcard = WildcardMatch::wildcard($lookupValue); } else { $valueIsString = false; $wildcard = ''; } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ( $valueIsString && is_string($lookupArrayValue) ) { if (WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; // wildcard match } } else { if ($lookupArrayValue === $lookupValue) { return $i; // exact match } if ( $valueIsNumeric && (is_float($lookupArrayValue) || is_int($lookupArrayValue)) && $lookupArrayValue == $lookupValue ) { return $i; // exact match } } } return null; } /** * @param mixed[] $lookupArray * @param mixed[] $keySet */ private static function matchLargestValue(array $lookupArray, mixed $lookupValue, array $keySet): mixed { if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach (array_reverse($lookupArray) as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } else { foreach ($lookupArray as $i => $lookupArrayValue) { if ($lookupArrayValue === $lookupValue) { return $keySet[$i]; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ($valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue))) { if ($lookupArrayValue <= $lookupValue) { return array_search($i, $keySet); } } $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); if ($typeMatch && ($lookupArrayValue <= $lookupValue)) { return array_search($i, $keySet); } } return null; } /** @param mixed[] $lookupArray */ private static function matchSmallestValue(array $lookupArray, mixed $lookupValue): int|string|null { $valueKey = null; if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); // The basic algorithm is: // Iterate and keep the highest match until the next element is smaller than the searched value. // Return immediately if perfect match is found foreach ($lookupArray as $i => $lookupArrayValue) { $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); $bothNumeric = $valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue)); if ($lookupArrayValue === $lookupValue) { // Another "special" case. If a perfect match is found, // the algorithm gives up immediately return $i; } if ($bothNumeric && $lookupValue == $lookupArrayValue) { return $i; // exact match, as above } if (($typeMatch || $bothNumeric) && $lookupArrayValue >= $lookupValue) { $valueKey = $i; } elseif ($typeMatch && $lookupArrayValue < $lookupValue) { //Excel algorithm gives up immediately if the first element is smaller than the searched value break; } } return $valueKey; } private static function validateLookupValue(mixed $lookupValue): void { // Lookup_value type has to be number, text, or logical values if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { throw new Exception(ExcelError::NA()); } } private static function validateMatchType(mixed $matchType): int { // Match_type is 0, 1 or -1 // However Excel accepts other numeric values, // including numeric strings and floats. // It seems to just be interested in the sign. if (!is_numeric($matchType)) { throw new Exception(ExcelError::Value()); } if ($matchType > 0) { return self::MATCHTYPE_LARGEST_VALUE; } if ($matchType < 0) { return self::MATCHTYPE_SMALLEST_VALUE; } return self::MATCHTYPE_FIRST_VALUE; } /** @param mixed[] $lookupArray */ private static function validateLookupArray(array $lookupArray): void { // Lookup_array should not be empty $lookupArraySize = count($lookupArray); if ($lookupArraySize <= 0) { throw new Exception(ExcelError::NA()); } } /** * @param mixed[] $lookupArray * * @return mixed[] */ private static function prepareLookupArray(array $lookupArray, mixed $matchType): array { // Lookup_array should contain only number, text, or logical values, or empty (null) cells foreach ($lookupArray as $i => $value) { // check the type of the value if ((!is_numeric($value)) && (!is_string($value)) && (!is_bool($value)) && ($value !== null)) { throw new Exception(ExcelError::NA()); } // Convert strings to lowercase for case-insensitive testing if (is_string($value)) { $lookupArray[$i] = StringHelper::strToLower($value); } if ( ($value === null) && (($matchType == self::MATCHTYPE_LARGEST_VALUE) || ($matchType == self::MATCHTYPE_SMALLEST_VALUE)) ) { unset($lookupArray[$i]); } } return $lookupArray; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Filter.php ================================================ (bool) ($matchArray[$index] ?? null), ARRAY_FILTER_USE_KEY ); } /** * @param mixed[] $lookupArray * @param mixed[] $matchArray * * @return mixed[] */ private static function filterByColumn(array $lookupArray, array $matchArray): array { $lookupArray = Matrix::transpose($lookupArray); if (count($matchArray) === 1) { $matchArray = array_pop($matchArray); } /** @var mixed[] $matchArray */ array_walk( $matchArray, function (&$value): void { $value = [$value]; } ); $result = self::filterByRow($lookupArray, $matchArray); return Matrix::transpose($result); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Formula.php ================================================ getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); } if ( $worksheet === null || !$worksheet->cellExists($cellReference) || !$worksheet->getCell($cellReference)->isFormula() ) { return ExcelError::NA(); } return $worksheet->getCell($cellReference)->getValueString(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php ================================================ |float|int|string $indexNumber The row number in table_array from which the matching value must be returned. * The first row is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, $lookupArray, $indexNumber, mixed $notExactMatch = true): mixed { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $lookupArray = self::convertLiteralArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = reset($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) { return ExcelError::REF(); } $firstkey = $f[0] - 1; $returnColumn = $firstkey + $indexNumber; /** @var mixed[][] $lookupArray */ $firstColumn = array_shift($f) ?? 1; $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // otherwise return the appropriate value return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)]; } return ExcelError::NA(); } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed[][] $lookupArray * @param int|string $column */ private static function hLookupSearch(mixed $lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower(StringHelper::convertToString($lookupValue)); $rowNumber = null; foreach ($lookupArray[$column] as $rowKey => $rowData) { // break if we have passed possible keys /** @var string $rowKey */ $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData); $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData); /** @var scalar $rowData */ $cellDataLower = StringHelper::strToLower((string) $rowData); if ( $notExactMatch && (($bothNumeric && $rowData > $lookupValue) || ($bothNotNumeric && $cellDataLower > $lookupLower)) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, Coordinate::columnIndexFromString($rowKey), $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } /** * @param mixed[] $lookupArray * * @return mixed[] */ private static function convertLiteralArray(array $lookupArray): array { if (array_key_exists(0, $lookupArray)) { $lookupArray2 = []; $row = 0; foreach ($lookupArray as $arrayVal) { ++$row; if (!is_array($arrayVal)) { $arrayVal = [$arrayVal]; } $arrayVal2 = []; foreach ($arrayVal as $key2 => $val2) { $index = Coordinate::stringFromColumnIndex($key2 + 1); $arrayVal2[$index] = $val2; } $lookupArray2[$row] = $arrayVal2; } $lookupArray = $lookupArray2; } return $lookupArray; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php ================================================ getWorkSheet(); $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle(); $value = (string) preg_replace('/^=/', '', $namedRange->getValue()); self::adjustSheetTitle($sheetTitle, $value); $cellAddress1 = $sheetTitle . $value; $cellAddress = $cellAddress1; $a1 = self::CELLADDRESS_USE_A1; } if (str_contains($cellAddress, ':')) { [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); } $cellAddress = self::convertR1C1($cellAddress1, $cellAddress2, $a1, $baseRow, $baseCol); return [$cellAddress1, $cellAddress2, $cellAddress]; } /** @return array{string, ?Worksheet, string} */ public static function extractWorksheet(string $cellAddress, Cell $cell): array { $sheetName = ''; if (str_contains($cellAddress, '!')) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true, true); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet, $sheetName]; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Hstack.php ================================================ $rows) { $matrix[] = array_pad([], $columns, ExcelError::NA()); ++$rows; } } $transpose = array_map(null, ...$inputData); //* @phpstan-ignore-line $returnMatrix = []; foreach ($transpose as $array) { $returnMatrix[] = Functions::flattenArray($array); } return $returnMatrix; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php ================================================ getCoordinate(); $worksheet = $cell->getWorksheetOrNull(); } $linkURL = ($linkURL === null) ? '' : StringHelper::convertToString(Functions::flattenSingleValue($linkURL)); $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName); if ((!is_object($cell)) || (trim($linkURL) == '')) { return ExcelError::REF(); } $displayName = StringHelper::convertToString($displayName, false); if (trim($displayName) === '') { $displayName = $linkURL; } $worksheet?->getCell($coordinate) ->getHyperlink() ->setUrl($linkURL) ->setTooltip($displayName) ->setDisplay(''); return $displayName; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php ================================================ getCoordinate()); try { $a1 = self::a1Format($a1fmt); $cellAddress = self::validateAddress($cellAddress); } catch (Exception $e) { return $e->getMessage(); } [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } try { [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName, $baseRow, $baseCol); } catch (Exception) { return ExcelError::REF(); } if ( (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress1, $matches)) || (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress2, $matches))) ) { return ExcelError::REF(); } return self::extractRequiredCells($worksheet, $cellAddress); } /** * Extract range values. * * @return mixed[] Array of values in range if range contains more than one element. * Otherwise, a single value is returned. */ private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress): array { return Calculation::getInstance($worksheet?->getParent()) ->extractCellRange($cellAddress, $worksheet, false, createCell: true); } private static function handleRowColumnRanges(?Worksheet $worksheet, string $start, string $end): string { // Being lazy, we're only checking a single row/column to get the max if (ctype_digit($start) && $start <= AddressRange::MAX_ROW) { // Max 16,384 columns for Excel2007 $endColRef = ($worksheet !== null) ? $worksheet->getHighestDataColumn((int) $start) : AddressRange::MAX_COLUMN; return "A{$start}:{$endColRef}{$end}"; } elseif (ctype_alpha($start) && strlen($start) <= 3) { // Max 1,048,576 rows for Excel2007 $endRowRef = ($worksheet !== null) ? $worksheet->getHighestDataRow($start) : AddressRange::MAX_ROW; return "{$start}1:{$end}{$endRowRef}"; } return "{$start}:{$end}"; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php ================================================ 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { $lookupVector = Matrix::transpose($lookupVector); $lookupRows = self::rowCount($lookupVector); /** @var mixed[][] $lookupVector */ $lookupColumns = self::columnCount($lookupVector); } $resultVector = self::verifyResultVector($resultVector ?? $lookupVector); //* @phpstan-ignore-line if ($lookupRows === 2 && !$hasResultVector) { $resultVector = array_pop($lookupVector); $lookupVector = array_shift($lookupVector); } /** @var array $lookupVector */ /** @var array $resultVector */ if ($lookupColumns !== 2) { $lookupVector = self::verifyLookupValues($lookupVector, $resultVector); } return VLookup::lookup($lookupValue, $lookupVector, 2); } /** * @param array $lookupVector * @param array $resultVector * * @return mixed[] */ private static function verifyLookupValues(array $lookupVector, array $resultVector): array { foreach ($lookupVector as &$value) { if (is_array($value)) { $k = array_keys($value); $key1 = $key2 = array_shift($k); ++$key2; $dataValue1 = $value[$key1]; } else { $key1 = 0; $key2 = 1; $dataValue1 = $value; } $dataValue2 = array_shift($resultVector); if (is_array($dataValue2)) { $dataValue2 = array_shift($dataValue2); } /** @var int $key2 */ $value = [$key1 => $dataValue1, $key2 => $dataValue2]; } unset($value); return $lookupVector; } /** * @param mixed[][] $resultVector * * @return mixed[] */ private static function verifyResultVector(array $resultVector): array { $resultRows = self::rowCount($resultVector); $resultColumns = self::columnCount($resultVector); // we correctly orient our results if ($resultRows === 1 && $resultColumns > 1) { $resultVector = Matrix::transpose($resultVector); } return $resultVector; } /** @param mixed[] $dataArray */ private static function rowCount(array $dataArray): int { return count($dataArray); } /** @param mixed[][] $dataArray */ private static function columnCount(array $dataArray): int { $rowKeys = array_keys($dataArray); $row = array_shift($rowKeys); return count($dataArray[$row]); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php ================================================ = 1 */ protected static function validateIndexLookup(array $lookupArray, $index_number): int { // index_number must be a number greater than or equal to 1. // Excel results are inconsistent when index is non-numeric. // VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but // VLOOKUP(whatever, whatever, cellref) yields REF error // when cellref is '=SQRT(-1)'. So just try our best here. // Similar results if string (literal yields VALUE, cellRef REF). if (!is_numeric($index_number)) { throw new Exception(ExcelError::throwError($index_number)); } if ($index_number < 1) { throw new Exception(ExcelError::VALUE()); } // index_number must be less than or equal to the number of columns in lookupArray if (empty($lookupArray)) { throw new Exception(ExcelError::REF()); } return (int) $index_number; } protected static function checkMatch( bool $bothNumeric, bool $bothNotNumeric, bool $notExactMatch, int $rowKey, string $cellDataLower, string $lookupLower, ?int $rowNumber ): ?int { // remember the last key, but only if datatypes match if ($bothNumeric || $bothNotNumeric) { // Spreadsheets software returns first exact match, // we have sorted and we might have broken key orders // we want the first one (by its initial index) if ($notExactMatch) { $rowNumber = $rowKey; } elseif (($cellDataLower == $lookupLower) && (($rowNumber === null) || ($rowKey < $rowNumber))) { $rowNumber = $rowKey; } } return $rowNumber; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/LookupRefValidations.php ================================================ 1 && (count($values, COUNT_NORMAL) === 1 || count($values, COUNT_RECURSIVE) === count($values, COUNT_NORMAL)); } /** * TRANSPOSE. * * @param mixed $matrixData A matrix of values * * @return mixed[] */ public static function transpose($matrixData): array { $returnMatrix = []; if (!is_array($matrixData)) { $matrixData = [[$matrixData]]; } if (!is_array(end($matrixData))) { $matrixData = [$matrixData]; } $column = 0; /** @var mixed[][] $matrixData */ foreach ($matrixData as $matrixRow) { $row = 0; foreach ($matrixRow as $matrixCell) { $returnMatrix[$row][$column] = $matrixCell; ++$row; } ++$column; } return $returnMatrix; } /** * INDEX. * * Uses an index to choose a value from a reference or array * * Excel Function: * =INDEX(range_array, row_num, [column_num], [area_num]) * * @param mixed $matrix A range of cells or an array constant * @param mixed $rowNum The row in the array or range from which to return a value. * If row_num is omitted, column_num is required. * Or can be an array of values * @param mixed $columnNum The column in the array or range from which to return a value. * If column_num is omitted, row_num is required. * Or can be an array of values * * TODO Provide support for area_num, currently not supported * * @return mixed the value of a specified cell or array of cells * If an array of values is passed as the $rowNum and/or $columnNum arguments, then the returned result * will also be an array with the same dimensions */ public static function index(mixed $matrix, mixed $rowNum = 0, mixed $columnNum = null): mixed { if (is_array($rowNum) || is_array($columnNum)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $matrix, $rowNum, $columnNum); } $rowNum = $rowNum ?? 0; $columnNum = $columnNum ?? 0; if (is_scalar($matrix)) { if ($rowNum === 0 || $rowNum === 1) { if ($columnNum === 0 || $columnNum === 1) { if ($columnNum === 1 || $rowNum === 1) { return $matrix; } } } } try { $rowNum = LookupRefValidations::validatePositiveInt($rowNum); $columnNum = LookupRefValidations::validatePositiveInt($columnNum); } catch (Exception $e) { return $e->getMessage(); } if (is_array($matrix) && count($matrix) === 1 && $rowNum > 1) { $matrixKey = array_keys($matrix)[0]; if (is_array($matrix[$matrixKey])) { $tempMatrix = []; foreach ($matrix[$matrixKey] as $key => $value) { $tempMatrix[$key] = [$value]; } $matrix = $tempMatrix; } } if (!is_array($matrix) || ($rowNum > count($matrix))) { return ExcelError::REF(); } $rowKeys = array_keys($matrix); $columnKeys = @array_keys($matrix[$rowKeys[0]]); //* @phpstan-ignore-line if ($columnNum > count($columnKeys)) { return ExcelError::REF(); } if ($columnNum === 0) { return self::extractRowValue($matrix, $rowKeys, $rowNum); } $columnNum = $columnKeys[--$columnNum]; //* @phpstan-ignore-line if ($rowNum === 0) { return array_map( fn ($value): array => [$value], array_column($matrix, $columnNum) ); } $rowNum = $rowKeys[--$rowNum]; //* @phpstan-ignore-line /** @var mixed[][] $matrix */ return $matrix[$rowNum][$columnNum]; } /** * @param mixed[] $matrix * @param array $rowKeys */ private static function extractRowValue(array $matrix, array $rowKeys, int $rowNum): mixed { if ($rowNum === 0) { return $matrix; } $rowNum = $rowKeys[--$rowNum]; $row = $matrix[$rowNum]; if (is_array($row)) { return [$rowNum => $row]; } return $row; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php ================================================ |string An array containing a cell or range of cells, or a string on error */ public static function OFFSET(?string $cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, ?Cell $cell = null): string|array { /** @var int */ $rows = Functions::flattenSingleValue($rows); /** @var int */ $columns = Functions::flattenSingleValue($columns); /** @var int */ $height = Functions::flattenSingleValue($height); /** @var int */ $width = Functions::flattenSingleValue($width); if ($cellAddress === null || $cellAddress === '') { return ExcelError::VALUE(); } if (!is_object($cell)) { return ExcelError::REF(); } $sheet = $cell->getParent()?->getParent(); // worksheet if ($sheet !== null) { $cellAddress = Validations::definedNameToCoordinate($cellAddress, $sheet); } [$cellAddress, $worksheet] = self::extractWorksheet($cellAddress, $cell); $startCell = $endCell = $cellAddress; if (strpos($cellAddress, ':')) { [$startCell, $endCell] = explode(':', $cellAddress); } [$startCellColumn, $startCellRow] = Coordinate::indexesFromString($startCell); [, $endCellRow, $endCellColumn] = Coordinate::indexesFromString($endCell); $startCellRow += $rows; $startCellColumn += $columns - 1; if (($startCellRow <= 0) || ($startCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = self::adjustEndCellColumnForWidth($endCellColumn, $width, $startCellColumn, $columns); $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1); $endCellRow = self::adjustEndCellRowForHeight($height, $startCellRow, $rows, $endCellRow); if (($endCellRow <= 0) || ($endCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1); $cellAddress = "{$startCellColumn}{$startCellRow}"; if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { $cellAddress .= ":{$endCellColumn}{$endCellRow}"; } return self::extractRequiredCells($worksheet, $cellAddress); } /** @return mixed[] */ private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress): array { return Calculation::getInstance($worksheet?->getParent()) ->extractCellRange($cellAddress, $worksheet, false); } /** @return array{string, ?Worksheet} */ private static function extractWorksheet(?string $cellAddress, Cell $cell): array { $cellAddress = self::assessCellAddress($cellAddress ?? '', $cell); $sheetName = ''; if (str_contains($cellAddress, '!')) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true, true); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet]; } private static function assessCellAddress(string $cellAddress, Cell $cell): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $cellAddress) !== false) { $cellAddress = Functions::expandDefinedName($cellAddress, $cell); } return $cellAddress; } /** * @param null|object|scalar $width * @param scalar $columns */ private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns): int { $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; if (($width !== null) && (!is_object($width))) { $endCellColumn = $startCellColumn + (int) $width - 1; } else { $endCellColumn += (int) $columns; } return $endCellColumn; } /** * @param null|object|scalar $height * @param scalar $rows */ private static function adjustEndCellRowForHeight($height, int $startCellRow, $rows, int $endCellRow): int { if (($height !== null) && (!is_object($height))) { $endCellRow = $startCellRow + (int) $height - 1; } else { $endCellRow += (int) $rows; } return $endCellRow; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php ================================================ getColumn()) : 1; } /** * COLUMN. * * Returns the column number of the given cell reference * If the cell reference is a range of cells, COLUMN returns the column numbers of each column * in the reference as a horizontal array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the COLUMN function appears; * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * * @param null|mixed[]|string $cellAddress A reference to a range of cells for which you want the column numbers * * @return int|int[]|string */ public static function COLUMN($cellAddress = null, ?Cell $cell = null): int|string|array { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellColumn($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $columnKey => $value) { $columnKey = (string) preg_replace('/[^a-z]/i', '', $columnKey); return Coordinate::columnIndexFromString($columnKey); } return self::cellColumn($cell); } $cellAddress = $cellAddress ?? ''; if ($cell != null) { [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); } [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $cellAddress ??= ''; if (str_contains($cellAddress, ':')) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (string) preg_replace('/[^a-z]/i', '', $startAddress); $endAddress = (string) preg_replace('/[^a-z]/i', '', $endAddress); return range( Coordinate::columnIndexFromString($startAddress), Coordinate::columnIndexFromString($endAddress) ); } $cellAddress = (string) preg_replace('/[^a-z]/i', '', $cellAddress); try { return Coordinate::columnIndexFromString($cellAddress); } catch (SpreadsheetException) { return ExcelError::NAME(); } } /** * COLUMNS. * * Returns the number of columns in an array or reference. * * Excel Function: * =COLUMNS(cellAddress) * * @param null|mixed[]|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of columns * * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (is_string($cellAddress) && ErrorValue::isError($cellAddress, true)) { return $cellAddress; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $rows; } return $columns; } private static function cellRow(?Cell $cell): int|string { return ($cell !== null) ? self::convert0ToName($cell->getRow()) : 1; } private static function convert0ToName(int|string $result): int|string { if (is_int($result) && ($result <= 0 || $result > AddressRange::MAX_ROW)) { return ExcelError::NAME(); } return $result; } /** * ROW. * * Returns the row number of the given cell reference * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference * as a vertical array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the ROW function appears; * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * * @param null|mixed[][]|string $cellAddress A reference to a range of cells for which you want the row numbers * * @return int|mixed[]|string */ public static function ROW($cellAddress = null, ?Cell $cell = null): int|string|array { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellRow($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $rowKey => $rowValue) { foreach ($rowValue as $columnKey => $cellValue) { return (int) preg_replace('/\D/', '', $rowKey); } } return self::cellRow($cell); } $cellAddress = $cellAddress ?? ''; if ($cell !== null) { [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); } [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $cellAddress ??= ''; if (str_contains($cellAddress, ':')) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (int) (string) preg_replace('/\D/', '', $startAddress); $endAddress = (int) (string) preg_replace('/\D/', '', $endAddress); return array_map( fn ($value): array => [$value], range($startAddress, $endAddress) ); } [$cellAddress] = explode(':', $cellAddress); return self::convert0ToName((int) preg_replace('/\D/', '', $cellAddress)); } /** * ROWS. * * Returns the number of rows in an array or reference. * * Excel Function: * =ROWS(cellAddress) * * @param null|mixed[]|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of rows * * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (is_string($cellAddress) && ErrorValue::isError($cellAddress, true)) { return $cellAddress; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $columns; } return $rows; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Selection.php ================================================ $entryCount)) { return ExcelError::VALUE(); } if (is_array($chooseArgs[$chosenEntry])) { return Functions::flattenArray($chooseArgs[$chosenEntry]); } return $chooseArgs[$chosenEntry]; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Sort.php ================================================ getMessage(); } // We want a simple, enumerated array of arrays where we can reference column by its index number. /** @var callable(mixed): mixed */ $temp = 'array_values'; /** @var array $sortOrder */ $sortArray = array_values(array_map($temp, $sortArray)); /** @var int[] $sortIndex */ return ($byColumn === true) ? self::sortByColumn($sortArray, $sortIndex, $sortOrder) : self::sortByRow($sortArray, $sortIndex, $sortOrder); } /** * SORTBY * The SORTBY function sorts the contents of a range or array based on the values in a corresponding range or array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * Microsoft doesn't even bother documenting that a column sort * is possible. However, it is. According to: * https://exceljet.net/functions/sortby-function * When by_array is a horizontal range, SORTBY sorts horizontally by columns. * My interpretation of this is that by_array must be an * array which contains exactly one row. * * NOTE: If the "byArray" contains a mixture of data types * (string/int/bool), the results may be unexpected. * This is also true if the array consists of string * representations of numbers, especially if there are * both positive and negative numbers in the mix. * * @param mixed $sortArray The range of cells being sorted * @param mixed $args * At least one additional argument must be provided, The vector or range to sort on * After that, arguments are passed as pairs: * sort order: ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * additional arrays or ranges for multi-level sorting * * @return mixed The sorted values from the sort range */ public static function sortBy(mixed $sortArray, mixed ...$args): mixed { if (!is_array($sortArray)) { $sortArray = [[$sortArray]]; } $transpose = false; $args0 = $args[0] ?? null; if (is_array($args0) && count($args0) === 1) { $args0 = reset($args0); if (is_array($args0) && count($args0) > 1) { $transpose = true; $sortArray = Matrix::transpose($sortArray); } } $sortArray = self::enumerateArrayKeys($sortArray); $lookupArraySize = count($sortArray); $argumentCount = count($args); try { $sortBy = $sortOrder = []; for ($i = 0; $i < $argumentCount; $i += 2) { $argsI = $args[$i]; if (!is_array($argsI)) { $argsI = [[$argsI]]; } $sortBy[] = self::validateSortVector($argsI, $lookupArraySize); $sortOrder[] = self::validateSortOrder($args[$i + 1] ?? self::ORDER_ASCENDING); } } catch (Exception $e) { return $e->getMessage(); } $temp = self::processSortBy($sortArray, $sortBy, $sortOrder); if ($transpose) { $temp = Matrix::transpose($temp); } return $temp; } /** * @param mixed[] $sortArray * * @return mixed[] */ private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } private static function validateScalarArgumentsForSort(mixed &$sortIndex, mixed &$sortOrder, int $sortArraySize): void { $sortIndex = self::validatePositiveInt($sortIndex, false); if ($sortIndex > $sortArraySize) { throw new Exception(ExcelError::VALUE()); } $sortOrder = self::validateSortOrder($sortOrder); } /** * @param mixed[] $sortVector * * @return mixed[] */ private static function validateSortVector(array $sortVector, int $sortArraySize): array { // It doesn't matter if it's a row or a column vectors, it works either way $sortVector = Functions::flattenArray($sortVector); if (count($sortVector) !== $sortArraySize) { throw new Exception(ExcelError::VALUE()); } return $sortVector; } private static function validateSortOrder(mixed $sortOrder): int { $sortOrder = self::validateInt($sortOrder); if (($sortOrder == self::ORDER_ASCENDING || $sortOrder === self::ORDER_DESCENDING) === false) { throw new Exception(ExcelError::VALUE()); } return $sortOrder; } /** @param mixed[] $sortIndex */ private static function validateArrayArgumentsForSort(array &$sortIndex, mixed &$sortOrder, int $sortArraySize): void { // It doesn't matter if they're row or column vectors, it works either way $sortIndex = Functions::flattenArray($sortIndex); $sortOrder = Functions::flattenArray($sortOrder); if ( count($sortOrder) === 0 || count($sortOrder) > $sortArraySize || (count($sortOrder) > count($sortIndex)) ) { throw new Exception(ExcelError::VALUE()); } if (count($sortIndex) > count($sortOrder)) { // If $sortOrder has fewer elements than $sortIndex, then the last order element is repeated. $sortOrder = array_merge( $sortOrder, array_fill(0, count($sortIndex) - count($sortOrder), array_pop($sortOrder)) ); } foreach ($sortIndex as $key => &$value) { self::validateScalarArgumentsForSort($value, $sortOrder[$key], $sortArraySize); } } /** * @param mixed[] $sortVector * * @return mixed[] */ private static function prepareSortVectorValues(array $sortVector): array { // Strings should be sorted case-insensitive. // Booleans are a complete mess. Excel always seems to sort // booleans in a mixed vector at either the top or the bottom, // so converting them to string or int doesn't really work. // Best advice is to use them in a boolean-only vector. // Code below chooses int conversion, which is sensible, // and, as a bonus, compatible with LibreOffice. return array_map( function ($value) { if (is_bool($value)) { return (int) $value; } if (is_string($value)) { return StringHelper::strToLower($value); } return $value; }, $sortVector ); } /** * @param mixed[] $sortArray * @param mixed[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function processSortBy(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; /** @var mixed[] */ $sortData = []; foreach ($sortIndex as $index => $sortValues) { /** @var mixed[] $sortValues */ $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortVector = self::executeVectorSortQuery($sortData, $sortArguments); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param mixed[] $sortArray * @param int[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function sortByRow(array $sortArray, array $sortIndex, array $sortOrder): array { $sortVector = self::buildVectorForSort($sortArray, $sortIndex, $sortOrder); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param mixed[] $sortArray * @param int[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function sortByColumn(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArray = Matrix::transpose($sortArray); $result = self::sortByRow($sortArray, $sortIndex, $sortOrder); return Matrix::transpose($result); } /** * @param mixed[] $sortArray * @param int[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function buildVectorForSort(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; $sortData = []; foreach ($sortIndex as $index => $sortIndexValue) { $sortValues = array_column($sortArray, $sortIndexValue - 1); $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortData = self::executeVectorSortQuery($sortData, $sortArguments); return $sortData; } /** * @param mixed[] $sortData * @param mixed[] $sortArguments * * @return mixed[] */ private static function executeVectorSortQuery(array $sortData, array $sortArguments): array { $sortData = Matrix::transpose($sortData); // We need to set an index that can be retained, as array_multisort doesn't maintain numeric keys. $sortDataIndexed = []; foreach ($sortData as $key => $value) { $sortDataIndexed[Coordinate::stringFromColumnIndex($key + 1)] = $value; } unset($sortData); $sortArguments[] = &$sortDataIndexed; array_multisort(...$sortArguments); // After the sort, we restore the numeric keys that will now be in the correct, sorted order $sortedData = []; foreach (array_keys($sortDataIndexed) as $key) { $sortedData[] = Coordinate::columnIndexFromString($key) - 1; } return $sortedData; } /** * @param mixed[] $sortArray * @param mixed[] $sortVector * * @return mixed[] */ private static function sortLookupArrayFromVector(array $sortArray, array $sortVector): array { // Building a new array in the correct (sorted) order works; but may be memory heavy for larger arrays $sortedArray = []; foreach ($sortVector as $index) { /** @var int|string $index */ $sortedArray[] = $sortArray[$index]; } return $sortedArray; // uksort( // $lookupArray, // function (int $a, int $b) use (array $sortVector) { // return $sortVector[$a] <=> $sortVector[$b]; // } // ); // // return $lookupArray; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/TorowTocol.php ================================================ [$x]), $result); } return $result; } /** * Excel function TOROW. * * @return mixed[]|string */ public static function torow(mixed $array, mixed $ignore = 0, mixed $byColumn = false): array|string { if (!is_numeric($ignore)) { return ExcelError::VALUE(); } $ignore = (int) $ignore; if ($ignore < 0 || $ignore > 3) { return ExcelError::VALUE(); } if (is_int($byColumn) || is_float($byColumn)) { $byColumn = (bool) $byColumn; } if (!is_bool($byColumn)) { return ExcelError::VALUE(); } if (!is_array($array)) { $array = [$array]; } if ($byColumn) { $temp = []; foreach ($array as $row) { if (!is_array($row)) { $row = [$row]; } $temp[] = Functions::flattenArray($row); } $array = ChooseRowsEtc::transpose($temp); } else { $array = Functions::flattenArray($array); } return self::byRow($array, $ignore); } /** * @param mixed[] $array * * @return mixed[] */ private static function byRow(array $array, int $ignore): array { $returnMatrix = []; foreach ($array as $row) { if (!is_array($row)) { $row = [$row]; } foreach ($row as $cell) { if ($cell === null) { if ($ignore === 1 || $ignore === 3) { continue; } $cell = 0; } elseif (ErrorValue::isError($cell, true)) { if ($ignore === 2 || $ignore === 3) { continue; } } $returnMatrix[] = $cell; } } return $returnMatrix; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Unique.php ================================================ count($flattenedLookupVector, COUNT_RECURSIVE) + 1) { // We're looking at a full column check (multiple rows) $transpose = Matrix::transpose($lookupVector); $result = self::uniqueByRow($transpose, $exactlyOnce); return (is_array($result)) ? Matrix::transpose($result) : $result; } $result = self::countValuesCaseInsensitive($flattenedLookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); return $result; } /** * @param string[] $caseSensitiveLookupValues * * @return mixed[] */ private static function countValuesCaseInsensitive(array $caseSensitiveLookupValues): array { $caseInsensitiveCounts = array_count_values( array_map( fn (string $value): string => StringHelper::strToUpper($value), $caseSensitiveLookupValues ) ); $caseSensitiveCounts = []; foreach ($caseInsensitiveCounts as $caseInsensitiveKey => $count) { if (is_numeric($caseInsensitiveKey)) { $caseSensitiveCounts[$caseInsensitiveKey] = $count; } else { foreach ($caseSensitiveLookupValues as $caseSensitiveValue) { if ($caseInsensitiveKey === StringHelper::strToUpper($caseSensitiveValue)) { $caseSensitiveCounts[$caseSensitiveValue] = $count; break; } } } } return $caseSensitiveCounts; } /** * @param mixed[] $values * * @return mixed[] */ private static function exactlyOnceFilter(array $values): array { return array_filter( $values, fn ($value): bool => $value === 1 ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php ================================================ |float|int|string $indexNumber The column number in table_array from which the matching value must be returned. * The first column is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, $lookupArray, mixed $indexNumber, mixed $notExactMatch = true): mixed { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = array_pop($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) { return ExcelError::REF(); } $columnKeys = array_keys($lookupArray[$firstRow]); $returnColumn = $columnKeys[--$indexNumber]; $firstColumn = array_shift($columnKeys) ?? 1; if (!$notExactMatch) { /** @var callable $callable */ $callable = [self::class, 'vlookupSort']; uasort($lookupArray, $callable); } /** @var string[][] $lookupArray */ $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // return the appropriate value return $lookupArray[$rowNumber][$returnColumn]; } return ExcelError::NA(); } /** * @param scalar[] $a * @param scalar[] $b */ private static function vlookupSort(array $a, array $b): int { reset($a); $firstColumn = key($a); $aLower = StringHelper::strToLower((string) $a[$firstColumn]); $bLower = StringHelper::strToLower((string) $b[$firstColumn]); if ($aLower == $bLower) { return 0; } return ($aLower < $bLower) ? -1 : 1; } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param string[][] $lookupArray * @param int|string $column */ private static function vLookupSearch(mixed $lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower(StringHelper::convertToString($lookupValue)); $rowNumber = null; foreach ($lookupArray as $rowKey => $rowData) { $bothNumeric = self::numeric($lookupValue) && self::numeric($rowData[$column]); $bothNotNumeric = !self::numeric($lookupValue) && !self::numeric($rowData[$column]); $cellDataLower = StringHelper::strToLower((string) $rowData[$column]); // break if we have passed possible keys if ( $notExactMatch && (($bothNumeric && ($rowData[$column] > $lookupValue)) || ($bothNotNumeric && ($cellDataLower > $lookupLower))) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, $rowKey, $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } private static function numeric(mixed $value): bool { return is_int($value) || is_float($value); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/LookupRef/Vstack.php ================================================ |float|int|string rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $number): array|string|int|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return abs($number); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Angle.php ================================================ |float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function toDegrees(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return rad2deg($number); } /** * RADIANS. * * Returns the result of builtin function deg2rad after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function toRadians(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return deg2rad($number); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php ================================================ 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1, ]; /** * Recursively calculate the arabic value of a roman numeral. * * @param string[] $roman */ private static function calculateArabic(array $roman, int &$sum = 0, int $subtract = 0): int { $numeral = array_shift($roman); if (!isset(self::ROMAN_LOOKUP[$numeral])) { throw new Exception('Invalid character detected'); } $arabic = self::ROMAN_LOOKUP[$numeral]; if (count($roman) > 0 && isset(self::ROMAN_LOOKUP[$roman[0]]) && $arabic < self::ROMAN_LOOKUP[$roman[0]]) { $subtract += $arabic; } else { $sum += ($arabic - $subtract); $subtract = 0; } if (count($roman) > 0) { self::calculateArabic($roman, $sum, $subtract); } return $sum; } /** * ARABIC. * * Converts a Roman numeral to an Arabic numeral. * * Excel Function: * ARABIC(text) * * @param string|string[] $roman Should be a string, or can be an array of strings * * @return array|int|string the arabic numeral contrived from the roman numeral * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $roman): array|int|string { if (is_array($roman)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $roman); } // An empty string should return 0 $roman = substr(trim(strtoupper((string) $roman)), 0, 255); if ($roman === '') { return 0; } // Convert the roman numeral to an arabic number $negativeNumber = $roman[0] === '-'; if ($negativeNumber) { $roman = trim(substr($roman, 1)); if ($roman === '') { return ExcelError::NAN(); } } try { $arabic = self::calculateArabic(mb_str_split($roman, 1, 'UTF-8')); } catch (Exception) { return ExcelError::VALUE(); // Invalid character detected } if ($negativeNumber) { $arabic *= -1; // The number should be negative } return $arabic; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Base.php ================================================ |string the text representation with the given radix (base) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $number, mixed $radix, mixed $minLength = null): array|string { if (is_array($number) || is_array($radix) || is_array($minLength)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $radix, $minLength); } try { $number = (float) floor(Helpers::validateNumericNullBool($number)); $radix = (int) Helpers::validateNumericNullBool($radix); } catch (Exception $e) { return $e->getMessage(); } return self::calculate($number, $radix, $minLength); } private static function calculate(float $number, int $radix, mixed $minLength): string { if ($minLength === null || is_numeric($minLength)) { if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { return ExcelError::NAN(); // Numeric range constraints } $outcome = strtoupper((string) base_convert("$number", 10, $radix)); if ($minLength !== null) { $outcome = str_pad($outcome, (int) $minLength, '0', STR_PAD_LEFT); // String padding } return $outcome; } return ExcelError::VALUE(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php ================================================ |float $number the number you want the ceiling * Or can be an array of values * @param array|float $significance the multiple to which you want to round * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ceiling($number, $significance = null) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } if ($significance === null) { self::floorCheck1Arg(); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOk((float) $number, (float) $significance); } /** * CEILING.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * CEILING.MATH(number[,significance[,mode]]) * * @param mixed $number Number to round * Or can be an array of values * @param mixed $significance Significance * Or can be an array of values * @param array|int $mode direction to round negative numbers * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function math(mixed $number, mixed $significance = null, $mode = 0, bool $checkSigns = false): array|string|float { if (is_array($number) || is_array($significance) || is_array($mode)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); $mode = Helpers::validateNumericNullSubstitution($mode, null); } catch (Exception $e) { return $e->getMessage(); } if (empty($significance * $number)) { return 0.0; } if ($checkSigns) { if (($number > 0 && $significance < 0) || ($number < 0 && $significance > 0)) { return ExcelError::NAN(); } } if (self::ceilingMathTest((float) $significance, (float) $number, (int) $mode)) { return floor($number / $significance) * $significance; } return ceil($number / $significance) * $significance; } /** * CEILING.PRECISE. * * Rounds number up, away from zero, to the nearest multiple of significance. * * Excel Function: * CEILING.PRECISE(number[,significance]) * * @param mixed $number the number you want to round * Or can be an array of values * @param array|float $significance the multiple to which you want to round * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function precise(mixed $number, $significance = 1): array|string|float { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, null); } catch (Exception $e) { return $e->getMessage(); } if (!$significance) { return 0.0; } $result = $number / abs($significance); return ceil($result) * $significance * (($significance < 0) ? -1 : 1); } /** * CEILING.ODS, pseudo-function - CEILING as implemented in ODS. * * ODS Function (theoretical): * CEILING.ODS(number[,significance[,mode]]) * * @param mixed $number Number to round * @param mixed $significance Significance * @param array|int $mode direction to round negative numbers * * @return array|float|string Rounded Number, or a string containing an error */ public static function mathOds(mixed $number, mixed $significance = null, $mode = 0): array|string|float { return self::math($number, $significance, $mode, true); } /** * Let CEILINGMATH complexity pass Scrutinizer. */ private static function ceilingMathTest(float $significance, float $number, int $mode): bool { return ($significance < 0) || ($number < 0 && !empty($mode)); } /** * Avoid Scrutinizer problems concerning complexity. */ private static function argumentsOk(float $number, float $significance): float|string { if (empty($number * $significance)) { return 0.0; } $signSig = Helpers::returnSign($significance); $signNum = Helpers::returnSign($number); if ( ($signSig === 1 && ($signNum === 1 || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC)) || ($signSig === -1 && $signNum === -1) ) { return ceil($number / $significance) * $significance; } return ExcelError::NAN(); } private static function floorCheck1Arg(): void { $compatibility = Functions::getCompatibilityMode(); if ($compatibility === Functions::COMPATIBILITY_EXCEL) { throw new Exception('Excel requires 2 arguments for CEILING'); } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php ================================================ |float|string Number of combinations, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function withoutRepetition(mixed $numObjs, mixed $numInSet): array|string|float { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); Helpers::validateNotNegative($numInSet); Helpers::validateNotNegative($numObjs - $numInSet); } catch (Exception $e) { return $e->getMessage(); } /** @var float */ $quotient = Factorial::fact($numObjs); /** @var float */ $divisor1 = Factorial::fact($numObjs - $numInSet); /** @var float */ $divisor2 = Factorial::fact($numInSet); return round($quotient / ($divisor1 * $divisor2)); } /** * COMBINA. * * Returns the number of combinations for a given number of items. Use COMBIN to * determine the total possible number of groups for a given number of items. * * Excel Function: * COMBINA(numObjs,numInSet) * * @param mixed $numObjs Number of different objects, or can be an array of numbers * @param mixed $numInSet Number of objects in each combination, or can be an array of numbers * * @return array|float|int|string Number of combinations, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function withRepetition(mixed $numObjs, mixed $numInSet): array|int|string|float { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); Helpers::validateNotNegative($numInSet); Helpers::validateNotNegative($numObjs); $numObjs = (int) $numObjs; $numInSet = (int) $numInSet; // Microsoft documentation says following is true, but Excel // does not enforce this restriction. //Helpers::validateNotNegative($numObjs - $numInSet); if ($numObjs === 0) { Helpers::validateNotNegative(-$numInSet); return 1; } } catch (Exception $e) { return $e->getMessage(); } /** @var float */ $quotient = Factorial::fact($numObjs + $numInSet - 1); /** @var float */ $divisor1 = Factorial::fact($numObjs - 1); /** @var float */ $divisor2 = Factorial::fact($numInSet); return round($quotient / ($divisor1 * $divisor2)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Exp.php ================================================ |float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return exp($number); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php ================================================ |float $factVal Factorial Value, or can be an array of numbers * * @return array|float|int|string Factorial, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fact($factVal): array|string|float|int { if (is_array($factVal)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); } try { $factVal = Helpers::validateNumericNullBool($factVal); Helpers::validateNotNegative($factVal); } catch (Exception $e) { return $e->getMessage(); } $factLoop = floor($factVal); if ($factVal > $factLoop) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return Statistical\Distributions\Gamma::gammaValue($factVal + 1); } } $factorial = 1; while ($factLoop > 1) { $factorial *= $factLoop--; } return $factorial; } /** * FACTDOUBLE. * * Returns the double factorial of a number. * * Excel Function: * FACTDOUBLE(factVal) * * @param array|float $factVal Factorial Value, or can be an array of numbers * * @return array|float|int|string Double Factorial, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function factDouble($factVal): array|string|float|int { if (is_array($factVal)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); } try { $factVal = Helpers::validateNumericNullSubstitution($factVal, 0); Helpers::validateNotNegative($factVal); } catch (Exception $e) { return $e->getMessage(); } $factLoop = floor($factVal); $factorial = 1; while ($factLoop > 1) { $factorial *= $factLoop; $factLoop -= 2; } return $factorial; } /** * MULTINOMIAL. * * Returns the ratio of the factorial of a sum of values to the product of factorials. * * @param mixed[] $args An array of mixed values for the Data Series * * @return float|int|string The result, or a string containing an error */ public static function multinomial(...$args): string|int|float { $summer = 0; $divisor = 1; try { // Loop through arguments foreach (Functions::flattenArray($args) as $argx) { $arg = Helpers::validateNumericNullSubstitution($argx, null); Helpers::validateNotNegative($arg); $arg = (int) $arg; $summer += $arg; /** @var float|int */ $temp = self::fact($arg); $divisor *= $temp; } } catch (Exception $e) { return $e->getMessage(); } $summer = self::fact($summer); return is_numeric($summer) ? ($summer / $divisor) : ExcelError::VALUE(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Floor.php ================================================ |float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function floor(mixed $number, mixed $significance = null) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } if ($significance === null) { self::floorCheck1Arg(); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOk((float) $number, (float) $significance); } /** * FLOOR.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * FLOOR.MATH(number[,significance[,mode]]) * * @param mixed $number Number to round * Or can be an array of values * @param mixed $significance Significance * Or can be an array of values * @param mixed $mode direction to round negative numbers * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function math(mixed $number, mixed $significance = null, mixed $mode = 0, bool $checkSigns = false) { if (is_array($number) || is_array($significance) || is_array($mode)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); $mode = Helpers::validateNumericNullSubstitution($mode, null); } catch (Exception $e) { return $e->getMessage(); } if (empty($significance * $number)) { return 0.0; } if ($checkSigns) { if (($number > 0 && $significance < 0) || ($number < 0 && $significance > 0)) { return ExcelError::NAN(); } } return self::argsOk((float) $number, (float) $significance, (int) $mode); } /** * FLOOR.ODS, pseudo-function - FLOOR as implemented in ODS. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * ODS Function (theoretical): * FLOOR.ODS(number[,significance[,mode]]) * * @param mixed $number Number to round * @param mixed $significance Significance * @param array|int $mode direction to round negative numbers * * @return array|float|string Rounded Number, or a string containing an error */ public static function mathOds(mixed $number, mixed $significance = null, mixed $mode = 0) { return self::math($number, $significance, $mode, true); } /** * FLOOR.PRECISE. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR.PRECISE(number[,significance]) * * @param array|float $number Number to round * Or can be an array of values * @param array|float $significance Significance * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function precise($number, $significance = 1) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, null); } catch (Exception $e) { return $e->getMessage(); } if (!$significance) { return 0.0; } return self::argumentsOkPrecise((float) $number, (float) $significance); } /** * Avoid Scrutinizer problems concerning complexity. */ private static function argumentsOkPrecise(float $number, float $significance): string|float { if ($significance == 0.0) { return ExcelError::DIV0(); } if ($number == 0.0) { return 0.0; } return floor($number / abs($significance)) * abs($significance); } /** * Avoid Scrutinizer complexity problems. * * @return float|string Rounded Number, or a string containing an error */ private static function argsOk(float $number, float $significance, int $mode): string|float { if (!$significance) { return ExcelError::DIV0(); } if (!$number) { return 0.0; } if (self::floorMathTest($number, $significance, $mode)) { return ceil($number / $significance) * $significance; } return floor($number / $significance) * $significance; } /** * Let FLOORMATH complexity pass Scrutinizer. */ private static function floorMathTest(float $number, float $significance, int $mode): bool { return Helpers::returnSign($significance) == -1 || (Helpers::returnSign($number) == -1 && !empty($mode)); } /** * Avoid Scrutinizer problems concerning complexity. */ private static function argumentsOk(float $number, float $significance): string|float { if ($significance == 0.0) { return ExcelError::DIV0(); } if ($number == 0.0) { return 0.0; } $signSig = Helpers::returnSign($significance); $signNum = Helpers::returnSign($number); if ( ($signSig === 1 && ($signNum === 1 || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC)) || ($signNum === -1 && $signSig === -1) ) { return floor($number / $significance) * $significance; } return ExcelError::NAN(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php ================================================ getMessage(); } if (count($arrayArgs) <= 0) { return ExcelError::VALUE(); } $gcd = (int) array_pop($arrayArgs); do { $gcd = self::evaluateGCD($gcd, (int) array_pop($arrayArgs)); } while (!empty($arrayArgs)); return $gcd; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php ================================================ = 0. */ public static function validateNotNegative(float|int $number, ?string $except = null): void { if ($number >= 0) { return; } throw new Exception($except ?? ExcelError::NAN()); } /** * Confirm number > 0. */ public static function validatePositive(float|int $number, ?string $except = null): void { if ($number > 0) { return; } throw new Exception($except ?? ExcelError::NAN()); } /** * Confirm number != 0. */ public static function validateNotZero(float|int $number): void { if ($number) { return; } throw new Exception(ExcelError::DIV0()); } public static function returnSign(float $number): int { return $number ? (($number > 0) ? 1 : -1) : 0; } public static function getEven(float $number): float { $significance = 2 * self::returnSign($number); return $significance ? (ceil($number / $significance) * $significance) : 0; } /** * Return NAN or value depending on argument. */ public static function numberOrNan(float $result): float|string { return is_nan($result) ? ExcelError::NAN() : $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php ================================================ |float $number Number to cast to an integer, or can be an array of numbers * * @return array|int|string Integer value, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number): array|string|int { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return (int) floor($number); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php ================================================ 1; --$i) { if (($value % $i) == 0) { $factorArray = array_merge($factorArray, self::factors($value / $i)); $factorArray = array_merge($factorArray, self::factors($i)); if ($i <= sqrt($value)) { break; } } } if (!empty($factorArray)) { rsort($factorArray); /** @var int[] $factorArray */ return $factorArray; } return [(int) $value]; } /** * LCM. * * Returns the lowest common multiplier of a series of numbers * The least common multiple is the smallest positive integer that is a multiple * of all integer arguments number1, number2, and so on. Use LCM to add fractions * with different denominators. * * Excel Function: * LCM(number1[,number2[, ...]]) * * @param mixed ...$args Data values * * @return int|string Lowest Common Multiplier, or a string containing an error */ public static function evaluate(mixed ...$args): int|string { try { $arrayArgs = []; $anyZeros = 0; $anyNonNulls = 0; foreach (Functions::flattenArray($args) as $value1) { $anyNonNulls += (int) ($value1 !== null); $value = Helpers::validateNumericNullSubstitution($value1, 1); Helpers::validateNotNegative($value); $arrayArgs[] = (int) $value; $anyZeros += (int) !((bool) $value); } self::testNonNulls($anyNonNulls); if ($anyZeros) { return 0; } } catch (Exception $e) { return $e->getMessage(); } $returnValue = 1; $allPoweredFactors = []; // Loop through arguments foreach ($arrayArgs as $value) { $myFactors = self::factors(floor($value)); $myCountedFactors = array_count_values($myFactors); $myPoweredFactors = []; foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower; } self::processPoweredFactors($allPoweredFactors, $myPoweredFactors); } foreach ($allPoweredFactors as $allPoweredFactor) { /** @var scalar $allPoweredFactor */ $returnValue *= (int) $allPoweredFactor; } return $returnValue; } /** * @param mixed[] $allPoweredFactors * @param mixed[] $myPoweredFactors */ private static function processPoweredFactors(array &$allPoweredFactors, array &$myPoweredFactors): void { foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { if (isset($allPoweredFactors[$myPoweredValue])) { if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; } } else { $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; } } } private static function testNonNulls(int $anyNonNulls): void { if (!$anyNonNulls) { throw new Exception(ExcelError::VALUE()); } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function withBase(mixed $number, mixed $base = 10): array|string|float { if (is_array($number) || is_array($base)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $base); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); $base = Helpers::validateNumericNullBool($base); Helpers::validatePositive($base); } catch (Exception $e) { return $e->getMessage(); } return log($number, $base); } /** * LOG10. * * Returns the result of builtin function log after validating args. * * @param mixed $number Should be numeric * Or can be an array of values * * @return array|float|string Rounded number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function base10(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); } catch (Exception $e) { return $e->getMessage(); } return log10($number); } /** * LN. * * Returns the result of builtin function log after validating args. * * @param mixed $number Should be numeric * Or can be an array of values * * @return array|float|string Rounded number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function natural(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); } catch (Exception $e) { return $e->getMessage(); } return log($number); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php ================================================ |string The resulting array, or a string containing an error */ public static function sequence(mixed $rows = 1, mixed $columns = 1, mixed $start = 1, mixed $step = 1): string|array { try { $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); Helpers::validatePositive($rows); $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); Helpers::validatePositive($columns); $start = Helpers::validateNumericNullSubstitution($start, 1); $step = Helpers::validateNumericNullSubstitution($step, 1); } catch (Exception $e) { return $e->getMessage(); } if ($step === 0) { return array_chunk( array_fill(0, $rows * $columns, $start), max($columns, 1) ); } return array_chunk( range($start, $start + (($rows * $columns - 1) * $step), $step), max($columns, 1) ); } /** * MDETERM. * * Returns the matrix determinant of an array. * * Excel Function: * MDETERM(array) * * @param mixed $matrixValues A matrix of values * * @return float|string The result, or a string containing an error */ public static function determinant(mixed $matrixValues) { try { $matrix = self::getMatrix($matrixValues); return $matrix->determinant(); } catch (MatrixException) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MINVERSE. * * Returns the inverse matrix for the matrix stored in an array. * * Excel Function: * MINVERSE(array) * * @param mixed $matrixValues A matrix of values * * @return array|string The result, or a string containing an error */ public static function inverse(mixed $matrixValues): array|string { try { $matrix = self::getMatrix($matrixValues); return $matrix->inverse()->toArray(); } catch (MatrixDiv0Exception) { return ExcelError::NAN(); } catch (MatrixException) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MMULT. * * @param mixed $matrixData1 A matrix of values * @param mixed $matrixData2 A matrix of values * * @return array|string The result, or a string containing an error */ public static function multiply(mixed $matrixData1, mixed $matrixData2): array|string { try { $matrixA = self::getMatrix($matrixData1); $matrixB = self::getMatrix($matrixData2); return $matrixA->multiply($matrixB)->toArray(); } catch (MatrixException) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MUnit. * * @param mixed $dimension Number of rows and columns * * @return array|string The result, or a string containing an error */ public static function identity(mixed $dimension) { try { $dimension = (int) Helpers::validateNumericNullBool($dimension); Helpers::validatePositive($dimension, ExcelError::VALUE()); $matrix = Builder::createIdentityMatrix($dimension, 0)->toArray(); return $matrix; } catch (Exception $e) { return $e->getMessage(); } } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Operations.php ================================================ |float|string Remainder, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function mod(mixed $dividend, mixed $divisor): array|string|float { if (is_array($dividend) || is_array($divisor)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dividend, $divisor); } try { $dividend = Helpers::validateNumericNullBool($dividend); $divisor = Helpers::validateNumericNullBool($divisor); Helpers::validateNotZero($divisor); } catch (Exception $e) { return $e->getMessage(); } if (($dividend < 0.0) && ($divisor > 0.0)) { return $divisor - fmod(abs($dividend), $divisor); } if (($dividend > 0.0) && ($divisor < 0.0)) { return $divisor + fmod($dividend, abs($divisor)); } return fmod($dividend, $divisor); } /** * POWER. * * Computes x raised to the power y. * * @param null|array|bool|float|int|string $x Or can be an array of values * @param null|array|bool|float|int|string $y Or can be an array of values * * @return array|float|int|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function power(null|array|bool|float|int|string $x, null|array|bool|float|int|string $y): array|float|int|string { if (is_array($x) || is_array($y)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $y); } try { $x = Helpers::validateNumericNullBool($x); $y = Helpers::validateNumericNullBool($y); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if (!$x && !$y) { return ExcelError::NAN(); } if (!$x && $y < 0.0) { return ExcelError::DIV0(); } // Return $result = $x ** $y; return Helpers::numberOrNan($result); } /** * PRODUCT. * * PRODUCT returns the product of all the values and cells referenced in the argument list. * * Excel Function: * PRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function product(mixed ...$args): string|float { $args = array_filter( Functions::flattenArray($args), fn ($value): bool => $value !== null ); // Return value $returnValue = (count($args) === 0) ? 0.0 : 1.0; // Loop through arguments foreach ($args as $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue *= $arg; } else { return ExcelError::throwError($arg); } } return (float) $returnValue; } /** * QUOTIENT. * * QUOTIENT function returns the integer portion of a division. Numerator is the divided number * and denominator is the divisor. * * Excel Function: * QUOTIENT(value1,value2) * * @param mixed $numerator Expect float|int * Or can be an array of values * @param mixed $denominator Expect float|int * Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function quotient(mixed $numerator, mixed $denominator): array|string|int { if (is_array($numerator) || is_array($denominator)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numerator, $denominator); } try { $numerator = Helpers::validateNumericNullSubstitution($numerator, 0); $denominator = Helpers::validateNumericNullSubstitution($denominator, 0); Helpers::validateNotZero($denominator); } catch (Exception $e) { return $e->getMessage(); } return (int) ($numerator / $denominator); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Random.php ================================================ |int|string Random number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function randBetween(mixed $min, mixed $max): array|string|int { if (is_array($min) || is_array($max)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $min, $max); } try { $min = (int) Helpers::validateNumericNullBool($min); $max = (int) Helpers::validateNumericNullBool($max); Helpers::validateNotNegative($max - $min); } catch (Exception $e) { return $e->getMessage(); } return mt_rand($min, $max); } /** * RANDARRAY. * * Generates a list of sequential numbers in an array. * * Excel Function: * RANDARRAY([rows],[columns],[start],[step]) * * @param mixed $rows the number of rows to return, defaults to 1 * @param mixed $columns the number of columns to return, defaults to 1 * @param mixed $min the minimum number to be returned, defaults to 0 * @param mixed $max the maximum number to be returned, defaults to 1 * @param bool $wholeNumber the type of numbers to return: * False - Decimal numbers to 15 decimal places. (default) * True - Whole (integer) numbers * * @return array|string The resulting array, or a string containing an error */ public static function randArray(mixed $rows = 1, mixed $columns = 1, mixed $min = 0, mixed $max = 1, bool $wholeNumber = false): string|array { try { $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); Helpers::validatePositive($rows); $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); Helpers::validatePositive($columns); $min = Helpers::validateNumericNullSubstitution($min, 1); $max = Helpers::validateNumericNullSubstitution($max, 1); if ($max <= $min) { return ExcelError::VALUE(); } } catch (Exception $e) { return $e->getMessage(); } return array_chunk( array_map( fn (): int|float => $wholeNumber ? mt_rand((int) $min, (int) $max) : (mt_rand() / mt_getrandmax()) * ($max - $min) + $min, array_fill(0, $rows * $columns, $min) ), max($columns, 1) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Roman.php ================================================ ['VL'], 46 => ['VLI'], 47 => ['VLII'], 48 => ['VLIII'], 49 => ['VLIV', 'IL'], 95 => ['VC'], 96 => ['VCI'], 97 => ['VCII'], 98 => ['VCIII'], 99 => ['VCIV', 'IC'], 145 => ['CVL'], 146 => ['CVLI'], 147 => ['CVLII'], 148 => ['CVLIII'], 149 => ['CVLIV', 'CIL'], 195 => ['CVC'], 196 => ['CVCI'], 197 => ['CVCII'], 198 => ['CVCIII'], 199 => ['CVCIV', 'CIC'], 245 => ['CCVL'], 246 => ['CCVLI'], 247 => ['CCVLII'], 248 => ['CCVLIII'], 249 => ['CCVLIV', 'CCIL'], 295 => ['CCVC'], 296 => ['CCVCI'], 297 => ['CCVCII'], 298 => ['CCVCIII'], 299 => ['CCVCIV', 'CCIC'], 345 => ['CCCVL'], 346 => ['CCCVLI'], 347 => ['CCCVLII'], 348 => ['CCCVLIII'], 349 => ['CCCVLIV', 'CCCIL'], 395 => ['CCCVC'], 396 => ['CCCVCI'], 397 => ['CCCVCII'], 398 => ['CCCVCIII'], 399 => ['CCCVCIV', 'CCCIC'], 445 => ['CDVL'], 446 => ['CDVLI'], 447 => ['CDVLII'], 448 => ['CDVLIII'], 449 => ['CDVLIV', 'CDIL'], 450 => ['LD'], 451 => ['LDI'], 452 => ['LDII'], 453 => ['LDIII'], 454 => ['LDIV'], 455 => ['LDV'], 456 => ['LDVI'], 457 => ['LDVII'], 458 => ['LDVIII'], 459 => ['LDIX'], 460 => ['LDX'], 461 => ['LDXI'], 462 => ['LDXII'], 463 => ['LDXIII'], 464 => ['LDXIV'], 465 => ['LDXV'], 466 => ['LDXVI'], 467 => ['LDXVII'], 468 => ['LDXVIII'], 469 => ['LDXIX'], 470 => ['LDXX'], 471 => ['LDXXI'], 472 => ['LDXXII'], 473 => ['LDXXIII'], 474 => ['LDXXIV'], 475 => ['LDXXV'], 476 => ['LDXXVI'], 477 => ['LDXXVII'], 478 => ['LDXXVIII'], 479 => ['LDXXIX'], 480 => ['LDXXX'], 481 => ['LDXXXI'], 482 => ['LDXXXII'], 483 => ['LDXXXIII'], 484 => ['LDXXXIV'], 485 => ['LDXXXV'], 486 => ['LDXXXVI'], 487 => ['LDXXXVII'], 488 => ['LDXXXVIII'], 489 => ['LDXXXIX'], 490 => ['LDXL', 'XD'], 491 => ['LDXLI', 'XDI'], 492 => ['LDXLII', 'XDII'], 493 => ['LDXLIII', 'XDIII'], 494 => ['LDXLIV', 'XDIV'], 495 => ['LDVL', 'XDV', 'VD'], 496 => ['LDVLI', 'XDVI', 'VDI'], 497 => ['LDVLII', 'XDVII', 'VDII'], 498 => ['LDVLIII', 'XDVIII', 'VDIII'], 499 => ['LDVLIV', 'XDIX', 'VDIV', 'ID'], 545 => ['DVL'], 546 => ['DVLI'], 547 => ['DVLII'], 548 => ['DVLIII'], 549 => ['DVLIV', 'DIL'], 595 => ['DVC'], 596 => ['DVCI'], 597 => ['DVCII'], 598 => ['DVCIII'], 599 => ['DVCIV', 'DIC'], 645 => ['DCVL'], 646 => ['DCVLI'], 647 => ['DCVLII'], 648 => ['DCVLIII'], 649 => ['DCVLIV', 'DCIL'], 695 => ['DCVC'], 696 => ['DCVCI'], 697 => ['DCVCII'], 698 => ['DCVCIII'], 699 => ['DCVCIV', 'DCIC'], 745 => ['DCCVL'], 746 => ['DCCVLI'], 747 => ['DCCVLII'], 748 => ['DCCVLIII'], 749 => ['DCCVLIV', 'DCCIL'], 795 => ['DCCVC'], 796 => ['DCCVCI'], 797 => ['DCCVCII'], 798 => ['DCCVCIII'], 799 => ['DCCVCIV', 'DCCIC'], 845 => ['DCCCVL'], 846 => ['DCCCVLI'], 847 => ['DCCCVLII'], 848 => ['DCCCVLIII'], 849 => ['DCCCVLIV', 'DCCCIL'], 895 => ['DCCCVC'], 896 => ['DCCCVCI'], 897 => ['DCCCVCII'], 898 => ['DCCCVCIII'], 899 => ['DCCCVCIV', 'DCCCIC'], 945 => ['CMVL'], 946 => ['CMVLI'], 947 => ['CMVLII'], 948 => ['CMVLIII'], 949 => ['CMVLIV', 'CMIL'], 950 => ['LM'], 951 => ['LMI'], 952 => ['LMII'], 953 => ['LMIII'], 954 => ['LMIV'], 955 => ['LMV'], 956 => ['LMVI'], 957 => ['LMVII'], 958 => ['LMVIII'], 959 => ['LMIX'], 960 => ['LMX'], 961 => ['LMXI'], 962 => ['LMXII'], 963 => ['LMXIII'], 964 => ['LMXIV'], 965 => ['LMXV'], 966 => ['LMXVI'], 967 => ['LMXVII'], 968 => ['LMXVIII'], 969 => ['LMXIX'], 970 => ['LMXX'], 971 => ['LMXXI'], 972 => ['LMXXII'], 973 => ['LMXXIII'], 974 => ['LMXXIV'], 975 => ['LMXXV'], 976 => ['LMXXVI'], 977 => ['LMXXVII'], 978 => ['LMXXVIII'], 979 => ['LMXXIX'], 980 => ['LMXXX'], 981 => ['LMXXXI'], 982 => ['LMXXXII'], 983 => ['LMXXXIII'], 984 => ['LMXXXIV'], 985 => ['LMXXXV'], 986 => ['LMXXXVI'], 987 => ['LMXXXVII'], 988 => ['LMXXXVIII'], 989 => ['LMXXXIX'], 990 => ['LMXL', 'XM'], 991 => ['LMXLI', 'XMI'], 992 => ['LMXLII', 'XMII'], 993 => ['LMXLIII', 'XMIII'], 994 => ['LMXLIV', 'XMIV'], 995 => ['LMVL', 'XMV', 'VM'], 996 => ['LMVLI', 'XMVI', 'VMI'], 997 => ['LMVLII', 'XMVII', 'VMII'], 998 => ['LMVLIII', 'XMVIII', 'VMIII'], 999 => ['LMVLIV', 'XMIX', 'VMIV', 'IM'], 1045 => ['MVL'], 1046 => ['MVLI'], 1047 => ['MVLII'], 1048 => ['MVLIII'], 1049 => ['MVLIV', 'MIL'], 1095 => ['MVC'], 1096 => ['MVCI'], 1097 => ['MVCII'], 1098 => ['MVCIII'], 1099 => ['MVCIV', 'MIC'], 1145 => ['MCVL'], 1146 => ['MCVLI'], 1147 => ['MCVLII'], 1148 => ['MCVLIII'], 1149 => ['MCVLIV', 'MCIL'], 1195 => ['MCVC'], 1196 => ['MCVCI'], 1197 => ['MCVCII'], 1198 => ['MCVCIII'], 1199 => ['MCVCIV', 'MCIC'], 1245 => ['MCCVL'], 1246 => ['MCCVLI'], 1247 => ['MCCVLII'], 1248 => ['MCCVLIII'], 1249 => ['MCCVLIV', 'MCCIL'], 1295 => ['MCCVC'], 1296 => ['MCCVCI'], 1297 => ['MCCVCII'], 1298 => ['MCCVCIII'], 1299 => ['MCCVCIV', 'MCCIC'], 1345 => ['MCCCVL'], 1346 => ['MCCCVLI'], 1347 => ['MCCCVLII'], 1348 => ['MCCCVLIII'], 1349 => ['MCCCVLIV', 'MCCCIL'], 1395 => ['MCCCVC'], 1396 => ['MCCCVCI'], 1397 => ['MCCCVCII'], 1398 => ['MCCCVCIII'], 1399 => ['MCCCVCIV', 'MCCCIC'], 1445 => ['MCDVL'], 1446 => ['MCDVLI'], 1447 => ['MCDVLII'], 1448 => ['MCDVLIII'], 1449 => ['MCDVLIV', 'MCDIL'], 1450 => ['MLD'], 1451 => ['MLDI'], 1452 => ['MLDII'], 1453 => ['MLDIII'], 1454 => ['MLDIV'], 1455 => ['MLDV'], 1456 => ['MLDVI'], 1457 => ['MLDVII'], 1458 => ['MLDVIII'], 1459 => ['MLDIX'], 1460 => ['MLDX'], 1461 => ['MLDXI'], 1462 => ['MLDXII'], 1463 => ['MLDXIII'], 1464 => ['MLDXIV'], 1465 => ['MLDXV'], 1466 => ['MLDXVI'], 1467 => ['MLDXVII'], 1468 => ['MLDXVIII'], 1469 => ['MLDXIX'], 1470 => ['MLDXX'], 1471 => ['MLDXXI'], 1472 => ['MLDXXII'], 1473 => ['MLDXXIII'], 1474 => ['MLDXXIV'], 1475 => ['MLDXXV'], 1476 => ['MLDXXVI'], 1477 => ['MLDXXVII'], 1478 => ['MLDXXVIII'], 1479 => ['MLDXXIX'], 1480 => ['MLDXXX'], 1481 => ['MLDXXXI'], 1482 => ['MLDXXXII'], 1483 => ['MLDXXXIII'], 1484 => ['MLDXXXIV'], 1485 => ['MLDXXXV'], 1486 => ['MLDXXXVI'], 1487 => ['MLDXXXVII'], 1488 => ['MLDXXXVIII'], 1489 => ['MLDXXXIX'], 1490 => ['MLDXL', 'MXD'], 1491 => ['MLDXLI', 'MXDI'], 1492 => ['MLDXLII', 'MXDII'], 1493 => ['MLDXLIII', 'MXDIII'], 1494 => ['MLDXLIV', 'MXDIV'], 1495 => ['MLDVL', 'MXDV', 'MVD'], 1496 => ['MLDVLI', 'MXDVI', 'MVDI'], 1497 => ['MLDVLII', 'MXDVII', 'MVDII'], 1498 => ['MLDVLIII', 'MXDVIII', 'MVDIII'], 1499 => ['MLDVLIV', 'MXDIX', 'MVDIV', 'MID'], 1545 => ['MDVL'], 1546 => ['MDVLI'], 1547 => ['MDVLII'], 1548 => ['MDVLIII'], 1549 => ['MDVLIV', 'MDIL'], 1595 => ['MDVC'], 1596 => ['MDVCI'], 1597 => ['MDVCII'], 1598 => ['MDVCIII'], 1599 => ['MDVCIV', 'MDIC'], 1645 => ['MDCVL'], 1646 => ['MDCVLI'], 1647 => ['MDCVLII'], 1648 => ['MDCVLIII'], 1649 => ['MDCVLIV', 'MDCIL'], 1695 => ['MDCVC'], 1696 => ['MDCVCI'], 1697 => ['MDCVCII'], 1698 => ['MDCVCIII'], 1699 => ['MDCVCIV', 'MDCIC'], 1745 => ['MDCCVL'], 1746 => ['MDCCVLI'], 1747 => ['MDCCVLII'], 1748 => ['MDCCVLIII'], 1749 => ['MDCCVLIV', 'MDCCIL'], 1795 => ['MDCCVC'], 1796 => ['MDCCVCI'], 1797 => ['MDCCVCII'], 1798 => ['MDCCVCIII'], 1799 => ['MDCCVCIV', 'MDCCIC'], 1845 => ['MDCCCVL'], 1846 => ['MDCCCVLI'], 1847 => ['MDCCCVLII'], 1848 => ['MDCCCVLIII'], 1849 => ['MDCCCVLIV', 'MDCCCIL'], 1895 => ['MDCCCVC'], 1896 => ['MDCCCVCI'], 1897 => ['MDCCCVCII'], 1898 => ['MDCCCVCIII'], 1899 => ['MDCCCVCIV', 'MDCCCIC'], 1945 => ['MCMVL'], 1946 => ['MCMVLI'], 1947 => ['MCMVLII'], 1948 => ['MCMVLIII'], 1949 => ['MCMVLIV', 'MCMIL'], 1950 => ['MLM'], 1951 => ['MLMI'], 1952 => ['MLMII'], 1953 => ['MLMIII'], 1954 => ['MLMIV'], 1955 => ['MLMV'], 1956 => ['MLMVI'], 1957 => ['MLMVII'], 1958 => ['MLMVIII'], 1959 => ['MLMIX'], 1960 => ['MLMX'], 1961 => ['MLMXI'], 1962 => ['MLMXII'], 1963 => ['MLMXIII'], 1964 => ['MLMXIV'], 1965 => ['MLMXV'], 1966 => ['MLMXVI'], 1967 => ['MLMXVII'], 1968 => ['MLMXVIII'], 1969 => ['MLMXIX'], 1970 => ['MLMXX'], 1971 => ['MLMXXI'], 1972 => ['MLMXXII'], 1973 => ['MLMXXIII'], 1974 => ['MLMXXIV'], 1975 => ['MLMXXV'], 1976 => ['MLMXXVI'], 1977 => ['MLMXXVII'], 1978 => ['MLMXXVIII'], 1979 => ['MLMXXIX'], 1980 => ['MLMXXX'], 1981 => ['MLMXXXI'], 1982 => ['MLMXXXII'], 1983 => ['MLMXXXIII'], 1984 => ['MLMXXXIV'], 1985 => ['MLMXXXV'], 1986 => ['MLMXXXVI'], 1987 => ['MLMXXXVII'], 1988 => ['MLMXXXVIII'], 1989 => ['MLMXXXIX'], 1990 => ['MLMXL', 'MXM'], 1991 => ['MLMXLI', 'MXMI'], 1992 => ['MLMXLII', 'MXMII'], 1993 => ['MLMXLIII', 'MXMIII'], 1994 => ['MLMXLIV', 'MXMIV'], 1995 => ['MLMVL', 'MXMV', 'MVM'], 1996 => ['MLMVLI', 'MXMVI', 'MVMI'], 1997 => ['MLMVLII', 'MXMVII', 'MVMII'], 1998 => ['MLMVLIII', 'MXMVIII', 'MVMIII'], 1999 => ['MLMVLIV', 'MXMIX', 'MVMIV', 'MIM'], 2045 => ['MMVL'], 2046 => ['MMVLI'], 2047 => ['MMVLII'], 2048 => ['MMVLIII'], 2049 => ['MMVLIV', 'MMIL'], 2095 => ['MMVC'], 2096 => ['MMVCI'], 2097 => ['MMVCII'], 2098 => ['MMVCIII'], 2099 => ['MMVCIV', 'MMIC'], 2145 => ['MMCVL'], 2146 => ['MMCVLI'], 2147 => ['MMCVLII'], 2148 => ['MMCVLIII'], 2149 => ['MMCVLIV', 'MMCIL'], 2195 => ['MMCVC'], 2196 => ['MMCVCI'], 2197 => ['MMCVCII'], 2198 => ['MMCVCIII'], 2199 => ['MMCVCIV', 'MMCIC'], 2245 => ['MMCCVL'], 2246 => ['MMCCVLI'], 2247 => ['MMCCVLII'], 2248 => ['MMCCVLIII'], 2249 => ['MMCCVLIV', 'MMCCIL'], 2295 => ['MMCCVC'], 2296 => ['MMCCVCI'], 2297 => ['MMCCVCII'], 2298 => ['MMCCVCIII'], 2299 => ['MMCCVCIV', 'MMCCIC'], 2345 => ['MMCCCVL'], 2346 => ['MMCCCVLI'], 2347 => ['MMCCCVLII'], 2348 => ['MMCCCVLIII'], 2349 => ['MMCCCVLIV', 'MMCCCIL'], 2395 => ['MMCCCVC'], 2396 => ['MMCCCVCI'], 2397 => ['MMCCCVCII'], 2398 => ['MMCCCVCIII'], 2399 => ['MMCCCVCIV', 'MMCCCIC'], 2445 => ['MMCDVL'], 2446 => ['MMCDVLI'], 2447 => ['MMCDVLII'], 2448 => ['MMCDVLIII'], 2449 => ['MMCDVLIV', 'MMCDIL'], 2450 => ['MMLD'], 2451 => ['MMLDI'], 2452 => ['MMLDII'], 2453 => ['MMLDIII'], 2454 => ['MMLDIV'], 2455 => ['MMLDV'], 2456 => ['MMLDVI'], 2457 => ['MMLDVII'], 2458 => ['MMLDVIII'], 2459 => ['MMLDIX'], 2460 => ['MMLDX'], 2461 => ['MMLDXI'], 2462 => ['MMLDXII'], 2463 => ['MMLDXIII'], 2464 => ['MMLDXIV'], 2465 => ['MMLDXV'], 2466 => ['MMLDXVI'], 2467 => ['MMLDXVII'], 2468 => ['MMLDXVIII'], 2469 => ['MMLDXIX'], 2470 => ['MMLDXX'], 2471 => ['MMLDXXI'], 2472 => ['MMLDXXII'], 2473 => ['MMLDXXIII'], 2474 => ['MMLDXXIV'], 2475 => ['MMLDXXV'], 2476 => ['MMLDXXVI'], 2477 => ['MMLDXXVII'], 2478 => ['MMLDXXVIII'], 2479 => ['MMLDXXIX'], 2480 => ['MMLDXXX'], 2481 => ['MMLDXXXI'], 2482 => ['MMLDXXXII'], 2483 => ['MMLDXXXIII'], 2484 => ['MMLDXXXIV'], 2485 => ['MMLDXXXV'], 2486 => ['MMLDXXXVI'], 2487 => ['MMLDXXXVII'], 2488 => ['MMLDXXXVIII'], 2489 => ['MMLDXXXIX'], 2490 => ['MMLDXL', 'MMXD'], 2491 => ['MMLDXLI', 'MMXDI'], 2492 => ['MMLDXLII', 'MMXDII'], 2493 => ['MMLDXLIII', 'MMXDIII'], 2494 => ['MMLDXLIV', 'MMXDIV'], 2495 => ['MMLDVL', 'MMXDV', 'MMVD'], 2496 => ['MMLDVLI', 'MMXDVI', 'MMVDI'], 2497 => ['MMLDVLII', 'MMXDVII', 'MMVDII'], 2498 => ['MMLDVLIII', 'MMXDVIII', 'MMVDIII'], 2499 => ['MMLDVLIV', 'MMXDIX', 'MMVDIV', 'MMID'], 2545 => ['MMDVL'], 2546 => ['MMDVLI'], 2547 => ['MMDVLII'], 2548 => ['MMDVLIII'], 2549 => ['MMDVLIV', 'MMDIL'], 2595 => ['MMDVC'], 2596 => ['MMDVCI'], 2597 => ['MMDVCII'], 2598 => ['MMDVCIII'], 2599 => ['MMDVCIV', 'MMDIC'], 2645 => ['MMDCVL'], 2646 => ['MMDCVLI'], 2647 => ['MMDCVLII'], 2648 => ['MMDCVLIII'], 2649 => ['MMDCVLIV', 'MMDCIL'], 2695 => ['MMDCVC'], 2696 => ['MMDCVCI'], 2697 => ['MMDCVCII'], 2698 => ['MMDCVCIII'], 2699 => ['MMDCVCIV', 'MMDCIC'], 2745 => ['MMDCCVL'], 2746 => ['MMDCCVLI'], 2747 => ['MMDCCVLII'], 2748 => ['MMDCCVLIII'], 2749 => ['MMDCCVLIV', 'MMDCCIL'], 2795 => ['MMDCCVC'], 2796 => ['MMDCCVCI'], 2797 => ['MMDCCVCII'], 2798 => ['MMDCCVCIII'], 2799 => ['MMDCCVCIV', 'MMDCCIC'], 2845 => ['MMDCCCVL'], 2846 => ['MMDCCCVLI'], 2847 => ['MMDCCCVLII'], 2848 => ['MMDCCCVLIII'], 2849 => ['MMDCCCVLIV', 'MMDCCCIL'], 2895 => ['MMDCCCVC'], 2896 => ['MMDCCCVCI'], 2897 => ['MMDCCCVCII'], 2898 => ['MMDCCCVCIII'], 2899 => ['MMDCCCVCIV', 'MMDCCCIC'], 2945 => ['MMCMVL'], 2946 => ['MMCMVLI'], 2947 => ['MMCMVLII'], 2948 => ['MMCMVLIII'], 2949 => ['MMCMVLIV', 'MMCMIL'], 2950 => ['MMLM'], 2951 => ['MMLMI'], 2952 => ['MMLMII'], 2953 => ['MMLMIII'], 2954 => ['MMLMIV'], 2955 => ['MMLMV'], 2956 => ['MMLMVI'], 2957 => ['MMLMVII'], 2958 => ['MMLMVIII'], 2959 => ['MMLMIX'], 2960 => ['MMLMX'], 2961 => ['MMLMXI'], 2962 => ['MMLMXII'], 2963 => ['MMLMXIII'], 2964 => ['MMLMXIV'], 2965 => ['MMLMXV'], 2966 => ['MMLMXVI'], 2967 => ['MMLMXVII'], 2968 => ['MMLMXVIII'], 2969 => ['MMLMXIX'], 2970 => ['MMLMXX'], 2971 => ['MMLMXXI'], 2972 => ['MMLMXXII'], 2973 => ['MMLMXXIII'], 2974 => ['MMLMXXIV'], 2975 => ['MMLMXXV'], 2976 => ['MMLMXXVI'], 2977 => ['MMLMXXVII'], 2978 => ['MMLMXXVIII'], 2979 => ['MMLMXXIX'], 2980 => ['MMLMXXX'], 2981 => ['MMLMXXXI'], 2982 => ['MMLMXXXII'], 2983 => ['MMLMXXXIII'], 2984 => ['MMLMXXXIV'], 2985 => ['MMLMXXXV'], 2986 => ['MMLMXXXVI'], 2987 => ['MMLMXXXVII'], 2988 => ['MMLMXXXVIII'], 2989 => ['MMLMXXXIX'], 2990 => ['MMLMXL', 'MMXM'], 2991 => ['MMLMXLI', 'MMXMI'], 2992 => ['MMLMXLII', 'MMXMII'], 2993 => ['MMLMXLIII', 'MMXMIII'], 2994 => ['MMLMXLIV', 'MMXMIV'], 2995 => ['MMLMVL', 'MMXMV', 'MMVM'], 2996 => ['MMLMVLI', 'MMXMVI', 'MMVMI'], 2997 => ['MMLMVLII', 'MMXMVII', 'MMVMII'], 2998 => ['MMLMVLIII', 'MMXMVIII', 'MMVMIII'], 2999 => ['MMLMVLIV', 'MMXMIX', 'MMVMIV', 'MMIM'], 3045 => ['MMMVL'], 3046 => ['MMMVLI'], 3047 => ['MMMVLII'], 3048 => ['MMMVLIII'], 3049 => ['MMMVLIV', 'MMMIL'], 3095 => ['MMMVC'], 3096 => ['MMMVCI'], 3097 => ['MMMVCII'], 3098 => ['MMMVCIII'], 3099 => ['MMMVCIV', 'MMMIC'], 3145 => ['MMMCVL'], 3146 => ['MMMCVLI'], 3147 => ['MMMCVLII'], 3148 => ['MMMCVLIII'], 3149 => ['MMMCVLIV', 'MMMCIL'], 3195 => ['MMMCVC'], 3196 => ['MMMCVCI'], 3197 => ['MMMCVCII'], 3198 => ['MMMCVCIII'], 3199 => ['MMMCVCIV', 'MMMCIC'], 3245 => ['MMMCCVL'], 3246 => ['MMMCCVLI'], 3247 => ['MMMCCVLII'], 3248 => ['MMMCCVLIII'], 3249 => ['MMMCCVLIV', 'MMMCCIL'], 3295 => ['MMMCCVC'], 3296 => ['MMMCCVCI'], 3297 => ['MMMCCVCII'], 3298 => ['MMMCCVCIII'], 3299 => ['MMMCCVCIV', 'MMMCCIC'], 3345 => ['MMMCCCVL'], 3346 => ['MMMCCCVLI'], 3347 => ['MMMCCCVLII'], 3348 => ['MMMCCCVLIII'], 3349 => ['MMMCCCVLIV', 'MMMCCCIL'], 3395 => ['MMMCCCVC'], 3396 => ['MMMCCCVCI'], 3397 => ['MMMCCCVCII'], 3398 => ['MMMCCCVCIII'], 3399 => ['MMMCCCVCIV', 'MMMCCCIC'], 3445 => ['MMMCDVL'], 3446 => ['MMMCDVLI'], 3447 => ['MMMCDVLII'], 3448 => ['MMMCDVLIII'], 3449 => ['MMMCDVLIV', 'MMMCDIL'], 3450 => ['MMMLD'], 3451 => ['MMMLDI'], 3452 => ['MMMLDII'], 3453 => ['MMMLDIII'], 3454 => ['MMMLDIV'], 3455 => ['MMMLDV'], 3456 => ['MMMLDVI'], 3457 => ['MMMLDVII'], 3458 => ['MMMLDVIII'], 3459 => ['MMMLDIX'], 3460 => ['MMMLDX'], 3461 => ['MMMLDXI'], 3462 => ['MMMLDXII'], 3463 => ['MMMLDXIII'], 3464 => ['MMMLDXIV'], 3465 => ['MMMLDXV'], 3466 => ['MMMLDXVI'], 3467 => ['MMMLDXVII'], 3468 => ['MMMLDXVIII'], 3469 => ['MMMLDXIX'], 3470 => ['MMMLDXX'], 3471 => ['MMMLDXXI'], 3472 => ['MMMLDXXII'], 3473 => ['MMMLDXXIII'], 3474 => ['MMMLDXXIV'], 3475 => ['MMMLDXXV'], 3476 => ['MMMLDXXVI'], 3477 => ['MMMLDXXVII'], 3478 => ['MMMLDXXVIII'], 3479 => ['MMMLDXXIX'], 3480 => ['MMMLDXXX'], 3481 => ['MMMLDXXXI'], 3482 => ['MMMLDXXXII'], 3483 => ['MMMLDXXXIII'], 3484 => ['MMMLDXXXIV'], 3485 => ['MMMLDXXXV'], 3486 => ['MMMLDXXXVI'], 3487 => ['MMMLDXXXVII'], 3488 => ['MMMLDXXXVIII'], 3489 => ['MMMLDXXXIX'], 3490 => ['MMMLDXL', 'MMMXD'], 3491 => ['MMMLDXLI', 'MMMXDI'], 3492 => ['MMMLDXLII', 'MMMXDII'], 3493 => ['MMMLDXLIII', 'MMMXDIII'], 3494 => ['MMMLDXLIV', 'MMMXDIV'], 3495 => ['MMMLDVL', 'MMMXDV', 'MMMVD'], 3496 => ['MMMLDVLI', 'MMMXDVI', 'MMMVDI'], 3497 => ['MMMLDVLII', 'MMMXDVII', 'MMMVDII'], 3498 => ['MMMLDVLIII', 'MMMXDVIII', 'MMMVDIII'], 3499 => ['MMMLDVLIV', 'MMMXDIX', 'MMMVDIV', 'MMMID'], 3545 => ['MMMDVL'], 3546 => ['MMMDVLI'], 3547 => ['MMMDVLII'], 3548 => ['MMMDVLIII'], 3549 => ['MMMDVLIV', 'MMMDIL'], 3595 => ['MMMDVC'], 3596 => ['MMMDVCI'], 3597 => ['MMMDVCII'], 3598 => ['MMMDVCIII'], 3599 => ['MMMDVCIV', 'MMMDIC'], 3645 => ['MMMDCVL'], 3646 => ['MMMDCVLI'], 3647 => ['MMMDCVLII'], 3648 => ['MMMDCVLIII'], 3649 => ['MMMDCVLIV', 'MMMDCIL'], 3695 => ['MMMDCVC'], 3696 => ['MMMDCVCI'], 3697 => ['MMMDCVCII'], 3698 => ['MMMDCVCIII'], 3699 => ['MMMDCVCIV', 'MMMDCIC'], 3745 => ['MMMDCCVL'], 3746 => ['MMMDCCVLI'], 3747 => ['MMMDCCVLII'], 3748 => ['MMMDCCVLIII'], 3749 => ['MMMDCCVLIV', 'MMMDCCIL'], 3795 => ['MMMDCCVC'], 3796 => ['MMMDCCVCI'], 3797 => ['MMMDCCVCII'], 3798 => ['MMMDCCVCIII'], 3799 => ['MMMDCCVCIV', 'MMMDCCIC'], 3845 => ['MMMDCCCVL'], 3846 => ['MMMDCCCVLI'], 3847 => ['MMMDCCCVLII'], 3848 => ['MMMDCCCVLIII'], 3849 => ['MMMDCCCVLIV', 'MMMDCCCIL'], 3895 => ['MMMDCCCVC'], 3896 => ['MMMDCCCVCI'], 3897 => ['MMMDCCCVCII'], 3898 => ['MMMDCCCVCIII'], 3899 => ['MMMDCCCVCIV', 'MMMDCCCIC'], 3945 => ['MMMCMVL'], 3946 => ['MMMCMVLI'], 3947 => ['MMMCMVLII'], 3948 => ['MMMCMVLIII'], 3949 => ['MMMCMVLIV', 'MMMCMIL'], 3950 => ['MMMLM'], 3951 => ['MMMLMI'], 3952 => ['MMMLMII'], 3953 => ['MMMLMIII'], 3954 => ['MMMLMIV'], 3955 => ['MMMLMV'], 3956 => ['MMMLMVI'], 3957 => ['MMMLMVII'], 3958 => ['MMMLMVIII'], 3959 => ['MMMLMIX'], 3960 => ['MMMLMX'], 3961 => ['MMMLMXI'], 3962 => ['MMMLMXII'], 3963 => ['MMMLMXIII'], 3964 => ['MMMLMXIV'], 3965 => ['MMMLMXV'], 3966 => ['MMMLMXVI'], 3967 => ['MMMLMXVII'], 3968 => ['MMMLMXVIII'], 3969 => ['MMMLMXIX'], 3970 => ['MMMLMXX'], 3971 => ['MMMLMXXI'], 3972 => ['MMMLMXXII'], 3973 => ['MMMLMXXIII'], 3974 => ['MMMLMXXIV'], 3975 => ['MMMLMXXV'], 3976 => ['MMMLMXXVI'], 3977 => ['MMMLMXXVII'], 3978 => ['MMMLMXXVIII'], 3979 => ['MMMLMXXIX'], 3980 => ['MMMLMXXX'], 3981 => ['MMMLMXXXI'], 3982 => ['MMMLMXXXII'], 3983 => ['MMMLMXXXIII'], 3984 => ['MMMLMXXXIV'], 3985 => ['MMMLMXXXV'], 3986 => ['MMMLMXXXVI'], 3987 => ['MMMLMXXXVII'], 3988 => ['MMMLMXXXVIII'], 3989 => ['MMMLMXXXIX'], 3990 => ['MMMLMXL', 'MMMXM'], 3991 => ['MMMLMXLI', 'MMMXMI'], 3992 => ['MMMLMXLII', 'MMMXMII'], 3993 => ['MMMLMXLIII', 'MMMXMIII'], 3994 => ['MMMLMXLIV', 'MMMXMIV'], 3995 => ['MMMLMVL', 'MMMXMV', 'MMMVM'], 3996 => ['MMMLMVLI', 'MMMXMVI', 'MMMVMI'], 3997 => ['MMMLMVLII', 'MMMXMVII', 'MMMVMII'], 3998 => ['MMMLMVLIII', 'MMMXMVIII', 'MMMVMIII'], 3999 => ['MMMLMVLIV', 'MMMXMIX', 'MMMVMIV', 'MMMIM'], ]; private const THOUSANDS = ['', 'M', 'MM', 'MMM']; private const HUNDREDS = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; private const TENS = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; private const ONES = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; const MAX_ROMAN_VALUE = 3999; const MAX_ROMAN_STYLE = 4; private static function valueOk(int $aValue, int $style): string { $origValue = $aValue; $m = \intdiv($aValue, 1000); $aValue %= 1000; $c = \intdiv($aValue, 100); $aValue %= 100; $t = \intdiv($aValue, 10); $aValue %= 10; $result = self::THOUSANDS[$m] . self::HUNDREDS[$c] . self::TENS[$t] . self::ONES[$aValue]; if ($style > 0) { if (array_key_exists($origValue, self::VALUES)) { $arr = self::VALUES[$origValue]; $idx = min($style, count($arr)) - 1; $result = $arr[$idx]; } } return $result; } private static function styleOk(int $aValue, int $style): string { return ($aValue < 0 || $aValue > self::MAX_ROMAN_VALUE) ? ExcelError::VALUE() : self::valueOk($aValue, $style); } public static function calculateRoman(int $aValue, int $style): string { return ($style < 0 || $style > self::MAX_ROMAN_STYLE) ? ExcelError::VALUE() : self::styleOk($aValue, $style); } /** * ROMAN. * * Converts a number to Roman numeral * * @param mixed $aValue Number to convert * Or can be an array of numbers * @param mixed $style Number indicating one of five possible forms * Or can be an array of styles * * @return array|string Roman numeral, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $aValue, mixed $style = 0): array|string { if (is_array($aValue) || is_array($style)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $aValue, $style); } try { $aValue = Helpers::validateNumericNullBool($aValue); if (is_bool($style)) { $style = $style ? 0 : 4; } $style = Helpers::validateNumericNullSubstitution($style, null); } catch (Exception $e) { return $e->getMessage(); } return self::calculateRoman((int) $aValue, (int) $style); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Round.php ================================================ |float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function round(mixed $number, mixed $precision): array|string|float { if (is_array($number) || is_array($precision)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $precision); } try { $number = Helpers::validateNumericNullBool($number); $precision = Helpers::validateNumericNullBool($precision); } catch (Exception $e) { return $e->getMessage(); } return round($number, (int) $precision); } /** * ROUNDUP. * * Rounds a number up to a specified number of decimal places * * @param array|float $number Number to round, or can be an array of numbers * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function up($number, $digits): array|string|float { if (is_array($number) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); } try { $number = Helpers::validateNumericNullBool($number); $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0.0) { return 0.0; } if (PHP_VERSION_ID >= 80400) { return round( (float) (string) $number, $digits, RoundingMode::AwayFromZero //* @phpstan-ignore-line ); } // @codeCoverageIgnoreStart if ($number < 0.0) { return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); } return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); // @codeCoverageIgnoreEnd } /** * ROUNDDOWN. * * Rounds a number down to a specified number of decimal places * * @param null|array|float|string $number Number to round, or can be an array of numbers * @param array|float|int|string $digits Number of digits to which you want to round $number, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function down($number, $digits): array|string|float { if (is_array($number) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); } try { $number = Helpers::validateNumericNullBool($number); $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0.0) { return 0.0; } if (PHP_VERSION_ID >= 80400) { return round( (float) (string) $number, $digits, RoundingMode::TowardsZero //* @phpstan-ignore-line ); } // @codeCoverageIgnoreStart if ($number < 0.0) { return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); } return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); // @codeCoverageIgnoreEnd } /** * MROUND. * * Rounds a number to the nearest multiple of a specified value * * @param mixed $number Expect float. Number to round, or can be an array of numbers * @param mixed $multiple Expect int. Multiple to which you want to round, or can be an array of numbers. * * @return array|float|int|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function multiple(mixed $number, mixed $multiple): array|string|int|float { if (is_array($number) || is_array($multiple)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $multiple); } try { $number = Helpers::validateNumericNullSubstitution($number, 0); $multiple = Helpers::validateNumericNullSubstitution($multiple, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0 || $multiple == 0) { return 0; } if ((Helpers::returnSign($number)) == (Helpers::returnSign($multiple))) { $multiplier = 1 / $multiple; return round($number * $multiplier) / $multiplier; } return ExcelError::NAN(); } /** * EVEN. * * Returns number rounded up to the nearest even integer. * You can use this function for processing items that come in twos. For example, * a packing crate accepts rows of one or two items. The crate is full when * the number of items, rounded up to the nearest two, matches the crate's * capacity. * * Excel Function: * EVEN(number) * * @param array|float $number Number to round, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function even($number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::getEven($number); } /** * ODD. * * Returns number rounded up to the nearest odd integer. * * @param array|float $number Number to round, or can be an array of numbers * * @return array|float|int|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function odd($number): array|string|int|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } $significance = Helpers::returnSign($number); if ($significance == 0) { return 1; } $result = ceil($number / $significance) * $significance; if ($result == Helpers::getEven($result)) { $result += $significance; } return $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php ================================================ |float|int|string The result, or a string containing an error */ public static function evaluate(mixed $x, mixed $n, mixed $m, ...$args): array|string|float|int { if (is_array($x) || is_array($n) || is_array($m)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 3, $x, $n, $m, ...$args); } try { $x = Helpers::validateNumericNullSubstitution($x, 0); $n = Helpers::validateNumericNullSubstitution($n, 0); $m = Helpers::validateNumericNullSubstitution($m, 0); // Loop through arguments $aArgs = Functions::flattenArray($args); $returnValue = 0; $i = 0; foreach ($aArgs as $argx) { if ($argx !== null) { $arg = Helpers::validateNumericNullSubstitution($argx, 0); $returnValue += $arg * $x ** ($n + ($m * $i)); ++$i; } } } catch (Exception $e) { return $e->getMessage(); } return $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Sign.php ================================================ |float $number Number to round, or can be an array of numbers * * @return array|int|string sign value, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number): array|string|int { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::returnSign($number); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php ================================================ |float|string square root * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sqrt(mixed $number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(sqrt($number)); } /** * SQRTPI. * * Returns the square root of (number * pi). * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string Square Root of Number * Pi, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function pi($number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullSubstitution($number, 0); Helpers::validateNotNegative($number); } catch (Exception $e) { return $e->getMessage(); } return sqrt($number * M_PI); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php ================================================ getWorksheet()->getRowDimension((int) $row)->getVisible(); }, ARRAY_FILTER_USE_KEY ); } /** * @param mixed[] $args * * @return mixed[] */ protected static function filterFilteredArgs(Cell $cellReference, array $args): array { return array_filter( $args, function ($index) use ($cellReference) { $explodeArray = explode('.', $index); $row = $explodeArray[1] ?? ''; return is_numeric($row) ? ($cellReference->getWorksheet()->getRowDimension((int) $row)->getVisibleAfterFilter()) : true; }, ARRAY_FILTER_USE_KEY ); } /** * @param mixed[] $args * * @return mixed[] */ protected static function filterFormulaArgs(Cell $cellReference, array $args): array { return array_filter( $args, function ($index) use ($cellReference): bool { $explodeArray = explode('.', $index); $row = $explodeArray[1] ?? ''; $column = $explodeArray[2] ?? ''; $retVal = true; if ($cellReference->getWorksheet()->cellExists($column . $row)) { //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); $cellFormula = !preg_match( '/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', $cellReference->getWorksheet()->getCell($column . $row)->getValueString() ); $retVal = !$isFormula || $cellFormula; } return $retVal; }, ARRAY_FILTER_USE_KEY ); } /** * @var array */ private const CALL_FUNCTIONS = [ 1 => [Statistical\Averages::class, 'average'], // 1 and 101 [Statistical\Counts::class, 'COUNT'], // 2 and 102 [Statistical\Counts::class, 'COUNTA'], // 3 and 103 [Statistical\Maximum::class, 'max'], // 4 and 104 [Statistical\Minimum::class, 'min'], // 5 and 105 [Operations::class, 'product'], // 6 and 106 [Statistical\StandardDeviations::class, 'STDEV'], // 7 and 107 [Statistical\StandardDeviations::class, 'STDEVP'], // 8 and 108 [Sum::class, 'sumIgnoringStrings'], // 9 and 109 [Statistical\Variances::class, 'VAR'], // 10 and 110 [Statistical\Variances::class, 'VARP'], // 111 and 111 ]; /** * SUBTOTAL. * * Returns a subtotal in a list or database. * * @param mixed $functionType * A number 1 to 11 that specifies which function to * use in calculating subtotals within a range * list * Numbers 101 to 111 shadow the functions of 1 to 11 * but ignore any values in the range that are * in hidden rows * @param mixed[] $args A mixed data series of values */ public static function evaluate(mixed $functionType, ...$args): float|int|string { /** @var Cell */ $cellReference = array_pop($args); $bArgs = Functions::flattenArrayIndexed($args); $aArgs = []; // int keys must come before string keys for PHP 8.0+ // Otherwise, PHP thinks positional args follow keyword // in the subsequent call to call_user_func_array. // Fortunately, order of args is unimportant to Subtotal. foreach ($bArgs as $key => $value) { if (is_int($key)) { $aArgs[$key] = $value; } } foreach ($bArgs as $key => $value) { if (!is_int($key)) { $aArgs[$key] = $value; } } try { $subtotal = (int) Helpers::validateNumericNullBool($functionType); } catch (Exception $e) { return $e->getMessage(); } // Calculate if ($subtotal > 100) { $aArgs = self::filterHiddenArgs($cellReference, $aArgs); $subtotal -= 100; } else { $aArgs = self::filterFilteredArgs($cellReference, $aArgs); } $aArgs = self::filterFormulaArgs($cellReference, $aArgs); if (array_key_exists($subtotal, self::CALL_FUNCTIONS)) { $call = self::CALL_FUNCTIONS[$subtotal]; return call_user_func_array($call, $aArgs); //* @phpstan-ignore-line } return ExcelError::VALUE(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Sum.php ================================================ |float|int|string */ public static function sumErroringStrings(mixed ...$args): float|int|string|array { $returnValue = 0; // Loop through the arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue += $arg; } elseif (is_bool($arg)) { $returnValue += (int) $arg; } elseif (ErrorValue::isError($arg, true)) { /** @var string $arg */ return $arg; } elseif ($arg !== null && !Functions::isCellValue($k)) { // ignore non-numerics from cell, but fail as literals (except null) return ExcelError::VALUE(); } } return $returnValue; } /** * SUMPRODUCT. * * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string The result, or a string containing an error */ public static function product(mixed ...$args): string|int|float { $arrayList = $args; $wrkArray = Functions::flattenArray(array_shift($arrayList)); $wrkCellCount = count($wrkArray); for ($i = 0; $i < $wrkCellCount; ++$i) { if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { $wrkArray[$i] = 0; } } foreach ($arrayList as $matrixData) { $array2 = Functions::flattenArray($matrixData); $count = count($array2); if ($wrkCellCount != $count) { return ExcelError::VALUE(); } foreach ($array2 as $i => $val) { if ((!is_numeric($val)) || (is_string($val))) { $val = 0; } /** @var array $wrkArray */ $wrkArray[$i] *= $val; } } /** @var array $wrkArray */ return array_sum($wrkArray); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php ================================================ getMessage(); } return $returnValue; } /** * @param mixed[] $array1 * @param mixed[] $array2 */ private static function getCount(array $array1, array $array2): int { $count = count($array1); if ($count !== count($array2)) { throw new Exception(ExcelError::NA()); } return $count; } /** * These functions accept only numeric arguments, not even strings which are numeric. */ private static function numericNotString(mixed $item): bool { return is_numeric($item) && !is_string($item); } /** * SUMX2MY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 */ public static function sumXSquaredMinusYSquared(array $matrixData1, array $matrixData2): string|int|float { try { /** @var array */ $array1 = Functions::flattenArray($matrixData1); /** @var array */ $array2 = Functions::flattenArray($matrixData2); $count = self::getCount($array1, $array2); $result = 0; for ($i = 0; $i < $count; ++$i) { if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); } } } catch (Exception $e) { return $e->getMessage(); } return $result; } /** * SUMX2PY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 */ public static function sumXSquaredPlusYSquared(array $matrixData1, array $matrixData2): string|int|float { try { /** @var array */ $array1 = Functions::flattenArray($matrixData1); /** @var array */ $array2 = Functions::flattenArray($matrixData2); $count = self::getCount($array1, $array2); $result = 0; for ($i = 0; $i < $count; ++$i) { if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); } } } catch (Exception $e) { return $e->getMessage(); } return $result; } /** * SUMXMY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 */ public static function sumXMinusYSquared(array $matrixData1, array $matrixData2): string|int|float { try { /** @var array */ $array1 = Functions::flattenArray($matrixData1); /** @var array */ $array2 = Functions::flattenArray($matrixData2); $count = self::getCount($array1, $array2); $result = 0; for ($i = 0; $i < $count; ++$i) { if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); } } } catch (Exception $e) { return $e->getMessage(); } return $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php ================================================ |float $angle Number, or can be an array of numbers * * @return array|float|string The cosecant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function csc($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, sin($angle)); } /** * CSCH. * * Returns the hyperbolic cosecant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic cosecant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function csch($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, sinh($angle)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php ================================================ |float|string cosine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cos(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return cos($number); } /** * COSH. * * Returns the result of builtin function cosh after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic cosine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cosh(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return cosh($number); } /** * ACOS. * * Returns the arccosine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arccosine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acos($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(acos($number)); } /** * ACOSH. * * Returns the arc inverse hyperbolic cosine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic cosine of the number, or an error string * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acosh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(acosh($number)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php ================================================ |float $angle Number, or can be an array of numbers * * @return array|float|string The cotangent of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cot($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(cos($angle), sin($angle)); } /** * COTH. * * Returns the hyperbolic cotangent of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic cotangent of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function coth($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, tanh($angle)); } /** * ACOT. * * Returns the arccotangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arccotangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acot($number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return (M_PI / 2) - atan($number); } /** * ACOTH. * * Returns the hyperbolic arccotangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The hyperbolic arccotangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acoth($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } $result = ($number === 1) ? NAN : (log(($number + 1) / ($number - 1)) / 2); return Helpers::numberOrNan($result); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php ================================================ |float $angle Number, or can be an array of numbers * * @return array|float|string The secant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sec($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, cos($angle)); } /** * SECH. * * Returns the hyperbolic secant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic secant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sech($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, cosh($angle)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php ================================================ |float|string sine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sin(mixed $angle): array|string|float { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return sin($angle); } /** * SINH. * * Returns the result of builtin function sinh after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic sine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sinh(mixed $angle): array|string|float { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return sinh($angle); } /** * ASIN. * * Returns the arcsine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arcsine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function asin($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(asin($number)); } /** * ASINH. * * Returns the inverse hyperbolic sine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic sine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function asinh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(asinh($number)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php ================================================ |float|string tangent * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function tan(mixed $angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(sin($angle), cos($angle)); } /** * TANH. * * Returns the result of builtin function sinh after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic tangent * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function tanh(mixed $angle): array|string|float { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return tanh($angle); } /** * ATAN. * * Returns the arctangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arctangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function atan($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(atan($number)); } /** * ATANH. * * Returns the inverse hyperbolic tangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic tangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function atanh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(atanh($number)); } /** * ATAN2. * * This function calculates the arc tangent of the two variables x and y. It is similar to * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used * to determine the quadrant of the result. * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between * -pi and pi, excluding -pi. * * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. * * Excel Function: * ATAN2(xCoordinate,yCoordinate) * * @param mixed $xCoordinate should be float, the x-coordinate of the point, or can be an array of numbers * @param mixed $yCoordinate should be float, the y-coordinate of the point, or can be an array of numbers * * @return array|float|string The inverse tangent of the specified x- and y-coordinates, or a string containing an error * If an array of numbers is passed as one of the arguments, then the returned result will also be an array * with the same dimensions */ public static function atan2(mixed $xCoordinate, mixed $yCoordinate): array|string|float { if (is_array($xCoordinate) || is_array($yCoordinate)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $xCoordinate, $yCoordinate); } try { $xCoordinate = Helpers::validateNumericNullBool($xCoordinate); $yCoordinate = Helpers::validateNumericNullBool($yCoordinate); } catch (Exception $e) { return $e->getMessage(); } if (($xCoordinate == 0) && ($yCoordinate == 0)) { return ExcelError::DIV0(); } return atan2($yCoordinate, $xCoordinate); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php ================================================ |float|string $value Or can be an array of values * @param array|float|int|string $digits Or can be an array of values * * @return array|float|string Truncated value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(array|float|string|null $value = 0, array|float|int|string $digits = 0): array|float|string { if (is_array($value) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $digits); } return Round::down($value, $digits); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php ================================================ 0)) { $aCount = Counts::COUNT($aArgs); if (Minimum::min($aArgs) > 0) { return $aMean ** (1 / $aCount); } } return ExcelError::NAN(); } /** * HARMEAN. * * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the * arithmetic mean of reciprocals. * * Excel Function: * HARMEAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function harmonic(mixed ...$args): string|float|int { // Loop through arguments $aArgs = Functions::flattenArray($args); if (Minimum::min($aArgs) < 0) { return ExcelError::NAN(); } $returnValue = 0; $aCount = 0; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if ($arg <= 0) { return ExcelError::NAN(); } $returnValue += (1 / $arg); ++$aCount; } } // Return if ($aCount > 0) { return 1 / ($returnValue / $aCount); } return ExcelError::NA(); } /** * TRIMMEAN. * * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean * taken by excluding a percentage of data points from the top and bottom tails * of a data set. * * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * * @param mixed $args Data values */ public static function trim(mixed ...$args): float|string { $aArgs = Functions::flattenArray($args); // Calculate $percent = array_pop($aArgs); if ((is_numeric($percent)) && (!is_string($percent))) { if (($percent < 0) || ($percent > 1)) { return ExcelError::NAN(); } $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } $discard = floor(Counts::COUNT($mArgs) * $percent / 2); sort($mArgs); for ($i = 0; $i < $discard; ++$i) { array_pop($mArgs); array_shift($mArgs); } return Averages::average($mArgs); } return ExcelError::VALUE(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Averages.php ================================================ $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { /** @var float|int|numeric-string $arg */ /** @var float|int|numeric-string $aMean */ $returnValue += abs($arg - $aMean); ++$aCount; } } // Return if ($aCount === 0) { return ExcelError::DIV0(); } return $returnValue / $aCount; } /** * AVERAGE. * * Returns the average (arithmetic mean) of the arguments * * Excel Function: * AVERAGE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string (string if result is an error) */ public static function average(mixed ...$args): string|int|float { $returnValue = $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { /** @var float|int|numeric-string $arg */ $returnValue += $arg; ++$aCount; } } // Return if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * AVERAGEA. * * Returns the average of its arguments, including numbers, text, and logical values * * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string (string if result is an error) */ public static function averageA(mixed ...$args): string|int|float { $returnValue = null; $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { if (is_numeric($arg)) { // do nothing } elseif (is_bool($arg)) { $arg = (int) $arg; } elseif (!Functions::isMatrixValue($k)) { $arg = 0; } else { return ExcelError::VALUE(); } $returnValue += $arg; ++$aCount; } if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * MEDIAN. * * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. * * Excel Function: * MEDIAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function median(mixed ...$args): float|string { $aArgs = Functions::flattenArray($args); $returnValue = ExcelError::NAN(); /** @var array */ $aArgs = self::filterArguments($aArgs); $valueCount = count($aArgs); if ($valueCount > 0) { sort($aArgs, SORT_NUMERIC); $valueCount = $valueCount / 2; if ($valueCount == floor($valueCount)) { $returnValue = ($aArgs[$valueCount--] + $aArgs[$valueCount]) / 2; //* @phpstan-ignore-line } else { $valueCount = (int) floor($valueCount); $returnValue = $aArgs[$valueCount]; } } return $returnValue; } /** * MODE. * * Returns the most frequently occurring, or repetitive, value in an array or range of data * * Excel Function: * MODE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function mode(mixed ...$args): float|string { $returnValue = ExcelError::NA(); // Loop through arguments $aArgs = Functions::flattenArray($args); $aArgs = self::filterArguments($aArgs); if (!empty($aArgs)) { return self::modeCalc($aArgs); } return $returnValue; } /** * @param mixed[] $args * * @return mixed[] */ protected static function filterArguments(array $args): array { return array_filter( $args, function ($value): bool { // Is it a numeric value? return is_numeric($value) && (!is_string($value)); } ); } /** * Special variant of array_count_values that isn't limited to strings and integers, * but can work with floating point numbers as values. * * @param mixed[] $data */ private static function modeCalc(array $data): float|string { $frequencyArray = []; $index = 0; $maxfreq = 0; $maxfreqkey = ''; $maxfreqdatum = ''; foreach ($data as $datum) { /** @var float|string $datum */ $found = false; ++$index; foreach ($frequencyArray as $key => $value) { /** @var string[] $value */ if ((string) $value['value'] == (string) $datum) { ++$frequencyArray[$key]['frequency']; $freq = $frequencyArray[$key]['frequency']; if ($freq > $maxfreq) { $maxfreq = $freq; $maxfreqkey = $key; $maxfreqdatum = $datum; } elseif ($freq == $maxfreq) { if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { //* @phpstan-ignore-line $maxfreqkey = $key; $maxfreqdatum = $datum; } } $found = true; break; } } if ($found === false) { $frequencyArray[] = [ 'value' => $datum, 'frequency' => 1, 'index' => $index, ]; } } if ($maxfreq <= 1) { return ExcelError::NA(); } return $maxfreqdatum; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php ================================================ $value !== null && $value !== '' ); $range = array_merge([[self::CONDITION_COLUMN_NAME]], array_chunk($range, 1)); $condition = Functions::flattenSingleValue($condition); $condition = array_merge([[self::CONDITION_COLUMN_NAME]], [[$condition]]); return DCount::evaluate($range, null, $condition, false); } /** * COUNTIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function COUNTIFS(mixed ...$args): int|string { if (empty($args)) { return 0; } elseif (count($args) === 2) { return self::COUNTIF(...$args); } $database = self::buildDatabase(...$args); $conditions = self::buildConditionSet(...$args); return DCount::evaluate($database, null, $conditions, false); } /** * MAXIFS. * * Returns the maximum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function MAXIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMax::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * MINIFS. * * Returns the minimum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function MINIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMin::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * SUMIF. * * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: * SUMIF(range, criteria, [sum_range]) * * @param mixed $range Data values, expecting array * @param mixed $sumRange Data values, expecting array */ public static function SUMIF(mixed $range, mixed $condition, mixed $sumRange = []): null|float|string { if ( !is_array($range) || array_key_exists(0, $range) || !is_array($sumRange) || array_key_exists(0, $sumRange) ) { $refError = ExcelError::REF(); if (in_array($refError, [$range, $sumRange], true)) { return $refError; } throw new CalcException('Must specify range of cells, not any kind of literal'); } $database = self::databaseFromRangeAndValue($range, $sumRange); $condition = Functions::flattenSingleValue($condition); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * SUMIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * SUMIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function SUMIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } elseif (count($args) === 3) { return self::SUMIF($args[1], $args[2], $args[0]); } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** * @param mixed[] $args * * @return mixed[][] */ private static function buildConditionSet(...$args): array { $conditions = self::buildConditions(1, ...$args); return array_map(null, ...$conditions); } /** * @param mixed[] $args * * @return mixed[][] */ private static function buildConditionSetForValueRange(...$args): array { $conditions = self::buildConditions(2, ...$args); if (count($conditions) === 1) { return array_map( fn ($value): array => [$value], $conditions[0] ); } return array_map(null, ...$conditions); } /** * @param mixed[] $args * * @return mixed[][] */ private static function buildConditions(int $startOffset, ...$args): array { $conditions = []; $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $conditions[] = array_merge([sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], [$args[$argument]]); ++$pairCount; } return $conditions; } /** * @param mixed[] $args * * @return mixed[] */ private static function buildDatabase(...$args): array { $database = []; return self::buildDataSet(0, $database, ...$args); } /** * @param mixed[] $args * * @return mixed[] */ private static function buildDatabaseWithValueRange(...$args): array { $database = []; $database[] = array_merge( [self::VALUE_COLUMN_NAME], Functions::flattenArray($args[0]) ); return self::buildDataSet(1, $database, ...$args); } /** * @param mixed[][] $database * @param mixed[] $args * * @return mixed[] */ private static function buildDataSet(int $startOffset, array $database, ...$args): array { $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $database[] = array_merge( [sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], Functions::flattenArray($args[$argument]) ); ++$pairCount; } return array_map(null, ...$database); } /** * @param mixed[] $range * @param mixed[] $valueRange * * @return mixed[] */ private static function databaseFromRangeAndValue(array $range, array $valueRange = []): array { $range = Functions::flattenArray($range); $valueRange = Functions::flattenArray($valueRange); if (empty($valueRange)) { $valueRange = $range; } $database = array_map(null, array_merge([self::CONDITION_COLUMN_NAME], $range), array_merge([self::VALUE_COLUMN_NAME], $valueRange)); return $database; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Confidence.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONFIDENCE(mixed $alpha, mixed $stdDev, mixed $size) { if (is_array($alpha) || is_array($stdDev) || is_array($size)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $alpha, $stdDev, $size); } try { $alpha = StatisticalValidations::validateFloat($alpha); $stdDev = StatisticalValidations::validateFloat($stdDev); $size = StatisticalValidations::validateInt($size); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) { return ExcelError::NAN(); } /** @var float $temp */ $temp = Distributions\StandardNormal::inverse(1 - $alpha / 2); /** @var float */ $result = Functions::scalar($temp * $stdDev / sqrt($size)); return $result; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Counts.php ================================================ $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if (self::isAcceptedCountable($arg, $k, true)) { ++$returnValue; } } return $returnValue; } /** * COUNTA. * * Counts the number of cells that are not empty within the list of arguments * * Excel Function: * COUNTA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function COUNTA(mixed ...$args): int { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Nulls are counted if literals, but not if cell values if ($arg !== null || (!Functions::isCellValue($k))) { ++$returnValue; } } return $returnValue; } /** * COUNTBLANK. * * Counts the number of empty cells within the list of arguments * * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * * @param mixed $range Data values */ public static function COUNTBLANK(mixed $range): int { if ($range === null) { return 1; } if (!is_array($range) || array_key_exists(0, $range)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArray($range); foreach ($aArgs as $arg) { // Is it a blank cell? if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { ++$returnValue; } } return $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Deviations.php ================================================ $arg) { // Is it a numeric value? if ( (is_bool($arg)) && ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; } if ((is_numeric($arg)) && (!is_string($arg))) { $returnValue += ($arg - $aMean) ** 2; ++$aCount; } } return $aCount === 0 ? ExcelError::VALUE() : $returnValue; } /** * KURT. * * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness * or flatness of a distribution compared with the normal distribution. Positive * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * * @param mixed[] ...$args Data Series */ public static function kurtosis(...$args): string|int|float { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = (float) StandardDeviations::STDEV($aArgs); if ($stdDev > 0) { $count = $summer = 0; foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summer += (($arg - $mean) / $stdDev) ** 4; ++$count; } } } if ($count > 3) { return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / (($count - 2) * ($count - 3))); } } return ExcelError::DIV0(); } /** * SKEW. * * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry * of a distribution around its mean. Positive skewness indicates a distribution with an * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * * @param mixed[] ...$args Data Series * * @return float|int|string The result, or a string containing an error */ public static function skew(...$args): string|int|float { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = StandardDeviations::STDEV($aArgs); if ($stdDev === 0.0 || is_string($stdDev)) { return ExcelError::DIV0(); } $count = $summer = 0; // Loop through arguments foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } elseif (!is_numeric($arg)) { return ExcelError::VALUE(); } else { // Is it a numeric value? if (!is_string($arg)) { $summer += (($arg - $mean) / $stdDev) ** 3; ++$count; } } } if ($count > 2) { return $summer * ($count / (($count - 1) * ($count - 2))); } return ExcelError::DIV0(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $alpha, mixed $beta, mixed $rMin = 0.0, mixed $rMax = 1.0): array|string|float { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $rMin, $rMax); } $rMin = $rMin ?? 0.0; $rMax = $rMax ?? 1.0; try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $rMax = DistributionValidations::validateFloat($rMax); $rMin = DistributionValidations::validateFloat($rMin); } catch (Exception $e) { return $e->getMessage(); } if ($rMin > $rMax) { $tmp = $rMin; $rMin = $rMax; $rMax = $tmp; } if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { return ExcelError::NAN(); } $value -= $rMin; $value /= ($rMax - $rMin); return self::incompleteBeta($value, $alpha, $beta); } /** * BETAINV. * * Returns the inverse of the Beta distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * @param mixed $rMin Minimum value as a float * Or can be an array of values * @param mixed $rMax Maximum value as a float * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $alpha, mixed $beta, mixed $rMin = 0.0, mixed $rMax = 1.0): array|string|float { if (is_array($probability) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta, $rMin, $rMax); } $rMin = $rMin ?? 0.0; $rMax = $rMax ?? 1.0; try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $rMax = DistributionValidations::validateFloat($rMax); $rMin = DistributionValidations::validateFloat($rMin); } catch (Exception $e) { return $e->getMessage(); } if ($rMin > $rMax) { $tmp = $rMin; $rMin = $rMax; $rMax = $tmp; } if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta, $rMin, $rMax); } private static function calculateInverse(float $probability, float $alpha, float $beta, float $rMin, float $rMax): string|float { $a = 0; $b = 2; $guess = ($a + $b) / 2; $i = 0; while ((($b - $a) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { $guess = ($a + $b) / 2; $result = self::distribution($guess, $alpha, $beta); if (($result === $probability) || ($result === 0.0)) { $b = $a; } elseif ($result > $probability) { $b = $guess; } else { $a = $guess; } } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return round($rMin + $guess * ($rMax - $rMin), 12); } /** * Incomplete beta function. * * @author Jaco van Kooten * @author Paul Meagher * * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). * * @param float $x require 0<=x<=1 * @param float $p require p>0 * @param float $q require q>0 * * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow */ public static function incompleteBeta(float $x, float $p, float $q): float { if ($x <= 0.0) { return 0.0; } elseif ($x >= 1.0) { return 1.0; } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { return 0.0; } $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); if ($x < ($p + 1.0) / ($p + $q + 2.0)) { return $beta_gam * self::betaFraction($x, $p, $q) / $p; } return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); } // Function cache for logBeta function private static float $logBetaCacheP = 0.0; private static float $logBetaCacheQ = 0.0; private static float $logBetaCacheResult = 0.0; /** * The natural logarithm of the beta function. * * @param float $p require p>0 * @param float $q require q>0 * * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow * * @author Jaco van Kooten */ private static function logBeta(float $p, float $q): float { if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { self::$logBetaCacheP = $p; self::$logBetaCacheQ = $q; if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { self::$logBetaCacheResult = 0.0; } else { self::$logBetaCacheResult = Gamma::logGamma($p) + Gamma::logGamma($q) - Gamma::logGamma($p + $q); } } return self::$logBetaCacheResult; } /** * Evaluates of continued fraction part of incomplete beta function. * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). * * @author Jaco van Kooten */ private static function betaFraction(float $x, float $p, float $q): float { $c = 1.0; $sum_pq = $p + $q; $p_plus = $p + 1.0; $p_minus = $p - 1.0; $h = 1.0 - $sum_pq * $x / $p_plus; if (abs($h) < self::XMININ) { $h = self::XMININ; } $h = 1.0 / $h; $frac = $h; $m = 1; $delta = 0.0; while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) { $m2 = 2 * $m; // even index for d $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); $h = 1.0 + $d * $h; if (abs($h) < self::XMININ) { $h = self::XMININ; } $h = 1.0 / $h; $c = 1.0 + $d / $c; if (abs($c) < self::XMININ) { $c = self::XMININ; } $frac *= $h * $c; // odd index for d $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); $h = 1.0 + $d * $h; if (abs($h) < self::XMININ) { $h = self::XMININ; } $h = 1.0 / $h; $c = 1.0 + $d / $c; if (abs($c) < self::XMININ) { $c = self::XMININ; } $delta = $h * $c; $frac *= $delta; ++$m; } return $frac; } /* private static function betaValue(float $a, float $b): float { return (Gamma::gammaValue($a) * Gamma::gammaValue($b)) / Gamma::gammaValue($a + $b); } private static function regularizedIncompleteBeta(float $value, float $a, float $b): float { return self::incompleteBeta($value, $a, $b) / self::betaValue($a, $b); } */ } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $trials, mixed $probability, mixed $cumulative) { if (is_array($value) || is_array($trials) || is_array($probability) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $trials, $probability, $cumulative); } try { $value = DistributionValidations::validateInt($value); $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($value > $trials)) { return ExcelError::NAN(); } if ($cumulative) { return self::calculateCumulativeBinomial($value, $trials, $probability); } /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $value); return $comb * $probability ** $value * (1 - $probability) ** ($trials - $value); } /** * BINOM.DIST.RANGE. * * Returns the Binomial Distribution probability for the number of successes from a specified number * of trials falling into a specified range. * * @param mixed $trials Integer number of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $successes The integer number of successes in trials * Or can be an array of values * @param mixed $limit Upper limit for successes in trials as null, or an integer * If null, then this will indicate the same as the number of Successes * Or can be an array of values * * @return array|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function range(mixed $trials, mixed $probability, mixed $successes, mixed $limit = null): array|string|float|int { if (is_array($trials) || is_array($probability) || is_array($successes) || is_array($limit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $successes, $limit); } $limit = $limit ?? $successes; try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $successes = DistributionValidations::validateInt($successes); $limit = DistributionValidations::validateInt($limit); } catch (Exception $e) { return $e->getMessage(); } if (($successes < 0) || ($successes > $trials)) { return ExcelError::NAN(); } if (($limit < 0) || ($limit > $trials) || $limit < $successes) { return ExcelError::NAN(); } $summer = 0; for ($i = $successes; $i <= $limit; ++$i) { /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } /** * NEGBINOMDIST. * * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that * there will be number_f failures before the number_s-th success, when the constant * probability of a success is probability_s. This function is similar to the binomial * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * * @param mixed $failures Number of Failures as an integer * Or can be an array of values * @param mixed $successes Threshold number of Successes as an integer * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * TODO Add support for the cumulative flag not present for NEGBINOMDIST, but introduced for NEGBINOM.DIST * The cumulative default should be false to reflect the behaviour of NEGBINOMDIST */ public static function negative(mixed $failures, mixed $successes, mixed $probability): array|string|float { if (is_array($failures) || is_array($successes) || is_array($probability)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $failures, $successes, $probability); } try { $failures = DistributionValidations::validateInt($failures); $successes = DistributionValidations::validateInt($successes); $probability = DistributionValidations::validateProbability($probability); } catch (Exception $e) { return $e->getMessage(); } if (($failures < 0) || ($successes < 1)) { return ExcelError::NAN(); } if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (($failures + $successes - 1) <= 0) { return ExcelError::NAN(); } } /** @var float $comb */ $comb = Combinations::withoutRepetition($failures + $successes - 1, $successes - 1); return $comb * ($probability ** $successes) * ((1 - $probability) ** $failures); } /** * BINOM.INV. * * Returns the smallest value for which the cumulative binomial distribution is greater * than or equal to a criterion value * * @param mixed $trials number of Bernoulli trials as an integer * Or can be an array of values * @param mixed $probability probability of a success on each trial as a float * Or can be an array of values * @param mixed $alpha criterion value as a float * Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $trials, mixed $probability, mixed $alpha): array|string|int { if (is_array($trials) || is_array($probability) || is_array($alpha)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $alpha); } try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); } catch (Exception $e) { return $e->getMessage(); } if ($trials < 0) { return ExcelError::NAN(); } elseif (($alpha < 0.0) || ($alpha > 1.0)) { return ExcelError::NAN(); } $successes = 0; while ($successes <= $trials) { $result = self::calculateCumulativeBinomial($successes, $trials, $probability); if ($result >= $alpha) { break; } ++$successes; } return $successes; } private static function calculateCumulativeBinomial(int $value, int $trials, float $probability): float|int { $summer = 0; for ($i = 0; $i <= $value; ++$i) { /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php ================================================ |float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionRightTail(mixed $value, mixed $degrees): array|string|int|float { if (is_array($value) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); } /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionLeftTail(mixed $value, mixed $degrees, mixed $cumulative): array|string|int|float { if (is_array($value) || is_array($degrees) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } if ($cumulative === true) { $temp = self::distributionRightTail($value, $degrees); return 1 - (is_numeric($temp) ? $temp : 0); } return ($value ** (($degrees / 2) - 1) * exp(-$value / 2)) / ((2 ** ($degrees / 2)) * Gamma::gammaValue($degrees / 2)); } /** * CHIINV. * * Returns the inverse of the right-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseRightTail(mixed $probability, mixed $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } $callback = fn (float $value): float => 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); $newtonRaphson = new NewtonRaphson($callback); return $newtonRaphson->execute($probability); } /** * CHIINV. * * Returns the inverse of the left-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseLeftTail(mixed $probability, mixed $degrees): array|string|float { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } return self::inverseLeftTailCalculation($probability, $degrees); } /** * CHITEST. * * Uses the chi-square test to calculate the probability that the differences between two supplied data sets * (of observed and expected frequencies), are likely to be simply due to sampling error, * or if they are likely to be real. * * @param float[] $actual an array of observed frequencies * @param float[] $expected an array of expected frequencies */ public static function test($actual, $expected): float|string { $rows = count($actual); /** @var float[] */ $actual = Functions::flattenArray($actual); /** @var float[] */ $expected = Functions::flattenArray($expected); $columns = intdiv(count($actual), $rows); $countActuals = count($actual); $countExpected = count($expected); if ($countActuals !== $countExpected || $countActuals === 1) { return ExcelError::NAN(); } $result = 0.0; for ($i = 0; $i < $countActuals; ++$i) { if ($expected[$i] == 0.0) { return ExcelError::DIV0(); } elseif ($expected[$i] < 0.0) { return ExcelError::NAN(); } $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i]; } $degrees = self::degrees($rows, $columns); /** @var float|string */ $result = Functions::scalar(self::distributionRightTail($result, $degrees)); return $result; } protected static function degrees(int $rows, int $columns): int { if ($rows === 1) { return $columns - 1; } elseif ($columns === 1) { return $rows - 1; } return ($columns - 1) * ($rows - 1); } private static function inverseLeftTailCalculation(float $probability, int $degrees): float { // bracket the root $min = 0; $sd = sqrt(2.0 * $degrees); $max = 2 * $sd; $s = -1; while ($s * self::pchisq($max, $degrees) > $probability * $s) { $min = $max; $max += 2 * $sd; } // Find root using bisection $chi2 = 0.5 * ($min + $max); while (($max - $min) > self::EPS * $chi2) { if ($s * self::pchisq($chi2, $degrees) > $probability * $s) { $min = $chi2; } else { $max = $chi2; } $chi2 = 0.5 * ($min + $max); } return $chi2; } private static function pchisq(float $chi2, int $degrees): float { return self::gammp($degrees, 0.5 * $chi2); } private static function gammp(int $n, float $x): float { if ($x < 0.5 * $n + 1) { return self::gser($n, $x); } return 1 - self::gcf($n, $x); } // Return the incomplete gamma function P(n/2,x) evaluated by // series representation. Algorithm from numerical recipe. // Assume that n is a positive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gser(int $n, float $x): float { /** @var float $gln */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $ap = $a; $sum = 1.0 / $a; $del = $sum; for ($i = 1; $i < 101; ++$i) { ++$ap; $del = $del * $x / $ap; $sum += $del; if ($del < $sum * self::EPS) { break; } } return $sum * exp(-$x + $a * log($x) - $gln); } // Return the incomplete gamma function Q(n/2,x) evaluated by // its continued fraction representation. Algorithm from numerical recipe. // Assume that n is a postive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gcf(int $n, float $x): float { /** @var float $gln */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $b = $x + 1 - $a; $fpmin = 1.e-300; $c = 1 / $fpmin; $d = 1 / $b; $h = $d; for ($i = 1; $i < 101; ++$i) { $an = -$i * ($i - $a); $b += 2; $d = $an * $d + $b; if (abs($d) < $fpmin) { $d = $fpmin; } $c = $b + $an / $c; if (abs($c) < $fpmin) { $c = $fpmin; } $d = 1 / $d; $del = $d * $c; $h = $h * $del; if (abs($del - 1) < self::EPS) { break; } } return $h * exp(-$x + $a * log($x) - $gln); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php ================================================ 1.0) { throw new Exception(ExcelError::NAN()); } return $probability; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $lambda, mixed $cumulative): array|string|float { if (is_array($value) || is_array($lambda) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $lambda, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $lambda = DistributionValidations::validateFloat($lambda); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($lambda < 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return 1 - exp(0 - $value * $lambda); } return $lambda * exp(0 - $value * $lambda); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $u, mixed $v, mixed $cumulative): array|string|float { if (is_array($value) || is_array($u) || is_array($v) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $u, $v, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $u = DistributionValidations::validateInt($u); $v = DistributionValidations::validateInt($v); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($value < 0 || $u < 1 || $v < 1) { return ExcelError::NAN(); } if ($cumulative) { $adjustedValue = ($u * $value) / ($u * $value + $v); return Beta::incompleteBeta($adjustedValue, $u / 2, $v / 2); } return (Gamma::gammaValue(($v + $u) / 2) / (Gamma::gammaValue($u / 2) * Gamma::gammaValue($v / 2))) * (($u / $v) ** ($u / 2)) * (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2))); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if (($value <= -1) || ($value >= 1)) { return ExcelError::NAN(); } return 0.5 * log((1 + $value) / (1 - $value)); } /** * FISHERINV. * * Returns the inverse of the Fisher transformation. Use this transformation when * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability): array|string|float { if (is_array($probability)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $probability); } try { $probability = DistributionValidations::validateFloat($probability); } catch (Exception $e) { return $e->getMessage(); } return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gamma(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ((((int) $value) == ((float) $value)) && $value <= 0.0) { return ExcelError::NAN(); } return self::gammaValue($value); } /** * GAMMADIST. * * Returns the gamma distribution. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * @param mixed $a Parameter to the distribution as a float * Or can be an array of values * @param mixed $b Parameter to the distribution as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $a, mixed $b, mixed $cumulative) { if (is_array($value) || is_array($a) || is_array($b) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $a, $b, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $a = DistributionValidations::validateFloat($a); $b = DistributionValidations::validateFloat($b); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($a <= 0) || ($b <= 0)) { return ExcelError::NAN(); } return self::calculateDistribution($value, $a, $b, $cumulative); } /** * GAMMAINV. * * Returns the inverse of the Gamma distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $alpha, mixed $beta) { if (is_array($probability) || is_array($alpha) || is_array($beta)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta); } try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0.0) || ($beta <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta); } /** * GAMMALN. * * Returns the natural logarithm of the gamma function. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ln(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ($value <= 0) { return ExcelError::NAN(); } return log(self::gammaValue($value)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php ================================================ Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = self::calculateDistribution($x, $alpha, $beta, true); $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } $pdf = self::calculateDistribution($x, $alpha, $beta, false); // Avoid division by zero if ($pdf !== 0.0) { $dx = $error / $pdf; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } // // Implementation of the incomplete Gamma function // public static function incompleteGamma(float $a, float $x): float { static $max = 32; $summer = 0; for ($n = 0; $n <= $max; ++$n) { $divisor = $a; for ($i = 1; $i <= $n; ++$i) { $divisor *= ($a + $i); } $summer += ($x ** $n / $divisor); } return $x ** $a * exp(0 - $x) * $summer; } private const GAMMA_VALUE_P0 = 1.000000000190015; private const GAMMA_VALUE_P = [ 1 => 76.18009172947146, 2 => -86.50532032941677, 3 => 24.01409824083091, 4 => -1.231739572450155, 5 => 1.208650973866179e-3, 6 => -5.395239384953e-6, ]; // // Implementation of the Gamma function // public static function gammaValue(float $value): float { if ($value == 0.0) { return 0; } $y = $x = $value; $tmp = $x + 5.5; $tmp -= ($x + 0.5) * log($tmp); $summer = self::GAMMA_VALUE_P0; for ($j = 1; $j <= 6; ++$j) { $summer += (self::GAMMA_VALUE_P[$j] / ++$y); } return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); } private const LG_D1 = -0.5772156649015328605195174; private const LG_D2 = 0.4227843350984671393993777; private const LG_D4 = 1.791759469228055000094023; private const LG_P1 = [ 4.945235359296727046734888, 201.8112620856775083915565, 2290.838373831346393026739, 11319.67205903380828685045, 28557.24635671635335736389, 38484.96228443793359990269, 26377.48787624195437963534, 7225.813979700288197698961, ]; private const LG_P2 = [ 4.974607845568932035012064, 542.4138599891070494101986, 15506.93864978364947665077, 184793.2904445632425417223, 1088204.76946882876749847, 3338152.967987029735917223, 5106661.678927352456275255, 3074109.054850539556250927, ]; private const LG_P4 = [ 14745.02166059939948905062, 2426813.369486704502836312, 121475557.4045093227939592, 2663432449.630976949898078, 29403789566.34553899906876, 170266573776.5398868392998, 492612579337.743088758812, 560625185622.3951465078242, ]; private const LG_Q1 = [ 67.48212550303777196073036, 1113.332393857199323513008, 7738.757056935398733233834, 27639.87074403340708898585, 54993.10206226157329794414, 61611.22180066002127833352, 36351.27591501940507276287, 8785.536302431013170870835, ]; private const LG_Q2 = [ 183.0328399370592604055942, 7765.049321445005871323047, 133190.3827966074194402448, 1136705.821321969608938755, 5267964.117437946917577538, 13467014.54311101692290052, 17827365.30353274213975932, 9533095.591844353613395747, ]; private const LG_Q4 = [ 2690.530175870899333379843, 639388.5654300092398984238, 41355999.30241388052042842, 1120872109.61614794137657, 14886137286.78813811542398, 101680358627.2438228077304, 341747634550.7377132798597, 446315818741.9713286462081, ]; private const LG_C = [ -0.001910444077728, 8.4171387781295e-4, -5.952379913043012e-4, 7.93650793500350248e-4, -0.002777777777777681622553, 0.08333333333333333331554247, 0.0057083835261, ]; // Rough estimate of the fourth root of logGamma_xBig private const LG_FRTBIG = 2.25e76; private const PNT68 = 0.6796875; // Function cache for logGamma private static float $logGammaCacheResult = 0.0; private static float $logGammaCacheX = 0.0; /** * logGamma function. * * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. * * The natural logarithm of the gamma function.
* Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
* Applied Mathematics Division
* Argonne National Laboratory
* Argonne, IL 60439
*

* References: *

    *
  1. W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
  2. *
  3. K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
  4. *
  5. Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
  6. *
*

*

* From the original documentation: *

*

* This routine calculates the LOG(GAMMA) function for a positive real argument X. * Computation is based on an algorithm outlined in references 1 and 2. * The program uses rational functions that theoretically approximate LOG(GAMMA) * to at least 18 significant decimal digits. The approximation for X > 12 is from * reference 3, while approximations for X < 12.0 are similar to those in reference * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, * the compiler, the intrinsic functions, and proper selection of the * machine-dependent constants. *

*

* Error returns:
* The program returns the value XINF for X .LE. 0.0 or when overflow would occur. * The computation is believed to be free of underflow and overflow. *

* * @version 1.1 * * @author Jaco van Kooten * * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 */ public static function logGamma(float $x): float { if ($x == self::$logGammaCacheX) { return self::$logGammaCacheResult; } $y = $x; if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { if ($y <= self::EPS) { $res = -log($y); } elseif ($y <= 1.5) { $res = self::logGamma1($y); } elseif ($y <= 4.0) { $res = self::logGamma2($y); } elseif ($y <= 12.0) { $res = self::logGamma3($y); } else { $res = self::logGamma4($y); } } else { // -------------------------- // Return for bad arguments // -------------------------- $res = self::MAX_VALUE; } // ------------------------------ // Final adjustments and return // ------------------------------ self::$logGammaCacheX = $x; self::$logGammaCacheResult = $res; return $res; } private static function logGamma1(float $y): float { // --------------------- // EPS .LT. X .LE. 1.5 // --------------------- if ($y < self::PNT68) { $corr = -log($y); $xm1 = $y; } else { $corr = 0.0; $xm1 = $y - 1.0; } $xden = 1.0; $xnum = 0.0; if ($y <= 0.5 || $y >= self::PNT68) { for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm1 + self::LG_P1[$i]; $xden = $xden * $xm1 + self::LG_Q1[$i]; } return $corr + $xm1 * (self::LG_D1 + $xm1 * ($xnum / $xden)); } $xm2 = $y - 1.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $corr + $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } private static function logGamma2(float $y): float { // --------------------- // 1.5 .LT. X .LE. 4.0 // --------------------- $xm2 = $y - 2.0; $xden = 1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } protected static function logGamma3(float $y): float { // ---------------------- // 4.0 .LT. X .LE. 12.0 // ---------------------- $xm4 = $y - 4.0; $xden = -1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm4 + self::LG_P4[$i]; $xden = $xden * $xm4 + self::LG_Q4[$i]; } return self::LG_D4 + $xm4 * ($xnum / $xden); } protected static function logGamma4(float $y): float { // --------------------------------- // Evaluate for argument .GE. 12.0 // --------------------------------- $res = 0.0; if ($y <= self::LG_FRTBIG) { $res = self::LG_C[6]; $ysq = $y * $y; for ($i = 0; $i < 6; ++$i) { $res = $res / $ysq + self::LG_C[$i]; } $res /= $y; $corr = log($y); $res = $res + log(self::SQRT2PI) - 0.5 * $corr; $res += $y * ($corr - 1.0); } return $res; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php ================================================ |float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $sampleSuccesses, mixed $sampleNumber, mixed $populationSuccesses, mixed $populationNumber): array|string|float { if ( is_array($sampleSuccesses) || is_array($sampleNumber) || is_array($populationSuccesses) || is_array($populationNumber) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber ); } try { $sampleSuccesses = DistributionValidations::validateInt($sampleSuccesses); $sampleNumber = DistributionValidations::validateInt($sampleNumber); $populationSuccesses = DistributionValidations::validateInt($populationSuccesses); $populationNumber = DistributionValidations::validateInt($populationNumber); } catch (Exception $e) { return $e->getMessage(); } if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { return ExcelError::NAN(); } if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { return ExcelError::NAN(); } if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { return ExcelError::NAN(); } $successesPopulationAndSample = (float) Combinations::withoutRepetition($populationSuccesses, $sampleSuccesses); $numbersPopulationAndSample = (float) Combinations::withoutRepetition($populationNumber, $sampleNumber); $adjustedPopulationAndSample = (float) Combinations::withoutRepetition( $populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses ); return $successesPopulationAndSample * $adjustedPopulationAndSample / $numbersPopulationAndSample; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative(mixed $value, mixed $mean, mixed $stdDev) { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if (($value <= 0) || ($stdDev <= 0)) { return ExcelError::NAN(); } return StandardNormal::cumulative((log($value) - $mean) / $stdDev); } /** * LOGNORM.DIST. * * Returns the lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $stdDev, mixed $cumulative = false) { if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value <= 0) || ($stdDev <= 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return StandardNormal::distribution((log($value) - $mean) / $stdDev, true); } return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) * exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2))); } /** * LOGINV. * * Returns the inverse of the lognormal cumulative distribution * * @param mixed $probability Float probability for which we want the value * Or can be an array of values * @param mixed $mean Mean Value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * @TODO Try implementing P J Acklam's refinement algorithm for greater * accuracy if I can get my head round the mathematics * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ */ public static function inverse(mixed $probability, mixed $mean, mixed $stdDev): array|string|float { if (is_array($probability) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); } try { $probability = DistributionValidations::validateProbability($probability); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } /** @var float $inverse */ $inverse = StandardNormal::inverse($probability); return exp($mean + $stdDev * $inverse); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php ================================================ callback = $callback; } public function execute(float $probability): string|int|float { $xLo = 100; $xHi = 0; $dx = 1; $x = $xNew = 1; $i = 0; while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = call_user_func($this->callback, $x); if (!is_float($result)) { return ExcelError::VALUE(); } $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } // Avoid division by zero if ($result != 0.0) { $dx = $error / $result; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i == self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $stdDev, mixed $cumulative): array|string|float { if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev < 0) { return ExcelError::NAN(); } if ($cumulative) { return 0.5 * (1 + Engineering\Erf::erfValue(($value - $mean) / ($stdDev * sqrt(2)))); } return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev)))); } /** * NORMINV. * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * * @param mixed $probability Float probability for which we want the value * Or can be an array of values * @param mixed $mean Mean Value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $mean, mixed $stdDev): array|string|float { if (is_array($probability) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); } try { $probability = DistributionValidations::validateProbability($probability); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev < 0) { return ExcelError::NAN(); } return (self::inverseNcdf($probability) * $stdDev) + $mean; } /* * inverse_ncdf.php * ------------------- * begin : Friday, January 16, 2004 * copyright : (C) 2004 Michael Nickerson * email : nickersonm@yahoo.com * */ private static function inverseNcdf(float $p): float { // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html // I have not checked the accuracy of this implementation. Be aware that PHP // will truncate the coeficcients to 14 digits. // You have permission to use and distribute this function freely for // whatever purpose you want, but please show common courtesy and give credit // where credit is due. // Input parameter is $p - probability - where 0 < p < 1. // Coefficients in rational approximations /** @var array */ static $a = [ 1 => -3.969683028665376e+01, 2 => 2.209460984245205e+02, 3 => -2.759285104469687e+02, 4 => 1.383577518672690e+02, 5 => -3.066479806614716e+01, 6 => 2.506628277459239e+00, ]; /** @var array */ static $b = [ 1 => -5.447609879822406e+01, 2 => 1.615858368580409e+02, 3 => -1.556989798598866e+02, 4 => 6.680131188771972e+01, 5 => -1.328068155288572e+01, ]; /** @var array */ static $c = [ 1 => -7.784894002430293e-03, 2 => -3.223964580411365e-01, 3 => -2.400758277161838e+00, 4 => -2.549732539343734e+00, 5 => 4.374664141464968e+00, 6 => 2.938163982698783e+00, ]; /** @var array */ static $d = [ 1 => 7.784695709041462e-03, 2 => 3.224671290700398e-01, 3 => 2.445134137142996e+00, 4 => 3.754408661907416e+00, ]; // Define lower and upper region break-points. $p_low = 0.02425; //Use lower region approx. below this $p_high = 1 - $p_low; //Use upper region approx. above this if (0 < $p && $p < $p_low) { // Rational approximation for lower region. $q = sqrt(-2 * log($p)); return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } elseif ($p_high < $p && $p < 1) { // Rational approximation for upper region. $q = sqrt(-2 * log(1 - $p)); return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } // Rational approximation for central region. $q = $p - 0.5; $r = $q * $q; return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $cumulative): array|string|float { if (is_array($value) || is_array($mean) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($mean < 0)) { return ExcelError::NAN(); } if ($cumulative) { $summer = 0; $floor = floor($value); for ($i = 0; $i <= $floor; ++$i) { /** @var float $fact */ $fact = MathTrig\Factorial::fact($i); $summer += $mean ** $i / $fact; } return exp(0 - $mean) * $summer; } /** @var float $fact */ $fact = MathTrig\Factorial::fact($value); return (exp(0 - $mean) * $mean ** $value) / $fact; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative(mixed $value) { return Normal::distribution($value, 0, 1, true); } /** * NORM.S.DIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value and cumulative through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $cumulative) { return Normal::distribution($value, 0, 1, $cumulative); } /** * NORMSINV. * * Returns the inverse of the standard normal cumulative distribution * * @param mixed $value float probability for which we want the value * Or can be an array of values * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::inverse() * All we need to do is pass the value through as scalar or as array * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $value) { return Normal::inverse($value, 0, 1); } /** * GAUSS. * * Calculates the probability that a member of a standard normal population will fall between * the mean and z standard deviations from the mean. * * @param mixed $value Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gauss(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_numeric($value)) { return ExcelError::VALUE(); } /** @var float $dist */ $dist = self::distribution($value, true); return $dist - 0.5; } /** * ZTEST. * * Returns the one-tailed P-value of a z-test. * * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be * greater than the average of observations in the data set (array) — that is, the observed sample mean. * * @param mixed $dataSet The dataset should be an array of float values for the observations * @param mixed $m0 Alpha Parameter * Or can be an array of values * @param mixed $sigma A null or float value for the Beta (Standard Deviation) Parameter; * if null, we use the standard deviation of the dataset * Or can be an array of values * * @return array|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function zTest(mixed $dataSet, mixed $m0, mixed $sigma = null) { if (is_array($m0) || is_array($sigma)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $dataSet, $m0, $sigma); } $dataSet = Functions::flattenArrayIndexed($dataSet); if (!is_numeric($m0) || ($sigma !== null && !is_numeric($sigma))) { return ExcelError::VALUE(); } if ($sigma === null) { /** @var float $sigma */ $sigma = StandardDeviations::STDEV($dataSet); } $n = count($dataSet); $sub1 = Averages::average($dataSet); if (!is_numeric($sub1)) { return $sub1; } $temp = self::cumulative(($sub1 - $m0) / ($sigma / sqrt($n))); return 1 - (is_numeric($temp) ? $temp : 0); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/StudentT.php ================================================ |float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $degrees, mixed $tails) { return self::calcDistribution($value, $degrees, $tails, self::distribution(...)); } /** * T.DIST.2T. * Returns the two-tailed Student's t distribution. * * @return array|float|string The result, or a string containing an error */ public static function tDotDistDot2T(mixed $value, mixed $degrees) { return self::calcDistribution($value, $degrees, 2, self::distribution(...)); } /** * T.DIST.RT. * Returns the right-tailed Student's t distribution. * * @return array|float|string The result, or a string containing an error */ public static function tDotDistDotRT(mixed $value, mixed $degrees) { return self::calcDistribution($value, $degrees, 1, self::distribution(...)); } /** * @return array|float|string The result, or a string containing an error */ private static function calcDistribution(mixed $value, mixed $degrees, mixed $tails, callable $callback) { if (is_array($value) || is_array($degrees) || is_array($tails)) { return self::evaluateArrayArguments($callback, $value, $degrees, $tails); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $tails = DistributionValidations::validateInt($tails); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { return ExcelError::NAN(); } return self::subTProb($value, $degrees, $tails); } /** * Based on code from Perl CPAN Statistical::Distributions. */ private static function subTProb(float $x, int $n, int $tails): float { $w = atan2($x / sqrt($n), 1); $z = cos($w) ** 2; $y = 1; for ($i = $n - 2; $i >= 2; $i -= 2) { $y = 1 + ($i - 1) / $i * $z * $y; } if ($n % 2 == 0) { $a = sin($w) / 2; $b = 0.5; } else { $a = ($n == 1) ? 0 : (sin($w) * cos($w) / M_PI); $b = 0.5 + $w / M_PI; } return $tails * max(0, 1 - $b - $a * $y); } /** * T.DIST. * Returns the Student's left-tailed t distribution, * either as a cumulative distribution function (cdf) (TRUE) * or as a probability density function (pdf) (FALSE), * where TRUE/FALSE are the value of $cumulative parameter. * * "True" algoritm adapted from java. * org.apache.commons.math3.distribution.TDistribution. * "False" algorithm comes from: * https://statproofbook.github.io/P/t-pdf.html * * @param mixed $cumulative Expecting bool. See above for explanation. * * @return array|float|string The result, or a string containing an error */ public static function tDotDist(mixed $value, mixed $degrees, mixed $cumulative) { if (is_array($value) || is_array($degrees) || is_array($cumulative)) { return self::evaluateArrayArguments(self::tDotDist(...), $value, $degrees, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } /** @var int $degrees */ if (($degrees < 1)) { return ExcelError::NAN(); } /** @var float $value */ if (!$cumulative) { return self::tDotDistFalse($value, $degrees); } $f16 = $degrees / ($degrees + $value * $value); $g16 = 0.5 * $degrees; $h16 = 0.5; $result = Beta::distribution($f16, $g16, $h16); if (is_numeric($result)) { $result = ($value < 0) ? (0.5 * $result) : (1 - 0.5 * $result); } return $result; } private static function tDotDistFalse(float $value, int $degrees): float|string { $result = $k15 = Gamma::gamma(($degrees + 1) / 2); if (is_numeric($k15)) { $result = $k16 = Gamma::gamma($degrees / 2); if (is_numeric($k16)) { $k17 = sqrt(M_PI * $degrees); $k18 = $k15 / ($k16 * $k17); $k19 = $value * $value / $degrees + 1; $k20 = -($degrees + 1) / 2; $k21 = $k19 ** $k20; $result = $k18 * $k21; } } /** @var float|string $result */ return $result; } /** * TINV and T.INV.2T. * Returns the two-tailed inverse of the Student t distribution. * * @param mixed $probability Float probability for the function * Or can be an array of values * @param mixed $degrees Integer value for degrees of freedom * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $degrees) { return self::calcInverse($probability, $degrees, 2, self::inverse(...)); } /** * @return array|float|string The result, or a string containing an error */ private static function calcInverse(mixed $probability, mixed $degrees, int $tails, callable $callback2) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments($callback2, $probability, $degrees, $tails); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees <= 0) { return ExcelError::NAN(); } $callback = fn ($value) => self::distribution($value, $degrees, $tails); $newtonRaphson = new NewtonRaphson($callback); $result = $newtonRaphson->execute($probability); if (is_numeric($result) && $tails === 1) { $result = -$result; // @codeCoverageIgnore } return $result; } /** * T.INV. * Returns the left-tailed inverse of the Student's t distribution. * * Based on code from Perl CPAN Statistical::Distributions. * * @return array|float|string The result, or a string containing an error */ public static function tDotInv(mixed $probability, mixed $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments(self::tDotInv(...), $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($probability == 0.5) { return 0.0; } if ($probability < 0.5) { $result = self::tDotInv(1.0 - $probability, $degrees); return is_numeric($result) ? -$result : $result; } $p = $probability; $n = $degrees; $u = self::subU($p); $u2 = $u ** 2; $a = ($u2 + 1) / 4; $b = ((5 * $u2 + 16) * $u2 + 3) / 96; $c = (((3 * $u2 + 19) * $u2 + 17) * $u2 - 15) / 384; $d = ((((79 * $u2 + 776) * $u2 + 1482) * $u2 - 1920) * $u2 - 945) / 92160; $e = (((((27 * $u2 + 339) * $u2 + 930) * $u2 - 1782) * $u2 - 765) * $u2 + 17955) / 368640; $x = $u * (1 + ($a + ($b + ($c + ($d + $e / $n) / $n) / $n) / $n) / $n); if ($n <= log10($p) ** 2 + 3) { do { $p1 = self::subTProb($x, $n, 1); $n1 = $n + 1; $delta = ($p1 - $p) / exp(($n1 * log($n1 / ($n + $x * $x)) + log($n / $n1 / 2 / M_PI) - 1 + (1 / $n1 - 1 / $n) / 6) / 2); $x += $delta; $round = sprintf('%.' . abs((int) (log10(abs($x)) - 4)) . 'F', $delta); } while (($x) && ($round != 0)); } return -$x; } /** * Based on code from Perl CPAN Statistical::Distributions. */ private static function subU(float $p): float { $y = -log(4 * $p * (1 - $p)); $x = sqrt( $y * (1.570796288 + $y * (.03706987906 + $y * (-.8364353589E-3 + $y * (-.2250947176E-3 + $y * (.6841218299E-5 + $y * (0.5824238515E-5 + $y * (-.104527497E-5 + $y * (.8360937017E-7 + $y * (-.3231081277E-8 + $y * (.3657763036E-10 + $y * .6936233982E-12)))))))))) ); if ($p > 0.5) { $x = -$x; } return $x; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php ================================================ |float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $alpha, mixed $beta, mixed $cumulative): array|string|float { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { return ExcelError::NAN(); } if ($cumulative) { return 1 - exp(0 - ($value / $beta) ** $alpha); } return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php ================================================ $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } /** @var float|int|string $returnValue */ return $returnValue; } /** * MAXA. * * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MAXA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function maxA(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg, true)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } /** @var float|int|string $returnValue */ return $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Minimum.php ================================================ getMessage(); } if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } $mArgs = self::percentileFilterValues($aArgs); $mValueCount = count($mArgs); if ($mValueCount > 0) { sort($mArgs); /** @var float[] $mArgs */ $count = Counts::COUNT($mArgs); $index = $entry * ($count - 1); $indexFloor = floor($index); $iBase = (int) $indexFloor; if ($index == $indexFloor) { return $mArgs[$iBase]; } $iNext = $iBase + 1; $iProportion = $index - $iBase; return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); } return ExcelError::NAN(); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. * Note that the returned rank is simply rounded to the appropriate significant digits, * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return * 0.667 rather than 0.666 * * @param mixed $valueSet An array of (float) values, or a reference to, a list of numbers * @param mixed $value The number whose rank you want to find * @param mixed $significance The (integer) number of significant digits for the returned percentage value * * @return float|string (string if result is an error) */ public static function PERCENTRANK(mixed $valueSet, mixed $value, mixed $significance = 3): string|float { $valueSet = Functions::flattenArray($valueSet); $value = Functions::flattenSingleValue($value); $significance = ($significance === null) ? 3 : Functions::flattenSingleValue($significance); try { $value = StatisticalValidations::validateFloat($value); $significance = StatisticalValidations::validateInt($significance); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); $valueCount = count($valueSet); if ($valueCount == 0) { return ExcelError::NA(); } sort($valueSet, SORT_NUMERIC); $valueAdjustor = $valueCount - 1; if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { return ExcelError::NA(); } $pos = array_search($value, $valueSet); if ($pos === false) { /** @var float[] $valueSet */ $pos = 0; $testValue = $valueSet[0]; while ($testValue < $value) { $testValue = $valueSet[++$pos]; } --$pos; $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); } return round(((float) $pos) / $valueAdjustor, $significance); } /** * QUARTILE. * * Returns the quartile of a data set. * * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function QUARTILE(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } $entry = floor($entry); $entry /= 4; if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } return self::PERCENTILE($aArgs, $entry); } /** * RANK. * * Returns the rank of a number in a list of numbers. * * @param mixed $value The number whose rank you want to find * @param mixed $valueSet An array of float values, or a reference to, a list of numbers * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error (0 = Descending, 1 = Ascending) */ public static function RANK(mixed $value, mixed $valueSet, mixed $order = self::RANK_SORT_DESCENDING) { $value = Functions::flattenSingleValue($value); $valueSet = Functions::flattenArray($valueSet); $order = ($order === null) ? self::RANK_SORT_DESCENDING : Functions::flattenSingleValue($order); try { $value = StatisticalValidations::validateFloat($value); $order = StatisticalValidations::validateInt($order); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); if ($order === self::RANK_SORT_DESCENDING) { rsort($valueSet, SORT_NUMERIC); } else { sort($valueSet, SORT_NUMERIC); } $pos = array_search($value, $valueSet); if ($pos === false) { return ExcelError::NA(); } return ++$pos; } /** * @param mixed[] $dataSet * * @return mixed[] */ protected static function percentileFilterValues(array $dataSet): array { return array_filter( $dataSet, fn ($value): bool => is_numeric($value) && !is_string($value) ); } /** * @param mixed[] $dataSet * * @return mixed[] */ protected static function rankFilterValues(array $dataSet): array { return array_filter( $dataSet, fn ($value): bool => is_numeric($value) ); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Permutations.php ================================================ |float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUT(mixed $numObjs, mixed $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < $numInSet) { return ExcelError::NAN(); } /** @var float|int|string */ $result1 = MathTrig\Factorial::fact($numObjs); if (is_string($result1)) { return $result1; } /** @var float|int|string */ $result2 = MathTrig\Factorial::fact($numObjs - $numInSet); if (is_string($result2)) { return $result2; } $result = round($result1 / $result2); return IntOrFloat::evaluate($result); } /** * PERMUTATIONA. * * Returns the number of permutations for a given number of objects (with repetitions) * that can be selected from the total objects. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUTATIONA(mixed $numObjs, mixed $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < 0 || $numInSet < 0) { return ExcelError::NAN(); } $result = $numObjs ** $numInSet; return IntOrFloat::evaluate($result); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/Size.php ================================================ = $count) { return ExcelError::NAN(); } rsort($mArgs); /** @var float[] $mArgs */ return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * SMALL. * * Returns the nth smallest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * SMALL(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function small(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } sort($mArgs); /** @var float[] $mArgs */ return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * @param mixed[] $args Data values * * @return mixed[] */ protected static function filter(array $args): array { $mArgs = []; foreach ($args as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } return $mArgs; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php ================================================ |float $value Value to normalize * Or can be an array of values * @param array|float $mean Mean Value * Or can be an array of values * @param array|float $stdDev Standard Deviation * Or can be an array of values * * @return array|float|string Standardized value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function execute($value, $mean, $stdDev): array|string|float { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = self::validateFloat($value); $mean = self::validateFloat($mean); $stdDev = self::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } return ($value - $mean) / $stdDev; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php ================================================ $array1 * @param array $array2 */ private static function filterTrendValues(array &$array1, array &$array2): void { foreach ($array1 as $key => $value) { if ((is_bool($value)) || (is_string($value)) || ($value === null)) { unset($array1[$key], $array2[$key]); } } } /** * @param mixed $array1 should be array, but scalar is made into one * @param mixed $array2 should be array, but scalar is made into one * * @param-out array $array1 * @param-out array $array2 */ private static function checkTrendArrays(mixed &$array1, mixed &$array2): void { if (!is_array($array1)) { $array1 = [$array1]; } if (!is_array($array2)) { $array2 = [$array2]; } $array1 = Functions::flattenArray($array1); $array2 = Functions::flattenArray($array2); self::filterTrendValues($array1, $array2); self::filterTrendValues($array2, $array1); // Reset the array indexes $array1 = array_merge($array1); $array2 = array_merge($array2); } /** * @param mixed[] $yValues * @param mixed[] $xValues */ protected static function validateTrendArrays(array $yValues, array $xValues): void { $yValueCount = count($yValues); $xValueCount = count($xValues); if (($yValueCount === 0) || ($yValueCount !== $xValueCount)) { throw new Exception(ExcelError::NA()); } elseif ($yValueCount === 1) { throw new Exception(ExcelError::DIV0()); } } /** * CORREL. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X */ public static function CORREL(mixed $yValues, $xValues = null): float|string { if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { return ExcelError::VALUE(); } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCorrelation(); } /** * COVAR. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed[] $yValues array of mixed Data Series Y * @param mixed[] $xValues array of mixed Data Series X */ public static function COVAR(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCovariance(); } /** * FORECAST. * * Calculates, or predicts, a future value by using existing values. * The predicted value is a y-value for a given x-value. * * @param mixed $xValue Float value of X for which we want to find Y * Or can be an array of values * @param mixed[] $yValues array of mixed Data Series Y * @param mixed[] $xValues array of mixed Data Series X * * @return array|bool|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function FORECAST(mixed $xValue, array $yValues, array $xValues) { if (is_array($xValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $xValue, $yValues, $xValues); } try { $xValue = StatisticalValidations::validateFloat($xValue); self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getValueOfYForX($xValue); } /** * GROWTH. * * Returns values along a predicted exponential Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return array>> */ public static function GROWTH(array $yValues, array $xValues = [], array $newValues = [], mixed $const = true): array { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); $newValues = Functions::flattenArray($newValues); $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if (empty($newValues)) { $newValues = $bestFitExponential->getXValues(); } $returnArray = []; foreach ($newValues as $xValue) { /** @var float $xValue */ $returnArray[0][] = [$bestFitExponential->getValueOfYForX($xValue)]; } return $returnArray; } /** * INTERCEPT. * * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X */ public static function INTERCEPT(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getIntersect(); } /** * LINEST. * * Calculates the statistics for a line by using the "least squares" method to calculate a straight line * that best fits your data, and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array|string The result, or a string containing an error */ public static function LINEST(array $yValues, ?array $xValues = null, mixed $const = true, mixed $stats = false): string|array { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ], [ $bestFitLinear->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitLinear->getIntersectSE(), ], [ $bestFitLinear->getGoodnessOfFit(), $bestFitLinear->getStdevOfResiduals(), ], [ $bestFitLinear->getF(), $bestFitLinear->getDFResiduals(), ], [ $bestFitLinear->getSSRegression(), $bestFitLinear->getSSResiduals(), ], ]; } return [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ]; } /** * LOGEST. * * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array|string The result, or a string containing an error */ public static function LOGEST(array $yValues, ?array $xValues = null, mixed $const = true, mixed $stats = false): string|array { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } foreach ($yValues as $value) { if ($value < 0.0) { return ExcelError::NAN(); } } $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ], [ $bestFitExponential->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitExponential->getIntersectSE(), ], [ $bestFitExponential->getGoodnessOfFit(), $bestFitExponential->getStdevOfResiduals(), ], [ $bestFitExponential->getF(), $bestFitExponential->getDFResiduals(), ], [ $bestFitExponential->getSSRegression(), $bestFitExponential->getSSResiduals(), ], ]; } return [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ]; } /** * RSQ. * * Returns the square of the Pearson product moment correlation coefficient through data points * in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function RSQ(array $yValues, array $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getGoodnessOfFit(); } /** * SLOPE. * * Returns the slope of the linear regression line through data points in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function SLOPE(array $yValues, array $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getSlope(); } /** * STEYX. * * Returns the standard error of the predicted y-value for each x in the regression. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X */ public static function STEYX(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getStdevOfResiduals(); } /** * TREND. * * Returns values along a linear Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return array>> */ public static function TREND(array $yValues, array $xValues = [], array $newValues = [], mixed $const = true): array { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); $newValues = Functions::flattenArray($newValues); $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if (empty($newValues)) { $newValues = $bestFitLinear->getXValues(); } $returnArray = []; foreach ($newValues as $xValue) { /** @var float $xValue */ $returnArray[0][] = [$bestFitLinear->getValueOfYForX($xValue)]; } return $returnArray; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php ================================================ 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARA. * * Estimates variance based on a sample, including numbers, text, and logical values * * Excel Function: * VARA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARA(mixed ...$args): string|float { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARP. * * Calculates variance based on the entire population * * Excel Function: * VARP(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARP(mixed ...$args): float|string { // Return value $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } /** * VARPA. * * Calculates variance based on the entire population, including numbers, text, and logical values * * Excel Function: * VARPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARPA(mixed ...$args): string|float { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php ================================================ |string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function lower(mixed $mixedCaseValue): array|string { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } try { $mixedCaseValue = Helpers::extractString($mixedCaseValue, true); } catch (CalcExp $e) { return $e->getMessage(); } return StringHelper::strToLower($mixedCaseValue); } /** * UPPERCASE. * * Converts a string value to upper case. * * @param mixed $mixedCaseValue The string value to convert to upper case * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function upper(mixed $mixedCaseValue): array|string { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } try { $mixedCaseValue = Helpers::extractString($mixedCaseValue, true); } catch (CalcExp $e) { return $e->getMessage(); } return StringHelper::strToUpper($mixedCaseValue); } /** * PROPERCASE. * * Converts a string value to proper or title case. * * @param mixed $mixedCaseValue The string value to convert to title case * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function proper(mixed $mixedCaseValue): array|string { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } try { $mixedCaseValue = Helpers::extractString($mixedCaseValue, true); } catch (CalcExp $e) { return $e->getMessage(); } return StringHelper::strToTitle($mixedCaseValue); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/CharacterConvert.php ================================================ |string The character string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function character(mixed $character): array|string { if (is_array($character)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $character); } return self::characterBoth($character, true); } /** @return array|string */ public static function characterUnicode(mixed $character): array|string { if (is_array($character)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $character); } return self::characterBoth($character, false); } private static function characterBoth(mixed $character, bool $ansi = true): string { try { $character = Helpers::validateInt($character, true); } catch (CalcExp $e) { return $e->getMessage(); } if ($ansi && $character === 219 && self::$oneByteCharacterSet[0] === 'M') { return '€'; } $min = Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE ? 0 : 1; if ($character < $min || ($ansi && $character > 255) || $character > 0x10FFFF) { return ExcelError::VALUE(); } if ($character > 0x10FFFD) { // last assigned return ExcelError::NA(); } if ($ansi) { $result = chr($character); return (string) iconv(self::$oneByteCharacterSet, 'UTF-8//IGNORE', $result); } return mb_chr($character, 'UTF-8'); } /** * CODE. * * @param mixed $characters String character to convert to its ASCII value * Or can be an array of values * * @return array|int|string A string if arguments are invalid * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function code(mixed $characters): array|string|int { if (is_array($characters)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $characters); } if (is_bool($characters) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $characters = $characters ? '1' : '0'; } return self::codeBoth(StringHelper::convertToString($characters, convertBool: true), true); } /** @return array|int|string */ public static function codeUnicode(mixed $characters): array|string|int { if (is_array($characters)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $characters); } if (is_bool($characters) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $characters = $characters ? '1' : '0'; } return self::codeBoth(StringHelper::convertToString($characters, convertBool: true), false); } private static function codeBoth(string $characters, bool $ansi = true): int|string { try { $characters = Helpers::extractString($characters, true); } catch (CalcExp $e) { return $e->getMessage(); } if ($characters === '') { return ExcelError::VALUE(); } $character = $characters; if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); } if ($ansi && $character === '€' && self::$oneByteCharacterSet[0] === 'M') { return 219; } $result = mb_ord($character, 'UTF-8'); if ($ansi) { $result = iconv('UTF-8', self::$oneByteCharacterSet . '//IGNORE', $character); return ($result !== '') ? ord("$result") : 63; // question mark } return $result; } public static function setWindowsCharacterSet(): void { self::$oneByteCharacterSet = 'Windows-1252'; } public static function setMacCharacterSet(): void { self::$oneByteCharacterSet = 'MAC'; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Concatenate.php ================================================ DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::CALC(); break; } } return $returnValue; } /** * This implements the CONCATENATE function. * * @param mixed $args data to be concatenated * * @return array|string */ public static function actualCONCATENATE(...$args): array|string { $useSingle = false; $cell = null; $count = count($args); if ($args[$count - 1] instanceof Cell) { /** @var Cell */ $cell = array_pop($args); $type = $cell->getWorksheet()->getParent()?->getCalculationEngine()->getInstanceArrayReturnType() ?? Calculation::getArrayReturnType(); $useSingle = $type === Calculation::RETURN_ARRAY_AS_VALUE; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_GNUMERIC) { return self::CONCATENATE(...$args); } $result = ''; foreach ($args as $operand2) { if ($useSingle && $cell instanceof Cell && is_array($operand2)) { $temp = Functions::convertArrayToCellRange($operand2); if ($temp !== '') { $operand2 = ExcelArrayPseudoFunctions::single($temp, $cell); } } /** @var null|array|bool|float|int|string $operand2 */ $result = self::concatenate2Args($result, $operand2); if (ErrorValue::isError($result, true) === true) { break; } } return $result; } /** * @param array|string $operand1 * @param null|array|bool|float|int|string $operand2 * * @return array|string */ private static function concatenate2Args(array|string $operand1, null|array|bool|float|int|string $operand2): array|string { if (is_array($operand1) || is_array($operand2)) { $operand1 = Calculation::boolToString($operand1); $operand2 = Calculation::boolToString($operand2); [$rows, $columns] = Calculation::checkMatrixOperands($operand1, $operand2, 2); $errorFound = false; for ($row = 0; $row < $rows && !$errorFound; ++$row) { for ($column = 0; $column < $columns; ++$column) { /** @var string[][] $operand2 */ if (ErrorValue::isError($operand2[$row][$column])) { return $operand2[$row][$column]; } /** @var string[][] $operand1 */ $operand1[$row][$column] = StringHelper::convertToString($operand1[$row][$column], convertBool: true) . StringHelper::convertToString($operand2[$row][$column], convertBool: true); if (mb_strlen($operand1[$row][$column]) > DataType::MAX_STRING_LENGTH) { $operand1 = ExcelError::CALC(); $errorFound = true; break; } } } } elseif (ErrorValue::isError($operand2, true) === true) { $operand1 = (string) $operand2; } else { $operand1 .= StringHelper::convertToString($operand2, convertBool: true); if (mb_strlen($operand1) > DataType::MAX_STRING_LENGTH) { $operand1 = ExcelError::CALC(); } } /** @var array|string $operand1 */ return $operand1; } /** * TEXTJOIN. * * @param null|string|string[] $delimiter The delimiter to use between the joined arguments * Or can be an array of values * @param null|bool|bool[] $ignoreEmpty true/false Flag indicating whether empty arguments should be skipped * Or can be an array of values * @param mixed $args The values to join * * @return array|string The joined string * If an array of values is passed for the $delimiter or $ignoreEmpty arguments, then the returned result * will also be an array with matching dimensions */ public static function TEXTJOIN($delimiter = '', $ignoreEmpty = true, mixed ...$args): array|string { if (is_array($delimiter) || is_array($ignoreEmpty)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $delimiter, $ignoreEmpty, ...$args ); } $delimiter ??= ''; $ignoreEmpty ??= true; /** @var mixed[] */ $aArgs = Functions::flattenArray($args); $returnValue = self::evaluateTextJoinArray($ignoreEmpty, $aArgs); $returnValue ??= implode($delimiter, $aArgs); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::CALC(); } return $returnValue; } /** @param mixed[] $aArgs */ private static function evaluateTextJoinArray(bool $ignoreEmpty, array &$aArgs): ?string { foreach ($aArgs as $key => &$arg) { $value = Helpers::extractString($arg); if (ErrorValue::isError($value, true)) { return $value; } if ($ignoreEmpty === true && ((is_string($arg) && trim($arg) === '') || $arg === null)) { unset($aArgs[$key]); } elseif (is_bool($arg)) { $arg = Helpers::convertBooleanValue($arg); } } return null; } /** * REPT. * * Returns the result of builtin function round after validating args. * * @param mixed $stringValue The value to repeat * Or can be an array of values * @param mixed $repeatCount The number of times the string value should be repeated * Or can be an array of values * * @return array|string The repeated string * If an array of values is passed for the $stringValue or $repeatCount arguments, then the returned result * will also be an array with matching dimensions */ public static function builtinREPT(mixed $stringValue, mixed $repeatCount): array|string { if (is_array($stringValue) || is_array($repeatCount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $stringValue, $repeatCount); } $stringValue = Helpers::extractString($stringValue); if (!is_numeric($repeatCount) || $repeatCount < 0) { $returnValue = ExcelError::VALUE(); } elseif (ErrorValue::isError($stringValue, true)) { $returnValue = $stringValue; } else { $returnValue = str_repeat($stringValue, (int) $repeatCount); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); // note VALUE not CALC } } return $returnValue; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Extract.php ================================================ |string The joined string * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function left(mixed $value, mixed $chars = 1): array|string { if (is_array($value) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); } try { $value = Helpers::extractString($value, true); $chars = Helpers::extractInt($chars, 0, 1); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, 0, $chars, 'UTF-8'); } /** * MID. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $start Integer offset of the first character that we want to extract * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value, $start or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function mid(mixed $value, mixed $start, mixed $chars): array|string { if (is_array($value) || is_array($start) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $start, $chars); } try { $value = Helpers::extractString($value, true); $start = Helpers::extractInt($start, 1); $chars = Helpers::extractInt($chars, 0); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, --$start, $chars, 'UTF-8'); } /** * RIGHT. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function right(mixed $value, mixed $chars = 1): array|string { if (is_array($value) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); } try { $value = Helpers::extractString($value, true); $chars = Helpers::extractInt($chars, 0, 1); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); } /** * TEXTBEFORE. * * @param mixed $text the text that you're searching * Or can be an array of values * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values * @param mixed $instance The instance of the delimiter after which you want to extract the text. * By default, this is the first instance (1). * A negative value means start searching from the end of the text string. * Or can be an array of values * @param mixed $matchMode Determines whether the match is case-sensitive or not. * 0 - Case-sensitive * 1 - Case-insensitive * Or can be an array of values * @param mixed $matchEnd Treats the end of text as a delimiter. * 0 - Don't match the delimiter against the end of the text. * 1 - Match the delimiter against the end of the text. * Or can be an array of values * @param array|bool|float|int|string $ifNotFound value to return if no match is found * The default is a #N/A Error * Or can be an array of values * * @return array|string the string extracted from text before the delimiter; or the $ifNotFound value * If an array of values is passed for any of the arguments, then the returned result * will also be an array with matching dimensions */ public static function before(mixed $text, $delimiter, mixed $instance = 1, mixed $matchMode = 0, mixed $matchEnd = 0, mixed $ifNotFound = '#N/A'): array|string { if (is_array($text) || is_array($instance) || is_array($matchMode) || is_array($matchEnd) || is_array($ifNotFound)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); } try { $text = Helpers::extractString($text ?? '', true); Helpers::extractString(Functions::flattenSingleValue($delimiter ?? ''), true); } catch (CalcExp $e) { return $e->getMessage(); } $instance = (int) StringHelper::convertToString($instance); $matchMode = (int) StringHelper::convertToString($matchMode); $matchEnd = (int) StringHelper::convertToString($matchEnd); $split = self::validateTextBeforeAfter($text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); if (is_string($split)) { return $split; } if (Helpers::extractString(Functions::flattenSingleValue($delimiter ?? '')) === '') { return ($instance > 0) ? '' : $text; } // Adjustment for a match as the first element of the split $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); $adjust = preg_match('/^' . $delimiter . "\$/{$flags}", $split[0]); $oddReverseAdjustment = count($split) % 2; $split = ($instance < 0) ? array_slice($split, 0, max(count($split) - (abs($instance) * 2 - 1) - $adjust - $oddReverseAdjustment, 0)) : array_slice($split, 0, $instance * 2 - 1 - $adjust); return implode('', $split); } /** * TEXTAFTER. * * @param mixed $text the text that you're searching * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values * @param mixed $instance The instance of the delimiter after which you want to extract the text. * By default, this is the first instance (1). * A negative value means start searching from the end of the text string. * Or can be an array of values * @param mixed $matchMode Determines whether the match is case-sensitive or not. * 0 - Case-sensitive * 1 - Case-insensitive * Or can be an array of values * @param mixed $matchEnd Treats the end of text as a delimiter. * 0 - Don't match the delimiter against the end of the text. * 1 - Match the delimiter against the end of the text. * Or can be an array of values * @param array|scalar $ifNotFound value to return if no match is found * The default is a #N/A Error * Or can be an array of values * * @return array|string the string extracted from text before the delimiter; or the $ifNotFound value * If an array of values is passed for any of the arguments, then the returned result * will also be an array with matching dimensions */ public static function after(mixed $text, $delimiter, mixed $instance = 1, mixed $matchMode = 0, mixed $matchEnd = 0, mixed $ifNotFound = '#N/A'): array|string { if (is_array($text) || is_array($instance) || is_array($matchMode) || is_array($matchEnd) || is_array($ifNotFound)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); } try { $text = Helpers::extractString($text ?? '', true); Helpers::extractString(Functions::flattenSingleValue($delimiter ?? ''), true); } catch (CalcExp $e) { return $e->getMessage(); } $instance = (int) StringHelper::convertToString($instance); $matchMode = (int) StringHelper::convertToString($matchMode); $matchEnd = (int) StringHelper::convertToString($matchEnd); $split = self::validateTextBeforeAfter($text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); if (is_string($split)) { return $split; } if (Helpers::extractString(Functions::flattenSingleValue($delimiter ?? '')) === '') { return ($instance < 0) ? '' : $text; } // Adjustment for a match as the first element of the split $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); $adjust = preg_match('/^' . $delimiter . "\$/{$flags}", $split[0]); $oddReverseAdjustment = count($split) % 2; $split = ($instance < 0) ? array_slice($split, count($split) - ((int) abs($instance + 1) * 2) - $adjust - $oddReverseAdjustment) : array_slice($split, $instance * 2 - $adjust); return implode('', $split); } /** * @param null|array|string $delimiter * @param array|scalar $ifNotFound * * @return array|string */ private static function validateTextBeforeAfter(string $text, null|array|string $delimiter, int $instance, int $matchMode, int $matchEnd, mixed $ifNotFound): array|string { $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); if (preg_match('/' . $delimiter . "/{$flags}", $text) === 0 && $matchEnd === 0) { return is_array($ifNotFound) ? $ifNotFound : StringHelper::convertToString($ifNotFound); } $split = preg_split('/' . $delimiter . "/{$flags}", $text, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); if ($split === false) { return ExcelError::NA(); } if ($instance === 0 || abs($instance) > StringHelper::countCharacters($text)) { return ExcelError::VALUE(); } if ($matchEnd === 0 && (abs($instance) > floor(count($split) / 2))) { return ExcelError::NA(); } elseif ($matchEnd !== 0 && (abs($instance) - 1 > ceil(count($split) / 2))) { return ExcelError::NA(); } return $split; } /** * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values */ private static function buildDelimiter($delimiter): string { if (is_array($delimiter)) { /** @var array */ $delimiter = Functions::flattenArray($delimiter); $quotedDelimiters = array_map( fn (?string $delimiter): string => preg_quote($delimiter ?? '', '/'), $delimiter ); $delimiters = implode('|', $quotedDelimiters); return '(' . $delimiters . ')'; } /** @var ?string $delimiter */ return '(' . preg_quote($delimiter ?? '', '/') . ')'; } private static function matchFlags(int $matchMode): string { return ($matchMode === 0) ? 'mu' : 'miu'; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Format.php ================================================ |string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function DOLLAR(mixed $value = 0, mixed $decimals = 2) { if (is_array($value) || is_array($decimals)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals); } try { $value = Helpers::extractFloat($value); $decimals = Helpers::extractInt($decimals, -100, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } $mask = '$#,##0'; if ($decimals > 0) { $mask .= '.' . str_repeat('0', $decimals); } else { $round = 10 ** abs($decimals); if ($value < 0) { $round = 0 - $round; } /** @var float|int|string */ $value = MathTrig\Round::multiple($value, $round); } $mask = "{$mask};-{$mask}"; return NumberFormat::toFormattedString($value, $mask); } /** * FIXED. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimals Integer value for the number of decimal places that should be formatted * Or can be an array of values * @param mixed $noCommas Boolean value indicating whether the value should have thousands separators or not * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function FIXEDFORMAT(mixed $value, mixed $decimals = 2, mixed $noCommas = false): array|string { if (is_array($value) || is_array($decimals) || is_array($noCommas)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals, $noCommas); } try { $value = Helpers::extractFloat($value); $decimals = Helpers::extractInt($decimals, -100, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } $valueResult = round($value, $decimals); if ($decimals < 0) { $decimals = 0; } if ($noCommas === false) { $valueResult = number_format( $valueResult, $decimals, StringHelper::getDecimalSeparator(), StringHelper::getThousandsSeparator() ); } return (string) $valueResult; } /** * TEXT. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $format A string with the Format mask that should be used * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function TEXTFORMAT(mixed $value, mixed $format): array|string { if (is_array($value) || is_array($format)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); } try { $value = Helpers::extractString($value, true); $format = Helpers::extractString($format, true); } catch (CalcExp $e) { return $e->getMessage(); } $format = (string) NumberFormat::convertSystemFormats($format); if (!is_numeric($value) && Date::isDateTimeFormatCode($format) && !Preg::isMatch('/^\s*\d+(\s+\d+)+\s*$/', $value)) { $value1 = DateTimeExcel\DateValue::fromString($value); $value2 = DateTimeExcel\TimeValue::fromString($value); /** @var float|int|string */ $value = (is_numeric($value1) && is_numeric($value2)) ? ($value1 + $value2) : (is_numeric($value1) ? $value1 : (is_numeric($value2) ? $value2 : $value)); } return (string) NumberFormat::toFormattedString($value, $format); } /** * @param mixed $value Value to check */ private static function convertValue(mixed $value, bool $spacesMeanZero = false): mixed { $value = $value ?? 0; if (is_bool($value)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $value = (int) $value; } else { throw new CalcExp(ExcelError::VALUE()); } } if (is_string($value)) { $value = trim($value); if (ErrorValue::isError($value, true)) { throw new CalcExp($value); } if ($spacesMeanZero && $value === '') { $value = 0; } } return $value; } /** * VALUE. * * @param mixed $value Value to check * Or can be an array of values * * @return array|DateTimeInterface|float|int|string A string if arguments are invalid * If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function VALUE(mixed $value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::convertValue($value); } catch (CalcExp $e) { return $e->getMessage(); } if (!is_numeric($value)) { $value = StringHelper::convertToString($value); $numberValue = str_replace( StringHelper::getThousandsSeparator(), '', trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) ); if ($numberValue === '') { return ExcelError::VALUE(); } if (is_numeric($numberValue)) { return (float) $numberValue; } $dateSetting = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); if (str_contains($value, ':')) { $timeValue = Functions::scalar(DateTimeExcel\TimeValue::fromString($value)); if ($timeValue !== ExcelError::VALUE()) { Functions::setReturnDateType($dateSetting); return $timeValue; //* @phpstan-ignore-line } } $dateValue = Functions::scalar(DateTimeExcel\DateValue::fromString($value)); if ($dateValue !== ExcelError::VALUE()) { Functions::setReturnDateType($dateSetting); return $dateValue; //* @phpstan-ignore-line } Functions::setReturnDateType($dateSetting); return ExcelError::VALUE(); } return (float) $value; } /** * VALUETOTEXT. * * @param mixed $value The value to format * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function valueToText(mixed $value, mixed $format = false): array|string { if (is_array($value) || is_array($format)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); } $format = (bool) $format; if (is_object($value) && $value instanceof RichText) { $value = $value->getPlainText(); } if (is_string($value)) { $value = ($format === true) ? StringHelper::convertToString(Calculation::wrapResult($value)) : $value; $value = str_replace("\n", '', $value); } elseif (is_bool($value)) { $value = Calculation::getLocaleBoolean($value ? 'TRUE' : 'FALSE'); } return StringHelper::convertToString($value); } private static function getDecimalSeparator(mixed $decimalSeparator): string { return empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : StringHelper::convertToString($decimalSeparator); } private static function getGroupSeparator(mixed $groupSeparator): string { return empty($groupSeparator) ? StringHelper::getThousandsSeparator() : StringHelper::convertToString($groupSeparator); } /** * NUMBERVALUE. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimalSeparator A string with the decimal separator to use, defaults to locale defined value * Or can be an array of values * @param mixed $groupSeparator A string with the group/thousands separator to use, defaults to locale defined value * Or can be an array of values * * @return array|float|string */ public static function NUMBERVALUE(mixed $value = '', mixed $decimalSeparator = null, mixed $groupSeparator = null): array|string|float { if (is_array($value) || is_array($decimalSeparator) || is_array($groupSeparator)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimalSeparator, $groupSeparator); } try { $value = self::convertValue($value, true); $decimalSeparator = self::getDecimalSeparator($decimalSeparator); $groupSeparator = self::getGroupSeparator($groupSeparator); } catch (CalcExp $e) { return $e->getMessage(); } /** @var null|array|scalar $value */ if (!is_array($value) && !is_numeric($value)) { $value = StringHelper::convertToString($value); $decimalPositions = Preg::matchAllWithOffsets('/' . preg_quote($decimalSeparator, '/') . '/', $value, $matches); if ($decimalPositions > 1) { return ExcelError::VALUE(); } $decimalOffset = array_pop($matches[0])[1] ?? null; if ($decimalOffset === null || strpos($value, $groupSeparator, $decimalOffset) !== false) { return ExcelError::VALUE(); } $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); // Handle the special case of trailing % signs $percentageString = rtrim($value, '%'); if (!is_numeric($percentageString)) { return ExcelError::VALUE(); } $percentageAdjustment = strlen($value) - strlen($percentageString); if ($percentageAdjustment) { $value = (float) $percentageString; $value /= 10 ** ($percentageAdjustment * 2); } } return is_array($value) ? ExcelError::VALUE() : (float) $value; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Helpers.php ================================================ |string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function replace(mixed $oldText, mixed $start, mixed $chars, mixed $newText): array|string { if (is_array($oldText) || is_array($start) || is_array($chars) || is_array($newText)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $oldText, $start, $chars, $newText); } try { $start = Helpers::extractInt($start, 1, 0, true); $chars = Helpers::extractInt($chars, 0, 0, true); $oldText = Helpers::extractString($oldText, true); $newText = Helpers::extractString($newText, true); $left = StringHelper::substring($oldText, 0, $start - 1); $right = StringHelper::substring($oldText, $start + $chars - 1, null); } catch (CalcExp $e) { return $e->getMessage(); } $returnValue = $left . $newText . $right; if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); } return $returnValue; } /** * SUBSTITUTE. * * @param mixed $text The text string value to modify * Or can be an array of values * @param mixed $fromText The string value that we want to replace in $text * Or can be an array of values * @param mixed $toText The string value that we want to replace with in $text * Or can be an array of values * @param mixed $instance Integer instance Number for the occurrence of frmText to change * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function substitute(mixed $text = '', mixed $fromText = '', mixed $toText = '', mixed $instance = null): array|string { if (is_array($text) || is_array($fromText) || is_array($toText) || is_array($instance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $text, $fromText, $toText, $instance); } try { $text = Helpers::extractString($text, true); $fromText = Helpers::extractString($fromText, true); $toText = Helpers::extractString($toText, true); if ($instance === null) { $returnValue = str_replace($fromText, $toText, $text); } else { if (is_bool($instance)) { if ($instance === false || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { return ExcelError::Value(); } $instance = 1; } $instance = Helpers::extractInt($instance, 1, 0, true); $returnValue = self::executeSubstitution($text, $fromText, $toText, $instance); } } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); } return $returnValue; } private static function executeSubstitution(string $text, string $fromText, string $toText, int $instance): string { $pos = -1; while ($instance > 0) { $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); if ($pos === false) { return $text; } --$instance; } return StringHelper::convertToString(Functions::scalar(self::REPLACE($text, ++$pos, StringHelper::countCharacters($fromText), $toText))); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Search.php ================================================ |int|string The offset where the first occurrence of needle was found in the haystack * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function sensitive(mixed $needle, mixed $haystack, mixed $offset = 1): array|string|int { if (is_array($needle) || is_array($haystack) || is_array($offset)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); } try { $needle = Helpers::extractString($needle, true); $haystack = Helpers::extractString($haystack, true); $offset = Helpers::extractInt($offset, 1, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($haystack) >= $offset) { if (StringHelper::countCharacters($needle) === 0) { return $offset; } $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); if ($pos !== false) { return ++$pos; } } return ExcelError::VALUE(); } /** * SEARCH (case-insensitive search). * * @param mixed $needle The string to look for * Or can be an array of values * @param mixed $haystack The string in which to look * Or can be an array of values * @param mixed $offset Integer offset within $haystack to start searching from * Or can be an array of values * * @return array|int|string The offset where the first occurrence of needle was found in the haystack * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function insensitive(mixed $needle, mixed $haystack, mixed $offset = 1): array|string|int { if (is_array($needle) || is_array($haystack) || is_array($offset)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); } try { $needle = Helpers::extractString($needle, true); $haystack = Helpers::extractString($haystack, true); $offset = Helpers::extractInt($offset, 1, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($haystack) >= $offset) { if (StringHelper::countCharacters($needle) === 0) { return $offset; } $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); if ($pos !== false) { return ++$pos; } } return ExcelError::VALUE(); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Text.php ================================================ |int|string If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function length(mixed $value = ''): array|int|string { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = Helpers::extractString($value, true); } catch (CalcExp $e) { return $e->getMessage(); } return mb_strlen($value, 'UTF-8'); } /** * Compares two text strings and returns TRUE if they are exactly the same, FALSE otherwise. * EXACT is case-sensitive but ignores formatting differences. * Use EXACT to test text being entered into a document. * * @param mixed $value1 String Value * Or can be an array of values * @param mixed $value2 String Value * Or can be an array of values * * @return array|bool|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function exact(mixed $value1, mixed $value2): array|bool|string { if (is_array($value1) || is_array($value2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value1, $value2); } try { $value1 = Helpers::extractString($value1, true); $value2 = Helpers::extractString($value2, true); } catch (CalcExp $e) { return $e->getMessage(); } return $value2 === $value1; } /** * T. * * @param mixed $testValue Value to check * Or can be an array of values * * @return array|string If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function test(mixed $testValue = ''): array|string { if (is_array($testValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $testValue); } if (is_string($testValue)) { return $testValue; } return ''; } /** * TEXTSPLIT. * * @param mixed $text the text that you're searching * @param null|array|string $columnDelimiter The text that marks the point where to spill the text across columns. * Multiple delimiters can be passed as an array of string values * @param null|array|string $rowDelimiter The text that marks the point where to spill the text down rows. * Multiple delimiters can be passed as an array of string values * @param bool $ignoreEmpty Specify FALSE to create an empty cell when two delimiters are consecutive. * true = create empty cells * false = skip empty cells * Defaults to TRUE, which creates an empty cell * @param bool $matchMode Determines whether the match is case-sensitive or not. * true = case-sensitive * false = case-insensitive * By default, a case-sensitive match is done. * @param mixed $padding The value with which to pad the result. * The default is #N/A. * * @return array|string the array built from the text, split by the row and column delimiters, or an error string */ public static function split(mixed $text, $columnDelimiter = null, $rowDelimiter = null, bool $ignoreEmpty = false, bool $matchMode = true, mixed $padding = '#N/A'): array|string { $text = Functions::flattenSingleValue($text); if (ErrorValue::isError($text, true)) { return StringHelper::convertToString($text); } $flags = self::matchFlags($matchMode); if ($rowDelimiter !== null) { $delimiter = self::buildDelimiter($rowDelimiter); $rows = ($delimiter === '()') ? [$text] : Preg::split("/{$delimiter}/{$flags}", StringHelper::convertToString($text)); } else { $rows = [$text]; } if ($ignoreEmpty === true) { $rows = array_values(array_filter( $rows, fn ($row): bool => $row !== '' )); } if ($columnDelimiter !== null) { $delimiter = self::buildDelimiter($columnDelimiter); array_walk( $rows, function (&$row) use ($delimiter, $flags, $ignoreEmpty): void { $row = ($delimiter === '()') ? [$row] : Preg::split("/{$delimiter}/{$flags}", StringHelper::convertToString($row)); if ($ignoreEmpty === true) { $row = array_values(array_filter( $row, fn ($value): bool => $value !== '' )); } } ); if ($ignoreEmpty === true) { $rows = array_values(array_filter( $rows, fn ($row): bool => $row !== [] && $row !== [''] )); } } return self::applyPadding($rows, $padding); } /** * @param mixed[] $rows * * @return mixed[] */ private static function applyPadding(array $rows, mixed $padding): array { $columnCount = array_reduce( $rows, fn (int $counter, array $row): int => max($counter, count($row)), //* @phpstan-ignore-line 0 ); return array_map( fn (array $row): array => (count($row) < $columnCount) //* @phpstan-ignore-line ? array_merge($row, array_fill(0, $columnCount - count($row), $padding)) : $row, $rows ); } /** * @param null|array|string $delimiter the text that marks the point before which you want to split * Multiple delimiters can be passed as an array of string values */ private static function buildDelimiter($delimiter): string { $valueSet = Functions::flattenArray($delimiter); if (is_array($delimiter) && count($valueSet) > 1) { /** @var array $valueSet */ $quotedDelimiters = array_map( fn (?string $delimiter): string => preg_quote($delimiter ?? '', '/'), $valueSet ); $delimiters = implode('|', $quotedDelimiters); return '(' . $delimiters . ')'; } return '(' . preg_quote(StringHelper::convertToString(Functions::flattenSingleValue($delimiter)), '/') . ')'; } private static function matchFlags(bool $matchMode): string { return ($matchMode === true) ? 'miu' : 'mu'; } /** @param mixed[][] $array */ public static function fromArray(array $array, int $format = 0): string { $result = []; foreach ($array as $row) { $cells = []; foreach ($row as $cellValue) { $value = ($format === 1) ? self::formatValueMode1($cellValue) : self::formatValueMode0($cellValue); $cells[] = $value; } $result[] = implode(($format === 1) ? ',' : ', ', $cells); } $result = implode(($format === 1) ? ';' : ', ', $result); return ($format === 1) ? '{' . $result . '}' : $result; } private static function formatValueMode0(mixed $cellValue): string { if (is_bool($cellValue)) { return Calculation::getLocaleBoolean($cellValue ? 'TRUE' : 'FALSE'); } return StringHelper::convertToString($cellValue); } private static function formatValueMode1(mixed $cellValue): string { if (is_string($cellValue) && ErrorValue::isError($cellValue) === false) { return Calculation::FORMULA_STRING_QUOTE . $cellValue . Calculation::FORMULA_STRING_QUOTE; } elseif (is_bool($cellValue)) { return Calculation::getLocaleBoolean($cellValue ? 'TRUE' : 'FALSE'); } return StringHelper::convertToString($cellValue); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Thai.php ================================================ 'ศูนย์', 1 => 'หนึ่ง', 2 => 'สอง', 3 => 'สาม', 4 => 'สี่', 5 => 'ห้า', 6 => 'หก', 7 => 'เจ็ด', 8 => 'แปด', 9 => 'เก้า', ]; private const THAI_UNITS = [ 1 => 'สิบ', 2 => 'ร้อย', 3 => 'พัน', 4 => 'หมื่น', 5 => 'แสน', 6 => 'ล้าน', ]; private const THAI_COMPOUND_ONE = 'เอ็ด'; private const THAI_COMPOUND_TWO = 'ยี่'; private const THAI_INTEGER = 'ถ้วน'; private const THAI_MINUS = 'ลบ'; private const THAI_BAHT = 'บาท'; private const THAI_SATANG = 'สตางค์'; /** * BAHTTEXT. * * @param mixed $number The number or array of numbers to convert * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array with the same dimensions */ public static function getBahtText(mixed $number): array|string { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } if (is_string($number) && preg_match('/^-?\d+$/', $number)) { $isNegative = str_starts_with($number, '-'); $baht = ltrim($number, '-0') ?: '0'; $satang = '00'; } elseif (is_bool($number) || is_numeric($number)) { $number += 0; $isNegative = $number < 0; [$baht, $satang] = explode('.', number_format(abs($number), 2, '.', '')); } else { return ExcelError::VALUE(); } $hasWhole = $baht !== '0'; $hasFraction = $satang !== '00'; if (!$hasWhole && !$hasFraction) { return self::THAI_DIGITS[0] . self::THAI_BAHT . self::THAI_INTEGER; } $text = $isNegative ? self::THAI_MINUS : ''; if ($hasWhole) { $text .= self::convertLarge($baht) . self::THAI_BAHT; } $text .= $hasFraction ? self::convertBlock($satang) . self::THAI_SATANG : self::THAI_INTEGER; return $text; } private static function convertLarge(string $digits): string { $length = strlen($digits) % 6 ?: 6; $chunks = [ substr($digits, 0, $length), ...str_split(substr($digits, $length), 6), ]; $chunks = array_filter($chunks, fn (string $chunk): bool => $chunk !== ''); return implode( self::THAI_UNITS[6], array_map(self::convertBlock(...), $chunks) ); } private static function convertBlock(string $block): string { $out = ''; $length = strlen($block); $i = 0; // Hundreds and higher powers for ($power = $length - 1; $power >= 2; --$power) { $digit = $block[$i++]; if ($digit !== '0') { $out .= self::THAI_DIGITS[$digit] . self::THAI_UNITS[$power]; } } // Tens $ten = $length > 1 ? $block[$i++] : '0'; if ($ten !== '0') { $out .= match ($ten) { '1' => '', '2' => self::THAI_COMPOUND_TWO, default => self::THAI_DIGITS[$ten], } . self::THAI_UNITS[1]; } // Ones $one = $block[$i] ?? '0'; if ($one !== '0') { $out .= $ten !== '0' && $one === '1' ? self::THAI_COMPOUND_ONE : self::THAI_DIGITS[$one]; } return $out; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/TextData/Trim.php ================================================ |string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function nonPrintable(mixed $stringValue = '') { if (is_array($stringValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue); } $stringValue = Helpers::extractString($stringValue); return (string) preg_replace('/[\x00-\x1f]/', '', "$stringValue"); } /** * TRIM. * * @param mixed $stringValue String Value to check * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function spaces(mixed $stringValue = ''): array|string { if (is_array($stringValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue); } $stringValue = Helpers::extractString($stringValue); return trim(preg_replace('/ +/', ' ', trim("$stringValue", ' ')) ?? '', ' '); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Token/Stack.php ================================================ > */ private array $stack = []; /** * Count of entries in the parser stack. */ private int $count = 0; public function __construct(BranchPruner $branchPruner) { $this->branchPruner = $branchPruner; } /** * Return the number of entries on the stack. */ public function count(): int { return $this->count; } /** * Push a new entry onto the stack. */ public function push(string $type, mixed $value, ?string $reference = null): void { $stackItem = $this->getStackItem($type, $value, $reference); $this->stack[$this->count++] = $stackItem; if ($type === 'Function') { $localeFunction = Calculation::localeFunc(StringHelper::convertToString($value)); if ($localeFunction != $value) { $this->stack[($this->count - 1)]['localeValue'] = $localeFunction; } } } /** @param array $stackItem */ public function pushStackItem(array $stackItem): void { $this->stack[$this->count++] = $stackItem; } /** @return array */ public function getStackItem(string $type, mixed $value, ?string $reference = null): array { $stackItem = [ 'type' => $type, 'value' => $value, 'reference' => $reference, ]; // will store the result under this alias $storeKey = $this->branchPruner->currentCondition(); if (isset($storeKey) || $reference === 'NULL') { $stackItem['storeKey'] = $storeKey; } // will only run computation if the matching store key is true $onlyIf = $this->branchPruner->currentOnlyIf(); if (isset($onlyIf) || $reference === 'NULL') { $stackItem['onlyIf'] = $onlyIf; } // will only run computation if the matching store key is false $onlyIfNot = $this->branchPruner->currentOnlyIfNot(); if (isset($onlyIfNot) || $reference === 'NULL') { $stackItem['onlyIfNot'] = $onlyIfNot; } return $stackItem; } /** * Pop the last entry from the stack. * * @return null|array */ public function pop(): ?array { if ($this->count > 0) { return $this->stack[--$this->count]; } return null; } /** * Return an entry from the stack without removing it. * * @return null|array */ public function last(int $n = 1): ?array { if ($this->count - $n < 0) { return null; } return $this->stack[$this->count - $n]; } /** * Clear the stack. */ public function clear(): void { $this->stack = []; $this->count = 0; } } ================================================ FILE: src/PhpSpreadsheet/Calculation/Web/Service.php ================================================ 2048) { return ExcelError::VALUE(); // Invalid URL length } $parsed = parse_url($url); $scheme = $parsed['scheme'] ?? ''; if ($scheme !== 'http' && $scheme !== 'https') { return ExcelError::VALUE(); // Invalid protocol } $domainWhiteList = $cell?->getWorksheet()->getParent()?->getDomainWhiteList() ?? []; $host = $parsed['host'] ?? ''; if (!in_array($host, $domainWhiteList, true)) { return ($cell === null) ? null : Functions::NOT_YET_IMPLEMENTED; // will be converted to oldCalculatedValue or null } // Get results from the webservice $ctxArray = [ 'http' => [ 'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', ], ]; if ($scheme === 'https') { $ctxArray['ssl'] = ['crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT]; } $ctx = stream_context_create($ctxArray); $output = @file_get_contents($url, false, $ctx); if ($output === false || mb_strlen($output) > 32767) { return ExcelError::VALUE(); // Output not a string or too long } return $output; } /** * URLENCODE. * * Returns data from a web service on the Internet or Intranet. * * Excel Function: * urlEncode(text) * * @return string the url encoded output */ public static function urlEncode(mixed $text): string { if (!is_string($text)) { return ExcelError::VALUE(); } return str_replace('+', '%20', urlencode($text)); } } ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/bg/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## български (Bulgarian) ## ############################################################ ArgumentSeparator = ; ## ## (For future use) ## currencySymbol = лв ## ## Error Codes ## NULL = #ПРАЗНО! DIV0 = #ДЕЛ/0! VALUE = #СТОЙНОСТ! REF = #РЕФ! NAME = #ИМЕ? NUM = #ЧИСЛО! NA = #Н/Д ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/bg/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## български (Bulgarian) ## ############################################################ ## ## Функции Куб (Cube Functions) ## CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП CUBEMEMBER = КУБЭЛЕМЕНТ CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ CUBESET = КУБМНОЖ CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ CUBEVALUE = КУБЗНАЧЕНИЕ ## ## Функции для работы с базами данных (Database Functions) ## DAVERAGE = ДСРЗНАЧ DCOUNT = БСЧЁТ DCOUNTA = БСЧЁТА DGET = БИЗВЛЕЧЬ DMAX = ДМАКС DMIN = ДМИН DPRODUCT = БДПРОИЗВЕД DSTDEV = ДСТАНДОТКЛ DSTDEVP = ДСТАНДОТКЛП DSUM = БДСУММ DVAR = БДДИСП DVARP = БДДИСПП ## ## Функции даты и времени (Date & Time Functions) ## DATE = ДАТА DATEVALUE = ДАТАЗНАЧ DAY = ДЕНЬ DAYS360 = ДНЕЙ360 EDATE = ДАТАМЕС EOMONTH = КОНМЕСЯЦА HOUR = ЧАС MINUTE = МИНУТЫ MONTH = МЕСЯЦ NETWORKDAYS = ЧИСТРАБДНИ NOW = ТДАТА SECOND = СЕКУНДЫ TIME = ВРЕМЯ TIMEVALUE = ВРЕМЗНАЧ TODAY = СЕГОДНЯ WEEKDAY = ДЕНЬНЕД WEEKNUM = НОМНЕДЕЛИ WORKDAY = РАБДЕНЬ YEAR = ГОД YEARFRAC = ДОЛЯГОДА ## ## Инженерные функции (Engineering Functions) ## BESSELI = БЕССЕЛЬ.I BESSELJ = БЕССЕЛЬ.J BESSELK = БЕССЕЛЬ.K BESSELY = БЕССЕЛЬ.Y BIN2DEC = ДВ.В.ДЕС BIN2HEX = ДВ.В.ШЕСТН BIN2OCT = ДВ.В.ВОСЬМ COMPLEX = КОМПЛЕКСН CONVERT = ПРЕОБР DEC2BIN = ДЕС.В.ДВ DEC2HEX = ДЕС.В.ШЕСТН DEC2OCT = ДЕС.В.ВОСЬМ DELTA = ДЕЛЬТА ERF = ФОШ ERFC = ДФОШ GESTEP = ПОРОГ HEX2BIN = ШЕСТН.В.ДВ HEX2DEC = ШЕСТН.В.ДЕС HEX2OCT = ШЕСТН.В.ВОСЬМ IMABS = МНИМ.ABS IMAGINARY = МНИМ.ЧАСТЬ IMARGUMENT = МНИМ.АРГУМЕНТ IMCONJUGATE = МНИМ.СОПРЯЖ IMCOS = МНИМ.COS IMDIV = МНИМ.ДЕЛ IMEXP = МНИМ.EXP IMLN = МНИМ.LN IMLOG10 = МНИМ.LOG10 IMLOG2 = МНИМ.LOG2 IMPOWER = МНИМ.СТЕПЕНЬ IMPRODUCT = МНИМ.ПРОИЗВЕД IMREAL = МНИМ.ВЕЩ IMSIN = МНИМ.SIN IMSQRT = МНИМ.КОРЕНЬ IMSUB = МНИМ.РАЗН IMSUM = МНИМ.СУММ OCT2BIN = ВОСЬМ.В.ДВ OCT2DEC = ВОСЬМ.В.ДЕС OCT2HEX = ВОСЬМ.В.ШЕСТН ## ## Финансовые функции (Financial Functions) ## ACCRINT = НАКОПДОХОД ACCRINTM = НАКОПДОХОДПОГАШ AMORDEGRC = АМОРУМ AMORLINC = АМОРУВ COUPDAYBS = ДНЕЙКУПОНДО COUPDAYS = ДНЕЙКУПОН COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ COUPNCD = ДАТАКУПОНПОСЛЕ COUPNUM = ЧИСЛКУПОН COUPPCD = ДАТАКУПОНДО CUMIPMT = ОБЩПЛАТ CUMPRINC = ОБЩДОХОД DB = ФУО DDB = ДДОБ DISC = СКИДКА DOLLARDE = РУБЛЬ.ДЕС DOLLARFR = РУБЛЬ.ДРОБЬ DURATION = ДЛИТ EFFECT = ЭФФЕКТ FV = БС FVSCHEDULE = БЗРАСПИС INTRATE = ИНОРМА IPMT = ПРПЛТ IRR = ВСД ISPMT = ПРОЦПЛАТ MDURATION = МДЛИТ MIRR = МВСД NOMINAL = НОМИНАЛ NPER = КПЕР NPV = ЧПС ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ODDFYIELD = ДОХОДПЕРВНЕРЕГ ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ODDLYIELD = ДОХОДПОСЛНЕРЕГ PMT = ПЛТ PPMT = ОСПЛТ PRICE = ЦЕНА PRICEDISC = ЦЕНАСКИДКА PRICEMAT = ЦЕНАПОГАШ PV = ПС RATE = СТАВКА RECEIVED = ПОЛУЧЕНО SLN = АПЛ SYD = АСЧ TBILLEQ = РАВНОКЧЕК TBILLPRICE = ЦЕНАКЧЕК TBILLYIELD = ДОХОДКЧЕК VDB = ПУО XIRR = ЧИСТВНДОХ XNPV = ЧИСТНЗ YIELD = ДОХОД YIELDDISC = ДОХОДСКИДКА YIELDMAT = ДОХОДПОГАШ ## ## Информационные функции (Information Functions) ## CELL = ЯЧЕЙКА ERROR.TYPE = ТИП.ОШИБКИ INFO = ИНФОРМ ISBLANK = ЕПУСТО ISERR = ЕОШ ISERROR = ЕОШИБКА ISEVEN = ЕЧЁТН ISLOGICAL = ЕЛОГИЧ ISNA = ЕНД ISNONTEXT = ЕНЕТЕКСТ ISNUMBER = ЕЧИСЛО ISODD = ЕНЕЧЁТ ISREF = ЕССЫЛКА ISTEXT = ЕТЕКСТ N = Ч NA = НД TYPE = ТИП ## ## Логические функции (Logical Functions) ## AND = И FALSE = ЛОЖЬ IF = ЕСЛИ IFERROR = ЕСЛИОШИБКА NOT = НЕ OR = ИЛИ TRUE = ИСТИНА ## ## Функции ссылки и поиска (Lookup & Reference Functions) ## ADDRESS = АДРЕС AREAS = ОБЛАСТИ CHOOSE = ВЫБОР COLUMN = СТОЛБЕЦ COLUMNS = ЧИСЛСТОЛБ GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ HLOOKUP = ГПР HYPERLINK = ГИПЕРССЫЛКА INDEX = ИНДЕКС INDIRECT = ДВССЫЛ LOOKUP = ПРОСМОТР MATCH = ПОИСКПОЗ OFFSET = СМЕЩ ROW = СТРОКА ROWS = ЧСТРОК RTD = ДРВ TRANSPOSE = ТРАНСП VLOOKUP = ВПР ## ## Математические и тригонометрические функции (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH COMBIN = ЧИСЛКОМБ COS = COS COSH = COSH DEGREES = ГРАДУСЫ EVEN = ЧЁТН EXP = EXP FACT = ФАКТР FACTDOUBLE = ДВФАКТР GCD = НОД INT = ЦЕЛОЕ LCM = НОК LN = LN LOG = LOG LOG10 = LOG10 MDETERM = МОПРЕД MINVERSE = МОБР MMULT = МУМНОЖ MOD = ОСТАТ MROUND = ОКРУГЛТ MULTINOMIAL = МУЛЬТИНОМ ODD = НЕЧЁТ PI = ПИ POWER = СТЕПЕНЬ PRODUCT = ПРОИЗВЕД QUOTIENT = ЧАСТНОЕ RADIANS = РАДИАНЫ RAND = СЛЧИС RANDBETWEEN = СЛУЧМЕЖДУ ROMAN = РИМСКОЕ ROUND = ОКРУГЛ ROUNDDOWN = ОКРУГЛВНИЗ ROUNDUP = ОКРУГЛВВЕРХ SERIESSUM = РЯД.СУММ SIGN = ЗНАК SIN = SIN SINH = SINH SQRT = КОРЕНЬ SQRTPI = КОРЕНЬПИ SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ SUM = СУММ SUMIF = СУММЕСЛИ SUMIFS = СУММЕСЛИМН SUMPRODUCT = СУММПРОИЗВ SUMSQ = СУММКВ SUMX2MY2 = СУММРАЗНКВ SUMX2PY2 = СУММСУММКВ SUMXMY2 = СУММКВРАЗН TAN = TAN TANH = TANH TRUNC = ОТБР ## ## Статистические функции (Statistical Functions) ## AVEDEV = СРОТКЛ AVERAGE = СРЗНАЧ AVERAGEA = СРЗНАЧА AVERAGEIF = СРЗНАЧЕСЛИ AVERAGEIFS = СРЗНАЧЕСЛИМН CORREL = КОРРЕЛ COUNT = СЧЁТ COUNTA = СЧЁТЗ COUNTBLANK = СЧИТАТЬПУСТОТЫ COUNTIF = СЧЁТЕСЛИ COUNTIFS = СЧЁТЕСЛИМН DEVSQ = КВАДРОТКЛ FISHER = ФИШЕР FISHERINV = ФИШЕРОБР FREQUENCY = ЧАСТОТА GAMMALN = ГАММАНЛОГ GEOMEAN = СРГЕОМ GROWTH = РОСТ HARMEAN = СРГАРМ INTERCEPT = ОТРЕЗОК KURT = ЭКСЦЕСС LARGE = НАИБОЛЬШИЙ LINEST = ЛИНЕЙН LOGEST = ЛГРФПРИБЛ MAX = МАКС MAXA = МАКСА MEDIAN = МЕДИАНА MIN = МИН MINA = МИНА PEARSON = ПИРСОН PERMUT = ПЕРЕСТ PROB = ВЕРОЯТНОСТЬ RSQ = КВПИРСОН SKEW = СКОС SLOPE = НАКЛОН SMALL = НАИМЕНЬШИЙ STANDARDIZE = НОРМАЛИЗАЦИЯ STDEVA = СТАНДОТКЛОНА STDEVPA = СТАНДОТКЛОНПА STEYX = СТОШYX TREND = ТЕНДЕНЦИЯ TRIMMEAN = УРЕЗСРЕДНЕЕ VARA = ДИСПА VARPA = ДИСПРА ## ## Текстовые функции (Text Functions) ## ASC = ASC BAHTTEXT = БАТТЕКСТ CHAR = СИМВОЛ CLEAN = ПЕЧСИМВ CODE = КОДСИМВ DOLLAR = РУБЛЬ EXACT = СОВПАД FIND = НАЙТИ FINDB = НАЙТИБ FIXED = ФИКСИРОВАННЫЙ LEFT = ЛЕВСИМВ LEFTB = ЛЕВБ LEN = ДЛСТР LENB = ДЛИНБ LOWER = СТРОЧН MID = ПСТР MIDB = ПСТРБ PHONETIC = PHONETIC PROPER = ПРОПНАЧ REPLACE = ЗАМЕНИТЬ REPLACEB = ЗАМЕНИТЬБ REPT = ПОВТОР RIGHT = ПРАВСИМВ RIGHTB = ПРАВБ SEARCH = ПОИСК SEARCHB = ПОИСКБ SUBSTITUTE = ПОДСТАВИТЬ T = Т TEXT = ТЕКСТ TRIM = СЖПРОБЕЛЫ UPPER = ПРОПИСН VALUE = ЗНАЧЕН ## ## (Web Functions) ## ## ## (Compatibility Functions) ## BETADIST = БЕТАРАСП BETAINV = БЕТАОБР BINOMDIST = БИНОМРАСП CEILING = ОКРВВЕРХ CHIDIST = ХИ2РАСП CHIINV = ХИ2ОБР CHITEST = ХИ2ТЕСТ CONCATENATE = СЦЕПИТЬ CONFIDENCE = ДОВЕРИТ COVAR = КОВАР CRITBINOM = КРИТБИНОМ EXPONDIST = ЭКСПРАСП FDIST = FРАСП FINV = FРАСПОБР FLOOR = ОКРВНИЗ FORECAST = ПРЕДСКАЗ FTEST = ФТЕСТ GAMMADIST = ГАММАРАСП GAMMAINV = ГАММАОБР HYPGEOMDIST = ГИПЕРГЕОМЕТ LOGINV = ЛОГНОРМОБР LOGNORMDIST = ЛОГНОРМРАСП MODE = МОДА NEGBINOMDIST = ОТРБИНОМРАСП NORMDIST = НОРМРАСП NORMINV = НОРМОБР NORMSDIST = НОРМСТРАСП NORMSINV = НОРМСТОБР PERCENTILE = ПЕРСЕНТИЛЬ PERCENTRANK = ПРОЦЕНТРАНГ POISSON = ПУАССОН QUARTILE = КВАРТИЛЬ RANK = РАНГ STDEV = СТАНДОТКЛОН STDEVP = СТАНДОТКЛОНП TDIST = СТЬЮДРАСП TINV = СТЬЮДРАСПОБР TTEST = ТТЕСТ VAR = ДИСП VARP = ДИСПР WEIBULL = ВЕЙБУЛЛ ZTEST = ZТЕСТ ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/cs/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Ceština (Czech) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 = #DĚLENÍ_NULOU! VALUE = #HODNOTA! REF = #ODKAZ! NAME = #NÁZEV? NUM = #ČÍSLO! NA = #NENÍ_K_DISPOZICI ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/cs/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Ceština (Czech) ## ############################################################ ## ## Funkce pro práci s datovými krychlemi (Cube Functions) ## CUBEKPIMEMBER = CUBEKPIMEMBER CUBEMEMBER = CUBEMEMBER CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY CUBERANKEDMEMBER = CUBERANKEDMEMBER CUBESET = CUBESET CUBESETCOUNT = CUBESETCOUNT CUBEVALUE = CUBEVALUE ## ## Funkce databáze (Database Functions) ## DAVERAGE = DPRŮMĚR DCOUNT = DPOČET DCOUNTA = DPOČET2 DGET = DZÍSKAT DMAX = DMAX DMIN = DMIN DPRODUCT = DSOUČIN DSTDEV = DSMODCH.VÝBĚR DSTDEVP = DSMODCH DSUM = DSUMA DVAR = DVAR.VÝBĚR DVARP = DVAR ## ## Funkce data a času (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATUMHODN DAY = DEN DAYS = DAYS DAYS360 = ROK360 EDATE = EDATE EOMONTH = EOMONTH HOUR = HODINA ISOWEEKNUM = ISOWEEKNUM MINUTE = MINUTA MONTH = MĚSÍC NETWORKDAYS = NETWORKDAYS NETWORKDAYS.INTL = NETWORKDAYS.INTL NOW = NYNÍ SECOND = SEKUNDA TIME = ČAS TIMEVALUE = ČASHODN TODAY = DNES WEEKDAY = DENTÝDNE WEEKNUM = WEEKNUM WORKDAY = WORKDAY WORKDAY.INTL = WORKDAY.INTL YEAR = ROK YEARFRAC = YEARFRAC ## ## Inženýrské funkce (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN2DEC BIN2HEX = BIN2HEX BIN2OCT = BIN2OCT BITAND = BITAND BITLSHIFT = BITLSHIFT BITOR = BITOR BITRSHIFT = BITRSHIFT BITXOR = BITXOR COMPLEX = COMPLEX CONVERT = CONVERT DEC2BIN = DEC2BIN DEC2HEX = DEC2HEX DEC2OCT = DEC2OCT DELTA = DELTA ERF = ERF ERF.PRECISE = ERF.PRECISE ERFC = ERFC ERFC.PRECISE = ERFC.PRECISE GESTEP = GESTEP HEX2BIN = HEX2BIN HEX2DEC = HEX2DEC HEX2OCT = HEX2OCT IMABS = IMABS IMAGINARY = IMAGINARY IMARGUMENT = IMARGUMENT IMCONJUGATE = IMCONJUGATE IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOWER IMPRODUCT = IMPRODUCT IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMSQRT IMSUB = IMSUB IMSUM = IMSUM IMTAN = IMTAN OCT2BIN = OCT2BIN OCT2DEC = OCT2DEC OCT2HEX = OCT2HEX ## ## Finanční funkce (Financial Functions) ## ACCRINT = ACCRINT ACCRINTM = ACCRINTM AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = COUPDAYBS COUPDAYS = COUPDAYS COUPDAYSNC = COUPDAYSNC COUPNCD = COUPNCD COUPNUM = COUPNUM COUPPCD = COUPPCD CUMIPMT = CUMIPMT CUMPRINC = CUMPRINC DB = ODPIS.ZRYCH DDB = ODPIS.ZRYCH2 DISC = DISC DOLLARDE = DOLLARDE DOLLARFR = DOLLARFR DURATION = DURATION EFFECT = EFFECT FV = BUDHODNOTA FVSCHEDULE = FVSCHEDULE INTRATE = INTRATE IPMT = PLATBA.ÚROK IRR = MÍRA.VÝNOSNOSTI ISPMT = ISPMT MDURATION = MDURATION MIRR = MOD.MÍRA.VÝNOSNOSTI NOMINAL = NOMINAL NPER = POČET.OBDOBÍ NPV = ČISTÁ.SOUČHODNOTA ODDFPRICE = ODDFPRICE ODDFYIELD = ODDFYIELD ODDLPRICE = ODDLPRICE ODDLYIELD = ODDLYIELD PDURATION = PDURATION PMT = PLATBA PPMT = PLATBA.ZÁKLAD PRICE = PRICE PRICEDISC = PRICEDISC PRICEMAT = PRICEMAT PV = SOUČHODNOTA RATE = ÚROKOVÁ.MÍRA RECEIVED = RECEIVED RRI = RRI SLN = ODPIS.LIN SYD = ODPIS.NELIN TBILLEQ = TBILLEQ TBILLPRICE = TBILLPRICE TBILLYIELD = TBILLYIELD VDB = ODPIS.ZA.INT XIRR = XIRR XNPV = XNPV YIELD = YIELD YIELDDISC = YIELDDISC YIELDMAT = YIELDMAT ## ## Informační funkce (Information Functions) ## CELL = POLÍČKO ERROR.TYPE = CHYBA.TYP INFO = O.PROSTŘEDÍ ISBLANK = JE.PRÁZDNÉ ISERR = JE.CHYBA ISERROR = JE.CHYBHODN ISEVEN = ISEVEN ISFORMULA = ISFORMULA ISLOGICAL = JE.LOGHODN ISNA = JE.NEDEF ISNONTEXT = JE.NETEXT ISNUMBER = JE.ČISLO ISODD = ISODD ISREF = JE.ODKAZ ISTEXT = JE.TEXT N = N NA = NEDEF SHEET = SHEET SHEETS = SHEETS TYPE = TYP ## ## Logické funkce (Logical Functions) ## AND = A FALSE = NEPRAVDA IF = KDYŽ IFERROR = IFERROR IFNA = IFNA IFS = IFS NOT = NE OR = NEBO SWITCH = SWITCH TRUE = PRAVDA XOR = XOR ## ## Vyhledávací funkce a funkce pro odkazy (Lookup & Reference Functions) ## ADDRESS = ODKAZ AREAS = POČET.BLOKŮ CHOOSE = ZVOLIT COLUMN = SLOUPEC COLUMNS = SLOUPCE FORMULATEXT = FORMULATEXT GETPIVOTDATA = ZÍSKATKONTDATA HLOOKUP = VVYHLEDAT HYPERLINK = HYPERTEXTOVÝ.ODKAZ INDEX = INDEX INDIRECT = NEPŘÍMÝ.ODKAZ LOOKUP = VYHLEDAT MATCH = POZVYHLEDAT OFFSET = POSUN ROW = ŘÁDEK ROWS = ŘÁDKY RTD = RTD TRANSPOSE = TRANSPOZICE VLOOKUP = SVYHLEDAT ## ## Matematické a trigonometrické funkce (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGGREGATE ARABIC = ARABIC ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTG ATAN2 = ARCTG2 ATANH = ARCTGH BASE = BASE CEILING.MATH = CEILING.MATH COMBIN = KOMBINACE COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = DEGREES EVEN = ZAOKROUHLIT.NA.SUDÉ EXP = EXP FACT = FAKTORIÁL FACTDOUBLE = FACTDOUBLE FLOOR.MATH = FLOOR.MATH GCD = GCD INT = CELÁ.ČÁST LCM = LCM LN = LN LOG = LOGZ LOG10 = LOG MDETERM = DETERMINANT MINVERSE = INVERZE MMULT = SOUČIN.MATIC MOD = MOD MROUND = MROUND MULTINOMIAL = MULTINOMIAL MUNIT = MUNIT ODD = ZAOKROUHLIT.NA.LICHÉ PI = PI POWER = POWER PRODUCT = SOUČIN QUOTIENT = QUOTIENT RADIANS = RADIANS RAND = NÁHČÍSLO RANDBETWEEN = RANDBETWEEN ROMAN = ROMAN ROUND = ZAOKROUHLIT ROUNDDOWN = ROUNDDOWN ROUNDUP = ROUNDUP SEC = SEC SECH = SECH SERIESSUM = SERIESSUM SIGN = SIGN SIN = SIN SINH = SINH SQRT = ODMOCNINA SQRTPI = SQRTPI SUBTOTAL = SUBTOTAL SUM = SUMA SUMIF = SUMIF SUMIFS = SUMIFS SUMPRODUCT = SOUČIN.SKALÁRNÍ SUMSQ = SUMA.ČTVERCŮ SUMX2MY2 = SUMX2MY2 SUMX2PY2 = SUMX2PY2 SUMXMY2 = SUMXMY2 TAN = TG TANH = TGH TRUNC = USEKNOUT ## ## Statistické funkce (Statistical Functions) ## AVEDEV = PRŮMODCHYLKA AVERAGE = PRŮMĚR AVERAGEA = AVERAGEA AVERAGEIF = AVERAGEIF AVERAGEIFS = AVERAGEIFS BETA.DIST = BETA.DIST BETA.INV = BETA.INV BINOM.DIST = BINOM.DIST BINOM.DIST.RANGE = BINOM.DIST.RANGE BINOM.INV = BINOM.INV CHISQ.DIST = CHISQ.DIST CHISQ.DIST.RT = CHISQ.DIST.RT CHISQ.INV = CHISQ.INV CHISQ.INV.RT = CHISQ.INV.RT CHISQ.TEST = CHISQ.TEST CONFIDENCE.NORM = CONFIDENCE.NORM CONFIDENCE.T = CONFIDENCE.T CORREL = CORREL COUNT = POČET COUNTA = POČET2 COUNTBLANK = COUNTBLANK COUNTIF = COUNTIF COUNTIFS = COUNTIFS COVARIANCE.P = COVARIANCE.P COVARIANCE.S = COVARIANCE.S DEVSQ = DEVSQ EXPON.DIST = EXPON.DIST F.DIST = F.DIST F.DIST.RT = F.DIST.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = FORECAST.ETS FORECAST.ETS.CONFINT = FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY = FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT = FORECAST.ETS.STAT FORECAST.LINEAR = FORECAST.LINEAR FREQUENCY = ČETNOSTI GAMMA = GAMMA GAMMA.DIST = GAMMA.DIST GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.PRECISE GAUSS = GAUSS GEOMEAN = GEOMEAN GROWTH = LOGLINTREND HARMEAN = HARMEAN HYPGEOM.DIST = HYPGEOM.DIST INTERCEPT = INTERCEPT KURT = KURT LARGE = LARGE LINEST = LINREGRESE LOGEST = LOGLINREGRESE LOGNORM.DIST = LOGNORM.DIST LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXIFS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINIFS MODE.MULT = MODE.MULT MODE.SNGL = MODE.SNGL NEGBINOM.DIST = NEGBINOM.DIST NORM.DIST = NORM.DIST NORM.INV = NORM.INV NORM.S.DIST = NORM.S.DIST NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = PERCENTRANK.EXC PERCENTRANK.INC = PERCENTRANK.INC PERMUT = PERMUTACE PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.DIST PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = RANK.AVG RANK.EQ = RANK.EQ RSQ = RKQ SKEW = SKEW SKEW.P = SKEW.P SLOPE = SLOPE SMALL = SMALL STANDARDIZE = STANDARDIZE STDEV.P = SMODCH.P STDEV.S = SMODCH.VÝBĚR.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STEYX T.DIST = T.DIST T.DIST.2T = T.DIST.2T T.DIST.RT = T.DIST.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = LINTREND TRIMMEAN = TRIMMEAN VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.DIST Z.TEST = Z.TEST ## ## Textové funkce (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = ZNAK CLEAN = VYČISTIT CODE = KÓD CONCAT = CONCAT DOLLAR = KČ EXACT = STEJNÉ FIND = NAJÍT FIXED = ZAOKROUHLIT.NA.TEXT LEFT = ZLEVA LEN = DÉLKA LOWER = MALÁ MID = ČÁST NUMBERVALUE = NUMBERVALUE PHONETIC = ZVUKOVÉ PROPER = VELKÁ2 REPLACE = NAHRADIT REPT = OPAKOVAT RIGHT = ZPRAVA SEARCH = HLEDAT SUBSTITUTE = DOSADIT T = T TEXT = HODNOTA.NA.TEXT TEXTJOIN = TEXTJOIN TRIM = PROČISTIT UNICHAR = UNICHAR UNICODE = UNICODE UPPER = VELKÁ VALUE = HODNOTA ## ## Webové funkce (Web Functions) ## ENCODEURL = ENCODEURL FILTERXML = FILTERXML WEBSERVICE = WEBSERVICE ## ## Funkce pro kompatibilitu (Compatibility Functions) ## BETADIST = BETADIST BETAINV = BETAINV BINOMDIST = BINOMDIST CEILING = ZAOKR.NAHORU CHIDIST = CHIDIST CHIINV = CHIINV CHITEST = CHITEST CONCATENATE = CONCATENATE CONFIDENCE = CONFIDENCE COVAR = COVAR CRITBINOM = CRITBINOM EXPONDIST = EXPONDIST FDIST = FDIST FINV = FINV FLOOR = ZAOKR.DOLŮ FORECAST = FORECAST FTEST = FTEST GAMMADIST = GAMMADIST GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMDIST LOGINV = LOGINV LOGNORMDIST = LOGNORMDIST MODE = MODE NEGBINOMDIST = NEGBINOMDIST NORMDIST = NORMDIST NORMINV = NORMINV NORMSDIST = NORMSDIST NORMSINV = NORMSINV PERCENTILE = PERCENTIL PERCENTRANK = PERCENTRANK POISSON = POISSON QUARTILE = QUARTIL RANK = RANK STDEV = SMODCH.VÝBĚR STDEVP = SMODCH TDIST = TDIST TINV = TINV TTEST = TTEST VAR = VAR.VÝBĚR VARP = VAR WEIBULL = WEIBULL ZTEST = ZTEST ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/da/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Dansk (Danish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NUL! DIV0 VALUE = #VÆRDI! REF = #REFERENCE! NAME = #NAVN? NUM NA = #I/T ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/da/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Dansk (Danish) ## ############################################################ ## ## Kubefunktioner (Cube Functions) ## CUBEKPIMEMBER = KUBE.KPI.MEDLEM CUBEMEMBER = KUBEMEDLEM CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB CUBERANKEDMEMBER = KUBERANGERET.MEDLEM CUBESET = KUBESÆT CUBESETCOUNT = KUBESÆT.ANTAL CUBEVALUE = KUBEVÆRDI ## ## Databasefunktioner (Database Functions) ## DAVERAGE = DMIDDEL DCOUNT = DTÆL DCOUNTA = DTÆLV DGET = DHENT DMAX = DMAKS DMIN = DMIN DPRODUCT = DPRODUKT DSTDEV = DSTDAFV DSTDEVP = DSTDAFVP DSUM = DSUM DVAR = DVARIANS DVARP = DVARIANSP ## ## Dato- og klokkeslætfunktioner (Date & Time Functions) ## DATE = DATO DATEDIF = DATO.FORSKEL DATESTRING = DATOSTRENG DATEVALUE = DATOVÆRDI DAY = DAG DAYS = DAGE DAYS360 = DAGE360 EDATE = EDATO EOMONTH = SLUT.PÅ.MÅNED HOUR = TIME ISOWEEKNUM = ISOUGE.NR MINUTE = MINUT MONTH = MÅNED NETWORKDAYS = ANTAL.ARBEJDSDAGE NETWORKDAYS.INTL = ANTAL.ARBEJDSDAGE.INTL NOW = NU SECOND = SEKUND THAIDAYOFWEEK = THAILANDSKUGEDAG THAIMONTHOFYEAR = THAILANDSKMÅNED THAIYEAR = THAILANDSKÅR TIME = TID TIMEVALUE = TIDSVÆRDI TODAY = IDAG WEEKDAY = UGEDAG WEEKNUM = UGE.NR WORKDAY = ARBEJDSDAG WORKDAY.INTL = ARBEJDSDAG.INTL YEAR = ÅR YEARFRAC = ÅR.BRØK ## ## Tekniske funktioner (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.TIL.DEC BIN2HEX = BIN.TIL.HEX BIN2OCT = BIN.TIL.OKT BITAND = BITOG BITLSHIFT = BITLSKIFT BITOR = BITELLER BITRSHIFT = BITRSKIFT BITXOR = BITXELLER COMPLEX = KOMPLEKS CONVERT = KONVERTER DEC2BIN = DEC.TIL.BIN DEC2HEX = DEC.TIL.HEX DEC2OCT = DEC.TIL.OKT DELTA = DELTA ERF = FEJLFUNK ERF.PRECISE = ERF.PRECISE ERFC = FEJLFUNK.KOMP ERFC.PRECISE = ERFC.PRECISE GESTEP = GETRIN HEX2BIN = HEX.TIL.BIN HEX2DEC = HEX.TIL.DEC HEX2OCT = HEX.TIL.OKT IMABS = IMAGABS IMAGINARY = IMAGINÆR IMARGUMENT = IMAGARGUMENT IMCONJUGATE = IMAGKONJUGERE IMCOS = IMAGCOS IMCOSH = IMAGCOSH IMCOT = IMAGCOT IMCSC = IMAGCSC IMCSCH = IMAGCSCH IMDIV = IMAGDIV IMEXP = IMAGEKSP IMLN = IMAGLN IMLOG10 = IMAGLOG10 IMLOG2 = IMAGLOG2 IMPOWER = IMAGPOTENS IMPRODUCT = IMAGPRODUKT IMREAL = IMAGREELT IMSEC = IMAGSEC IMSECH = IMAGSECH IMSIN = IMAGSIN IMSINH = IMAGSINH IMSQRT = IMAGKVROD IMSUB = IMAGSUB IMSUM = IMAGSUM IMTAN = IMAGTAN OCT2BIN = OKT.TIL.BIN OCT2DEC = OKT.TIL.DEC OCT2HEX = OKT.TIL.HEX ## ## Finansielle funktioner (Financial Functions) ## ACCRINT = PÅLØBRENTE ACCRINTM = PÅLØBRENTE.UDLØB AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KUPONDAGE.SA COUPDAYS = KUPONDAGE.A COUPDAYSNC = KUPONDAGE.ANK COUPNCD = KUPONDAG.NÆSTE COUPNUM = KUPONBETALINGER COUPPCD = KUPONDAG.FORRIGE CUMIPMT = AKKUM.RENTE CUMPRINC = AKKUM.HOVEDSTOL DB = DB DDB = DSA DISC = DISKONTO DOLLARDE = KR.DECIMAL DOLLARFR = KR.BRØK DURATION = VARIGHED EFFECT = EFFEKTIV.RENTE FV = FV FVSCHEDULE = FVTABEL INTRATE = RENTEFOD IPMT = R.YDELSE IRR = IA ISPMT = ISPMT MDURATION = MVARIGHED MIRR = MIA NOMINAL = NOMINEL NPER = NPER NPV = NUTIDSVÆRDI ODDFPRICE = ULIGE.KURS.PÅLYDENDE ODDFYIELD = ULIGE.FØRSTE.AFKAST ODDLPRICE = ULIGE.SIDSTE.KURS ODDLYIELD = ULIGE.SIDSTE.AFKAST PDURATION = PVARIGHED PMT = YDELSE PPMT = H.YDELSE PRICE = KURS PRICEDISC = KURS.DISKONTO PRICEMAT = KURS.UDLØB PV = NV RATE = RENTE RECEIVED = MODTAGET.VED.UDLØB RRI = RRI SLN = LA SYD = ÅRSAFSKRIVNING TBILLEQ = STATSOBLIGATION TBILLPRICE = STATSOBLIGATION.KURS TBILLYIELD = STATSOBLIGATION.AFKAST VDB = VSA XIRR = INTERN.RENTE XNPV = NETTO.NUTIDSVÆRDI YIELD = AFKAST YIELDDISC = AFKAST.DISKONTO YIELDMAT = AFKAST.UDLØBSDATO ## ## Informationsfunktioner (Information Functions) ## CELL = CELLE ERROR.TYPE = FEJLTYPE INFO = INFO ISBLANK = ER.TOM ISERR = ER.FJL ISERROR = ER.FEJL ISEVEN = ER.LIGE ISFORMULA = ER.FORMEL ISLOGICAL = ER.LOGISK ISNA = ER.IKKE.TILGÆNGELIG ISNONTEXT = ER.IKKE.TEKST ISNUMBER = ER.TAL ISODD = ER.ULIGE ISREF = ER.REFERENCE ISTEXT = ER.TEKST N = TAL NA = IKKE.TILGÆNGELIG SHEET = ARK SHEETS = ARK.FLERE TYPE = VÆRDITYPE ## ## Logiske funktioner (Logical Functions) ## AND = OG FALSE = FALSK IF = HVIS IFERROR = HVIS.FEJL IFNA = HVISIT IFS = HVISER NOT = IKKE OR = ELLER SWITCH = SKIFT TRUE = SAND XOR = XELLER ## ## Opslags- og referencefunktioner (Lookup & Reference Functions) ## ADDRESS = ADRESSE AREAS = OMRÅDER CHOOSE = VÆLG COLUMN = KOLONNE COLUMNS = KOLONNER FORMULATEXT = FORMELTEKST GETPIVOTDATA = GETPIVOTDATA HLOOKUP = VOPSLAG HYPERLINK = HYPERLINK INDEX = INDEKS INDIRECT = INDIREKTE LOOKUP = SLÅ.OP MATCH = SAMMENLIGN OFFSET = FORSKYDNING ROW = RÆKKE ROWS = RÆKKER RTD = RTD TRANSPOSE = TRANSPONER VLOOKUP = LOPSLAG *RC = RK ## ## Matematiske og trigonometriske funktioner (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = SAMLING ARABIC = ARABISK ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ARCTANH BASE = BASIS CEILING.MATH = LOFT.MAT CEILING.PRECISE = LOFT.PRECISE COMBIN = KOMBIN COMBINA = KOMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRADER ECMA.CEILING = ECMA.LOFT EVEN = LIGE EXP = EKSP FACT = FAKULTET FACTDOUBLE = DOBBELT.FAKULTET FLOOR.MATH = AFRUND.BUND.MAT FLOOR.PRECISE = AFRUND.GULV.PRECISE GCD = STØRSTE.FÆLLES.DIVISOR INT = HELTAL ISO.CEILING = ISO.LOFT LCM = MINDSTE.FÆLLES.MULTIPLUM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERT MMULT = MPRODUKT MOD = REST MROUND = MAFRUND MULTINOMIAL = MULTINOMIAL MUNIT = MENHED ODD = ULIGE PI = PI POWER = POTENS PRODUCT = PRODUKT QUOTIENT = KVOTIENT RADIANS = RADIANER RAND = SLUMP RANDBETWEEN = SLUMPMELLEM ROMAN = ROMERTAL ROUND = AFRUND ROUNDBAHTDOWN = RUNDBAHTNED ROUNDBAHTUP = RUNDBAHTOP ROUNDDOWN = RUND.NED ROUNDUP = RUND.OP SEC = SEC SECH = SECH SERIESSUM = SERIESUM SIGN = FORTEGN SIN = SIN SINH = SINH SQRT = KVROD SQRTPI = KVRODPI SUBTOTAL = SUBTOTAL SUM = SUM SUMIF = SUM.HVIS SUMIFS = SUM.HVISER SUMPRODUCT = SUMPRODUKT SUMSQ = SUMKV SUMX2MY2 = SUMX2MY2 SUMX2PY2 = SUMX2PY2 SUMXMY2 = SUMXMY2 TAN = TAN TANH = TANH TRUNC = AFKORT ## ## Statistiske funktioner (Statistical Functions) ## AVEDEV = MAD AVERAGE = MIDDEL AVERAGEA = MIDDELV AVERAGEIF = MIDDEL.HVIS AVERAGEIFS = MIDDEL.HVISER BETA.DIST = BETA.FORDELING BETA.INV = BETA.INV BINOM.DIST = BINOMIAL.FORDELING BINOM.DIST.RANGE = BINOMIAL.DIST.INTERVAL BINOM.INV = BINOMIAL.INV CHISQ.DIST = CHI2.FORDELING CHISQ.DIST.RT = CHI2.FORD.RT CHISQ.INV = CHI2.INV CHISQ.INV.RT = CHI2.INV.RT CHISQ.TEST = CHI2.TEST CONFIDENCE.NORM = KONFIDENS.NORM CONFIDENCE.T = KONFIDENST CORREL = KORRELATION COUNT = TÆL COUNTA = TÆLV COUNTBLANK = ANTAL.BLANKE COUNTIF = TÆL.HVIS COUNTIFS = TÆL.HVISER COVARIANCE.P = KOVARIANS.P COVARIANCE.S = KOVARIANS.S DEVSQ = SAK EXPON.DIST = EKSP.FORDELING F.DIST = F.FORDELING F.DIST.RT = F.FORDELING.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PROGNOSE.ETS FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SÆSONUDSVING FORECAST.ETS.STAT = PROGNOSE.ETS.STAT FORECAST.LINEAR = PROGNOSE.LINEÆR FREQUENCY = FREKVENS GAMMA = GAMMA GAMMA.DIST = GAMMA.FORDELING GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.PRECISE GAUSS = GAUSS GEOMEAN = GEOMIDDELVÆRDI GROWTH = FORØGELSE HARMEAN = HARMIDDELVÆRDI HYPGEOM.DIST = HYPGEO.FORDELING INTERCEPT = SKÆRING KURT = TOPSTEJL LARGE = STØRSTE LINEST = LINREGR LOGEST = LOGREGR LOGNORM.DIST = LOGNORM.FORDELING LOGNORM.INV = LOGNORM.INV MAX = MAKS MAXA = MAKSV MAXIFS = MAKSHVISER MEDIAN = MEDIAN MIN = MIN MINA = MINV MINIFS = MINHVISER MODE.MULT = HYPPIGST.FLERE MODE.SNGL = HYPPIGST.ENKELT NEGBINOM.DIST = NEGBINOM.FORDELING NORM.DIST = NORMAL.FORDELING NORM.INV = NORM.INV NORM.S.DIST = STANDARD.NORM.FORDELING NORM.S.INV = STANDARD.NORM.INV PEARSON = PEARSON PERCENTILE.EXC = FRAKTIL.UDELAD PERCENTILE.INC = FRAKTIL.MEDTAG PERCENTRANK.EXC = PROCENTPLADS.UDELAD PERCENTRANK.INC = PROCENTPLADS.MEDTAG PERMUT = PERMUT PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.FORDELING PROB = SANDSYNLIGHED QUARTILE.EXC = KVARTIL.UDELAD QUARTILE.INC = KVARTIL.MEDTAG RANK.AVG = PLADS.GNSN RANK.EQ = PLADS.LIGE RSQ = FORKLARINGSGRAD SKEW = SKÆVHED SKEW.P = SKÆVHED.P SLOPE = STIGNING SMALL = MINDSTE STANDARDIZE = STANDARDISER STDEV.P = STDAFV.P STDEV.S = STDAFV.S STDEVA = STDAFVV STDEVPA = STDAFVPV STEYX = STFYX T.DIST = T.FORDELING T.DIST.2T = T.FORDELING.2T T.DIST.RT = T.FORDELING.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = TENDENS TRIMMEAN = TRIMMIDDELVÆRDI VAR.P = VARIANS.P VAR.S = VARIANS.S VARA = VARIANSV VARPA = VARIANSPV WEIBULL.DIST = WEIBULL.FORDELING Z.TEST = Z.TEST ## ## Tekstfunktioner (Text Functions) ## BAHTTEXT = BAHTTEKST CHAR = TEGN CLEAN = RENS CODE = KODE CONCAT = CONCAT DOLLAR = KR EXACT = EKSAKT FIND = FIND FIXED = FAST ISTHAIDIGIT = ERTHAILANDSKCIFFER LEFT = VENSTRE LEN = LÆNGDE LOWER = SMÅ.BOGSTAVER MID = MIDT NUMBERSTRING = TALSTRENG NUMBERVALUE = TALVÆRDI PHONETIC = FONETISK PROPER = STORT.FORBOGSTAV REPLACE = ERSTAT REPT = GENTAG RIGHT = HØJRE SEARCH = SØG SUBSTITUTE = UDSKIFT T = T TEXT = TEKST TEXTJOIN = TEKST.KOMBINER THAIDIGIT = THAILANDSKCIFFER THAINUMSOUND = THAILANDSKNUMLYD THAINUMSTRING = THAILANDSKNUMSTRENG THAISTRINGLENGTH = THAILANDSKSTRENGLÆNGDE TRIM = FJERN.OVERFLØDIGE.BLANKE UNICHAR = UNICHAR UNICODE = UNICODE UPPER = STORE.BOGSTAVER VALUE = VÆRDI ## ## Webfunktioner (Web Functions) ## ENCODEURL = KODNINGSURL FILTERXML = FILTRERXML WEBSERVICE = WEBTJENESTE ## ## Kompatibilitetsfunktioner (Compatibility Functions) ## BETADIST = BETAFORDELING BETAINV = BETAINV BINOMDIST = BINOMIALFORDELING CEILING = AFRUND.LOFT CHIDIST = CHIFORDELING CHIINV = CHIINV CHITEST = CHITEST CONCATENATE = SAMMENKÆDNING CONFIDENCE = KONFIDENSINTERVAL COVAR = KOVARIANS CRITBINOM = KRITBINOM EXPONDIST = EKSPFORDELING FDIST = FFORDELING FINV = FINV FLOOR = AFRUND.GULV FORECAST = PROGNOSE FTEST = FTEST GAMMADIST = GAMMAFORDELING GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOFORDELING LOGINV = LOGINV LOGNORMDIST = LOGNORMFORDELING MODE = HYPPIGST NEGBINOMDIST = NEGBINOMFORDELING NORMDIST = NORMFORDELING NORMINV = NORMINV NORMSDIST = STANDARDNORMFORDELING NORMSINV = STANDARDNORMINV PERCENTILE = FRAKTIL PERCENTRANK = PROCENTPLADS POISSON = POISSON QUARTILE = KVARTIL RANK = PLADS STDEV = STDAFV STDEVP = STDAFVP TDIST = TFORDELING TINV = TINV TTEST = TTEST VAR = VARIANS VARP = VARIANSP WEIBULL = WEIBULL ZTEST = ZTEST ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/de/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Deutsch (German) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #WERT! REF = #BEZUG! NAME NUM = #ZAHL! NA = #NV ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/de/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Deutsch (German) ## ############################################################ ## ## Cubefunktionen (Cube Functions) ## CUBEKPIMEMBER = CUBEKPIELEMENT CUBEMEMBER = CUBEELEMENT CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT CUBERANKEDMEMBER = CUBERANGELEMENT CUBESET = CUBEMENGE CUBESETCOUNT = CUBEMENGENANZAHL CUBEVALUE = CUBEWERT ## ## Datenbankfunktionen (Database Functions) ## DAVERAGE = DBMITTELWERT DCOUNT = DBANZAHL DCOUNTA = DBANZAHL2 DGET = DBAUSZUG DMAX = DBMAX DMIN = DBMIN DPRODUCT = DBPRODUKT DSTDEV = DBSTDABW DSTDEVP = DBSTDABWN DSUM = DBSUMME DVAR = DBVARIANZ DVARP = DBVARIANZEN ## ## Datums- und Uhrzeitfunktionen (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATWERT DAY = TAG DAYS = TAGE DAYS360 = TAGE360 EDATE = EDATUM EOMONTH = MONATSENDE HOUR = STUNDE ISOWEEKNUM = ISOKALENDERWOCHE MINUTE = MINUTE MONTH = MONAT NETWORKDAYS = NETTOARBEITSTAGE NETWORKDAYS.INTL = NETTOARBEITSTAGE.INTL NOW = JETZT SECOND = SEKUNDE THAIDAYOFWEEK = THAIWOCHENTAG THAIMONTHOFYEAR = THAIMONATDESJAHRES THAIYEAR = THAIJAHR TIME = ZEIT TIMEVALUE = ZEITWERT TODAY = HEUTE WEEKDAY = WOCHENTAG WEEKNUM = KALENDERWOCHE WORKDAY = ARBEITSTAG WORKDAY.INTL = ARBEITSTAG.INTL YEAR = JAHR YEARFRAC = BRTEILJAHRE ## ## Technische Funktionen (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BININDEZ BIN2HEX = BININHEX BIN2OCT = BININOKT BITAND = BITUND BITLSHIFT = BITLVERSCHIEB BITOR = BITODER BITRSHIFT = BITRVERSCHIEB BITXOR = BITXODER COMPLEX = KOMPLEXE CONVERT = UMWANDELN DEC2BIN = DEZINBIN DEC2HEX = DEZINHEX DEC2OCT = DEZINOKT DELTA = DELTA ERF = GAUSSFEHLER ERF.PRECISE = GAUSSF.GENAU ERFC = GAUSSFKOMPL ERFC.PRECISE = GAUSSFKOMPL.GENAU GESTEP = GGANZZAHL HEX2BIN = HEXINBIN HEX2DEC = HEXINDEZ HEX2OCT = HEXINOKT IMABS = IMABS IMAGINARY = IMAGINÄRTEIL IMARGUMENT = IMARGUMENT IMCONJUGATE = IMKONJUGIERTE IMCOS = IMCOS IMCOSH = IMCOSHYP IMCOT = IMCOT IMCSC = IMCOSEC IMCSCH = IMCOSECHYP IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMAPOTENZ IMPRODUCT = IMPRODUKT IMREAL = IMREALTEIL IMSEC = IMSEC IMSECH = IMSECHYP IMSIN = IMSIN IMSINH = IMSINHYP IMSQRT = IMWURZEL IMSUB = IMSUB IMSUM = IMSUMME IMTAN = IMTAN OCT2BIN = OKTINBIN OCT2DEC = OKTINDEZ OCT2HEX = OKTINHEX ## ## Finanzmathematische Funktionen (Financial Functions) ## ACCRINT = AUFGELZINS ACCRINTM = AUFGELZINSF AMORDEGRC = AMORDEGRK AMORLINC = AMORLINEARK COUPDAYBS = ZINSTERMTAGVA COUPDAYS = ZINSTERMTAGE COUPDAYSNC = ZINSTERMTAGNZ COUPNCD = ZINSTERMNZ COUPNUM = ZINSTERMZAHL COUPPCD = ZINSTERMVZ CUMIPMT = KUMZINSZ CUMPRINC = KUMKAPITAL DB = GDA2 DDB = GDA DISC = DISAGIO DOLLARDE = NOTIERUNGDEZ DOLLARFR = NOTIERUNGBRU DURATION = DURATION EFFECT = EFFEKTIV FV = ZW FVSCHEDULE = ZW2 INTRATE = ZINSSATZ IPMT = ZINSZ IRR = IKV ISPMT = ISPMT MDURATION = MDURATION MIRR = QIKV NOMINAL = NOMINAL NPER = ZZR NPV = NBW ODDFPRICE = UNREGER.KURS ODDFYIELD = UNREGER.REND ODDLPRICE = UNREGLE.KURS ODDLYIELD = UNREGLE.REND PDURATION = PDURATION PMT = RMZ PPMT = KAPZ PRICE = KURS PRICEDISC = KURSDISAGIO PRICEMAT = KURSFÄLLIG PV = BW RATE = ZINS RECEIVED = AUSZAHLUNG RRI = ZSATZINVEST SLN = LIA SYD = DIA TBILLEQ = TBILLÄQUIV TBILLPRICE = TBILLKURS TBILLYIELD = TBILLRENDITE VDB = VDB XIRR = XINTZINSFUSS XNPV = XKAPITALWERT YIELD = RENDITE YIELDDISC = RENDITEDIS YIELDMAT = RENDITEFÄLL ## ## Informationsfunktionen (Information Functions) ## CELL = ZELLE ERROR.TYPE = FEHLER.TYP INFO = INFO ISBLANK = ISTLEER ISERR = ISTFEHL ISERROR = ISTFEHLER ISEVEN = ISTGERADE ISFORMULA = ISTFORMEL ISLOGICAL = ISTLOG ISNA = ISTNV ISNONTEXT = ISTKTEXT ISNUMBER = ISTZAHL ISODD = ISTUNGERADE ISREF = ISTBEZUG ISTEXT = ISTTEXT N = N NA = NV SHEET = BLATT SHEETS = BLÄTTER TYPE = TYP ## ## Logische Funktionen (Logical Functions) ## AND = UND FALSE = FALSCH IF = WENN IFERROR = WENNFEHLER IFNA = WENNNV IFS = WENNS NOT = NICHT OR = ODER SWITCH = ERSTERWERT TRUE = WAHR XOR = XODER ## ## Nachschlage- und Verweisfunktionen (Lookup & Reference Functions) ## ADDRESS = ADRESSE AREAS = BEREICHE CHOOSE = WAHL COLUMN = SPALTE COLUMNS = SPALTEN FORMULATEXT = FORMELTEXT GETPIVOTDATA = PIVOTDATENZUORDNEN HLOOKUP = WVERWEIS HYPERLINK = HYPERLINK INDEX = INDEX INDIRECT = INDIREKT LOOKUP = VERWEIS MATCH = VERGLEICH OFFSET = BEREICH.VERSCHIEBEN ROW = ZEILE ROWS = ZEILEN RTD = RTD TRANSPOSE = MTRANS VLOOKUP = SVERWEIS *RC = ZS ## ## Mathematische und trigonometrische Funktionen (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSHYP ACOT = ARCCOT ACOTH = ARCCOTHYP AGGREGATE = AGGREGAT ARABIC = ARABISCH ASIN = ARCSIN ASINH = ARCSINHYP ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ARCTANHYP BASE = BASIS CEILING.MATH = OBERGRENZE.MATHEMATIK CEILING.PRECISE = OBERGRENZE.GENAU COMBIN = KOMBINATIONEN COMBINA = KOMBINATIONEN2 COS = COS COSH = COSHYP COT = COT COTH = COTHYP CSC = COSEC CSCH = COSECHYP DECIMAL = DEZIMAL DEGREES = GRAD ECMA.CEILING = ECMA.OBERGRENZE EVEN = GERADE EXP = EXP FACT = FAKULTÄT FACTDOUBLE = ZWEIFAKULTÄT FLOOR.MATH = UNTERGRENZE.MATHEMATIK FLOOR.PRECISE = UNTERGRENZE.GENAU GCD = GGT INT = GANZZAHL ISO.CEILING = ISO.OBERGRENZE LCM = KGV LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDET MINVERSE = MINV MMULT = MMULT MOD = REST MROUND = VRUNDEN MULTINOMIAL = POLYNOMIAL MUNIT = MEINHEIT ODD = UNGERADE PI = PI POWER = POTENZ PRODUCT = PRODUKT QUOTIENT = QUOTIENT RADIANS = BOGENMASS RAND = ZUFALLSZAHL RANDBETWEEN = ZUFALLSBEREICH ROMAN = RÖMISCH ROUND = RUNDEN ROUNDBAHTDOWN = RUNDBAHTNED ROUNDBAHTUP = BAHTAUFRUNDEN ROUNDDOWN = ABRUNDEN ROUNDUP = AUFRUNDEN SEC = SEC SECH = SECHYP SERIESSUM = POTENZREIHE SIGN = VORZEICHEN SIN = SIN SINH = SINHYP SQRT = WURZEL SQRTPI = WURZELPI SUBTOTAL = TEILERGEBNIS SUM = SUMME SUMIF = SUMMEWENN SUMIFS = SUMMEWENNS SUMPRODUCT = SUMMENPRODUKT SUMSQ = QUADRATESUMME SUMX2MY2 = SUMMEX2MY2 SUMX2PY2 = SUMMEX2PY2 SUMXMY2 = SUMMEXMY2 TAN = TAN TANH = TANHYP TRUNC = KÜRZEN ## ## Statistische Funktionen (Statistical Functions) ## AVEDEV = MITTELABW AVERAGE = MITTELWERT AVERAGEA = MITTELWERTA AVERAGEIF = MITTELWERTWENN AVERAGEIFS = MITTELWERTWENNS BETA.DIST = BETA.VERT BETA.INV = BETA.INV BINOM.DIST = BINOM.VERT BINOM.DIST.RANGE = BINOM.VERT.BEREICH BINOM.INV = BINOM.INV CHISQ.DIST = CHIQU.VERT CHISQ.DIST.RT = CHIQU.VERT.RE CHISQ.INV = CHIQU.INV CHISQ.INV.RT = CHIQU.INV.RE CHISQ.TEST = CHIQU.TEST CONFIDENCE.NORM = KONFIDENZ.NORM CONFIDENCE.T = KONFIDENZ.T CORREL = KORREL COUNT = ANZAHL COUNTA = ANZAHL2 COUNTBLANK = ANZAHLLEEREZELLEN COUNTIF = ZÄHLENWENN COUNTIFS = ZÄHLENWENNS COVARIANCE.P = KOVARIANZ.P COVARIANCE.S = KOVARIANZ.S DEVSQ = SUMQUADABW EXPON.DIST = EXPON.VERT F.DIST = F.VERT F.DIST.RT = F.VERT.RE F.INV = F.INV F.INV.RT = F.INV.RE F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PROGNOSE.ETS FORECAST.ETS.CONFINT = PROGNOSE.ETS.KONFINT FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SAISONALITÄT FORECAST.ETS.STAT = PROGNOSE.ETS.STAT FORECAST.LINEAR = PROGNOSE.LINEAR FREQUENCY = HÄUFIGKEIT GAMMA = GAMMA GAMMA.DIST = GAMMA.VERT GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.GENAU GAUSS = GAUSS GEOMEAN = GEOMITTEL GROWTH = VARIATION HARMEAN = HARMITTEL HYPGEOM.DIST = HYPGEOM.VERT INTERCEPT = ACHSENABSCHNITT KURT = KURT LARGE = KGRÖSSTE LINEST = RGP LOGEST = RKP LOGNORM.DIST = LOGNORM.VERT LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXWENNS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINWENNS MODE.MULT = MODUS.VIELF MODE.SNGL = MODUS.EINF NEGBINOM.DIST = NEGBINOM.VERT NORM.DIST = NORM.VERT NORM.INV = NORM.INV NORM.S.DIST = NORM.S.VERT NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = QUANTIL.EXKL PERCENTILE.INC = QUANTIL.INKL PERCENTRANK.EXC = QUANTILSRANG.EXKL PERCENTRANK.INC = QUANTILSRANG.INKL PERMUT = VARIATIONEN PERMUTATIONA = VARIATIONEN2 PHI = PHI POISSON.DIST = POISSON.VERT PROB = WAHRSCHBEREICH QUARTILE.EXC = QUARTILE.EXKL QUARTILE.INC = QUARTILE.INKL RANK.AVG = RANG.MITTELW RANK.EQ = RANG.GLEICH RSQ = BESTIMMTHEITSMASS SKEW = SCHIEFE SKEW.P = SCHIEFE.P SLOPE = STEIGUNG SMALL = KKLEINSTE STANDARDIZE = STANDARDISIERUNG STDEV.P = STABW.N STDEV.S = STABW.S STDEVA = STABWA STDEVPA = STABWNA STEYX = STFEHLERYX T.DIST = T.VERT T.DIST.2T = T.VERT.2S T.DIST.RT = T.VERT.RE T.INV = T.INV T.INV.2T = T.INV.2S T.TEST = T.TEST TREND = TREND TRIMMEAN = GESTUTZTMITTEL VAR.P = VAR.P VAR.S = VAR.S VARA = VARIANZA VARPA = VARIANZENA WEIBULL.DIST = WEIBULL.VERT Z.TEST = G.TEST ## ## Textfunktionen (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = ZEICHEN CLEAN = SÄUBERN CODE = CODE CONCAT = TEXTKETTE DOLLAR = DM EXACT = IDENTISCH FIND = FINDEN FIXED = FEST ISTHAIDIGIT = ISTTHAIZAHLENWORT LEFT = LINKS LEN = LÄNGE LOWER = KLEIN MID = TEIL NUMBERVALUE = ZAHLENWERT PROPER = GROSS2 REPLACE = ERSETZEN REPT = WIEDERHOLEN RIGHT = RECHTS SEARCH = SUCHEN SUBSTITUTE = WECHSELN T = T TEXT = TEXT TEXTJOIN = TEXTVERKETTEN THAIDIGIT = THAIZAHLENWORT THAINUMSOUND = THAIZAHLSOUND THAINUMSTRING = THAILANDSKNUMSTRENG THAISTRINGLENGTH = THAIZEICHENFOLGENLÄNGE TRIM = GLÄTTEN UNICHAR = UNIZEICHEN UNICODE = UNICODE UPPER = GROSS VALUE = WERT ## ## Webfunktionen (Web Functions) ## ENCODEURL = URLCODIEREN FILTERXML = XMLFILTERN WEBSERVICE = WEBDIENST ## ## Kompatibilitätsfunktionen (Compatibility Functions) ## BETADIST = BETAVERT BETAINV = BETAINV BINOMDIST = BINOMVERT CEILING = OBERGRENZE CHIDIST = CHIVERT CHIINV = CHIINV CHITEST = CHITEST CONCATENATE = VERKETTEN CONFIDENCE = KONFIDENZ COVAR = KOVAR CRITBINOM = KRITBINOM EXPONDIST = EXPONVERT FDIST = FVERT FINV = FINV FLOOR = UNTERGRENZE FORECAST = SCHÄTZER FTEST = FTEST GAMMADIST = GAMMAVERT GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMVERT LOGINV = LOGINV LOGNORMDIST = LOGNORMVERT MODE = MODALWERT NEGBINOMDIST = NEGBINOMVERT NORMDIST = NORMVERT NORMINV = NORMINV NORMSDIST = STANDNORMVERT NORMSINV = STANDNORMINV PERCENTILE = QUANTIL PERCENTRANK = QUANTILSRANG POISSON = POISSON QUARTILE = QUARTILE RANK = RANG STDEV = STABW STDEVP = STABWN TDIST = TVERT TINV = TINV TTEST = TTEST VAR = VARIANZ VARP = VARIANZEN WEIBULL = WEIBULL ZTEST = GTEST ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/en/uk/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## English-UK (English-UK) ## ############################################################ ArgumentSeparator = , ## ## (For future use) ## currencySymbol = £ ## ## Error Codes ## NULL DIV0 VALUE REF NAME NUM NA ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/es/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Español (Spanish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #¡NULO! DIV0 = #¡DIV/0! VALUE = #¡VALOR! REF = #¡REF! NAME = #¿NOMBRE? NUM = #¡NUM! NA ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/es/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Español (Spanish) ## ############################################################ ## ## Funciones de cubo (Cube Functions) ## CUBEKPIMEMBER = MIEMBROKPICUBO CUBEMEMBER = MIEMBROCUBO CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO CUBERANKEDMEMBER = MIEMBRORANGOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = RECUENTOCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funciones de base de datos (Database Functions) ## DAVERAGE = BDPROMEDIO DCOUNT = BDCONTAR DCOUNTA = BDCONTARA DGET = BDEXTRAER DMAX = BDMAX DMIN = BDMIN DPRODUCT = BDPRODUCTO DSTDEV = BDDESVEST DSTDEVP = BDDESVESTP DSUM = BDSUMA DVAR = BDVAR DVARP = BDVARP ## ## Funciones de fecha y hora (Date & Time Functions) ## DATE = FECHA DATEDIF = SIFECHA DATESTRING = CADENA.FECHA DATEVALUE = FECHANUMERO DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = FECHA.MES EOMONTH = FIN.MES HOUR = HORA ISOWEEKNUM = ISO.NUM.DE.SEMANA MINUTE = MINUTO MONTH = MES NETWORKDAYS = DIAS.LAB NETWORKDAYS.INTL = DIAS.LAB.INTL NOW = AHORA SECOND = SEGUNDO THAIDAYOFWEEK = DIASEMTAI THAIMONTHOFYEAR = MESAÑOTAI THAIYEAR = AÑOTAI TIME = NSHORA TIMEVALUE = HORANUMERO TODAY = HOY WEEKDAY = DIASEM WEEKNUM = NUM.DE.SEMANA WORKDAY = DIA.LAB WORKDAY.INTL = DIA.LAB.INTL YEAR = AÑO YEARFRAC = FRAC.AÑO ## ## Funciones de ingeniería (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.A.DEC BIN2HEX = BIN.A.HEX BIN2OCT = BIN.A.OCT BITAND = BIT.Y BITLSHIFT = BIT.DESPLIZQDA BITOR = BIT.O BITRSHIFT = BIT.DESPLDCHA BITXOR = BIT.XO COMPLEX = COMPLEJO CONVERT = CONVERTIR DEC2BIN = DEC.A.BIN DEC2HEX = DEC.A.HEX DEC2OCT = DEC.A.OCT DELTA = DELTA ERF = FUN.ERROR ERF.PRECISE = FUN.ERROR.EXACTO ERFC = FUN.ERROR.COMPL ERFC.PRECISE = FUN.ERROR.COMPL.EXACTO GESTEP = MAYOR.O.IGUAL HEX2BIN = HEX.A.BIN HEX2DEC = HEX.A.DEC HEX2OCT = HEX.A.OCT IMABS = IM.ABS IMAGINARY = IMAGINARIO IMARGUMENT = IM.ANGULO IMCONJUGATE = IM.CONJUGADA IMCOS = IM.COS IMCOSH = IM.COSH IMCOT = IM.COT IMCSC = IM.CSC IMCSCH = IM.CSCH IMDIV = IM.DIV IMEXP = IM.EXP IMLN = IM.LN IMLOG10 = IM.LOG10 IMLOG2 = IM.LOG2 IMPOWER = IM.POT IMPRODUCT = IM.PRODUCT IMREAL = IM.REAL IMSEC = IM.SEC IMSECH = IM.SECH IMSIN = IM.SENO IMSINH = IM.SENOH IMSQRT = IM.RAIZ2 IMSUB = IM.SUSTR IMSUM = IM.SUM IMTAN = IM.TAN OCT2BIN = OCT.A.BIN OCT2DEC = OCT.A.DEC OCT2HEX = OCT.A.HEX ## ## Funciones financieras (Financial Functions) ## ACCRINT = INT.ACUM ACCRINTM = INT.ACUM.V AMORDEGRC = AMORTIZ.PROGRE AMORLINC = AMORTIZ.LIN COUPDAYBS = CUPON.DIAS.L1 COUPDAYS = CUPON.DIAS COUPDAYSNC = CUPON.DIAS.L2 COUPNCD = CUPON.FECHA.L2 COUPNUM = CUPON.NUM COUPPCD = CUPON.FECHA.L1 CUMIPMT = PAGO.INT.ENTRE CUMPRINC = PAGO.PRINC.ENTRE DB = DB DDB = DDB DISC = TASA.DESC DOLLARDE = MONEDA.DEC DOLLARFR = MONEDA.FRAC DURATION = DURACION EFFECT = INT.EFECTIVO FV = VF FVSCHEDULE = VF.PLAN INTRATE = TASA.INT IPMT = PAGOINT IRR = TIR ISPMT = INT.PAGO.DIR MDURATION = DURACION.MODIF MIRR = TIRM NOMINAL = TASA.NOMINAL NPER = NPER NPV = VNA ODDFPRICE = PRECIO.PER.IRREGULAR.1 ODDFYIELD = RENDTO.PER.IRREGULAR.1 ODDLPRICE = PRECIO.PER.IRREGULAR.2 ODDLYIELD = RENDTO.PER.IRREGULAR.2 PDURATION = P.DURACION PMT = PAGO PPMT = PAGOPRIN PRICE = PRECIO PRICEDISC = PRECIO.DESCUENTO PRICEMAT = PRECIO.VENCIMIENTO PV = VA RATE = TASA RECEIVED = CANTIDAD.RECIBIDA RRI = RRI SLN = SLN SYD = SYD TBILLEQ = LETRA.DE.TEST.EQV.A.BONO TBILLPRICE = LETRA.DE.TES.PRECIO TBILLYIELD = LETRA.DE.TES.RENDTO VDB = DVS XIRR = TIR.NO.PER XNPV = VNA.NO.PER YIELD = RENDTO YIELDDISC = RENDTO.DESC YIELDMAT = RENDTO.VENCTO ## ## Funciones de información (Information Functions) ## CELL = CELDA ERROR.TYPE = TIPO.DE.ERROR INFO = INFO ISBLANK = ESBLANCO ISERR = ESERR ISERROR = ESERROR ISEVEN = ES.PAR ISFORMULA = ESFORMULA ISLOGICAL = ESLOGICO ISNA = ESNOD ISNONTEXT = ESNOTEXTO ISNUMBER = ESNUMERO ISODD = ES.IMPAR ISREF = ESREF ISTEXT = ESTEXTO N = N NA = NOD SHEET = HOJA SHEETS = HOJAS TYPE = TIPO ## ## Funciones lógicas (Logical Functions) ## AND = Y FALSE = FALSO IF = SI IFERROR = SI.ERROR IFNA = SI.ND IFS = SI.CONJUNTO NOT = NO OR = O SWITCH = CAMBIAR TRUE = VERDADERO XOR = XO ## ## Funciones de búsqueda y referencia (Lookup & Reference Functions) ## ADDRESS = DIRECCION AREAS = AREAS CHOOSE = ELEGIR COLUMN = COLUMNA COLUMNS = COLUMNAS FORMULATEXT = FORMULATEXTO GETPIVOTDATA = IMPORTARDATOSDINAMICOS HLOOKUP = BUSCARH HYPERLINK = HIPERVINCULO INDEX = INDICE INDIRECT = INDIRECTO LOOKUP = BUSCAR MATCH = COINCIDIR OFFSET = DESREF ROW = FILA ROWS = FILAS RTD = RDTR TRANSPOSE = TRANSPONER VLOOKUP = BUSCARV *RC = FC ## ## Funciones matemáticas y trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = NUMERO.ARABE ASIN = ASENO ASINH = ASENOH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = MULTIPLO.SUPERIOR.MAT CEILING.PRECISE = MULTIPLO.SUPERIOR.EXACTO COMBIN = COMBINAT COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = CONV.DECIMAL DEGREES = GRADOS ECMA.CEILING = MULTIPLO.SUPERIOR.ECMA EVEN = REDONDEA.PAR EXP = EXP FACT = FACT FACTDOUBLE = FACT.DOBLE FLOOR.MATH = MULTIPLO.INFERIOR.MAT FLOOR.PRECISE = MULTIPLO.INFERIOR.EXACTO GCD = M.C.D INT = ENTERO ISO.CEILING = MULTIPLO.SUPERIOR.ISO LCM = M.C.M LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERSA MMULT = MMULT MOD = RESIDUO MROUND = REDOND.MULT MULTINOMIAL = MULTINOMIAL MUNIT = M.UNIDAD ODD = REDONDEA.IMPAR PI = PI POWER = POTENCIA PRODUCT = PRODUCTO QUOTIENT = COCIENTE RADIANS = RADIANES RAND = ALEATORIO RANDBETWEEN = ALEATORIO.ENTRE ROMAN = NUMERO.ROMANO ROUND = REDONDEAR ROUNDBAHTDOWN = REDONDEAR.BAHT.MAS ROUNDBAHTUP = REDONDEAR.BAHT.MENOS ROUNDDOWN = REDONDEAR.MENOS ROUNDUP = REDONDEAR.MAS SEC = SEC SECH = SECH SERIESSUM = SUMA.SERIES SIGN = SIGNO SIN = SENO SINH = SENOH SQRT = RAIZ SQRTPI = RAIZ2PI SUBTOTAL = SUBTOTALES SUM = SUMA SUMIF = SUMAR.SI SUMIFS = SUMAR.SI.CONJUNTO SUMPRODUCT = SUMAPRODUCTO SUMSQ = SUMA.CUADRADOS SUMX2MY2 = SUMAX2MENOSY2 SUMX2PY2 = SUMAX2MASY2 SUMXMY2 = SUMAXMENOSY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funciones estadísticas (Statistical Functions) ## AVEDEV = DESVPROM AVERAGE = PROMEDIO AVERAGEA = PROMEDIOA AVERAGEIF = PROMEDIO.SI AVERAGEIFS = PROMEDIO.SI.CONJUNTO BETA.DIST = DISTR.BETA.N BETA.INV = INV.BETA.N BINOM.DIST = DISTR.BINOM.N BINOM.DIST.RANGE = DISTR.BINOM.SERIE BINOM.INV = INV.BINOM CHISQ.DIST = DISTR.CHICUAD CHISQ.DIST.RT = DISTR.CHICUAD.CD CHISQ.INV = INV.CHICUAD CHISQ.INV.RT = INV.CHICUAD.CD CHISQ.TEST = PRUEBA.CHICUAD CONFIDENCE.NORM = INTERVALO.CONFIANZA.NORM CONFIDENCE.T = INTERVALO.CONFIANZA.T CORREL = COEF.DE.CORREL COUNT = CONTAR COUNTA = CONTARA COUNTBLANK = CONTAR.BLANCO COUNTIF = CONTAR.SI COUNTIFS = CONTAR.SI.CONJUNTO COVARIANCE.P = COVARIANCE.P COVARIANCE.S = COVARIANZA.M DEVSQ = DESVIA2 EXPON.DIST = DISTR.EXP.N F.DIST = DISTR.F.N F.DIST.RT = DISTR.F.CD F.INV = INV.F F.INV.RT = INV.F.CD F.TEST = PRUEBA.F.N FISHER = FISHER FISHERINV = PRUEBA.FISHER.INV FORECAST.ETS = PRONOSTICO.ETS FORECAST.ETS.CONFINT = PRONOSTICO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PRONOSTICO.ETS.ESTACIONALIDAD FORECAST.ETS.STAT = PRONOSTICO.ETS.STAT FORECAST.LINEAR = PRONOSTICO.LINEAL FREQUENCY = FRECUENCIA GAMMA = GAMMA GAMMA.DIST = DISTR.GAMMA.N GAMMA.INV = INV.GAMMA GAMMALN = GAMMA.LN GAMMALN.PRECISE = GAMMA.LN.EXACTO GAUSS = GAUSS GEOMEAN = MEDIA.GEOM GROWTH = CRECIMIENTO HARMEAN = MEDIA.ARMO HYPGEOM.DIST = DISTR.HIPERGEOM.N INTERCEPT = INTERSECCION.EJE KURT = CURTOSIS LARGE = K.ESIMO.MAYOR LINEST = ESTIMACION.LINEAL LOGEST = ESTIMACION.LOGARITMICA LOGNORM.DIST = DISTR.LOGNORM LOGNORM.INV = INV.LOGNORM MAX = MAX MAXA = MAXA MAXIFS = MAX.SI.CONJUNTO MEDIAN = MEDIANA MIN = MIN MINA = MINA MINIFS = MIN.SI.CONJUNTO MODE.MULT = MODA.VARIOS MODE.SNGL = MODA.UNO NEGBINOM.DIST = NEGBINOM.DIST NORM.DIST = DISTR.NORM.N NORM.INV = INV.NORM NORM.S.DIST = DISTR.NORM.ESTAND.N NORM.S.INV = INV.NORM.ESTAND PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = RANGO.PERCENTIL.EXC PERCENTRANK.INC = RANGO.PERCENTIL.INC PERMUT = PERMUTACIONES PERMUTATIONA = PERMUTACIONES.A PHI = FI POISSON.DIST = POISSON.DIST PROB = PROBABILIDAD QUARTILE.EXC = CUARTIL.EXC QUARTILE.INC = CUARTIL.INC RANK.AVG = JERARQUIA.MEDIA RANK.EQ = JERARQUIA.EQV RSQ = COEFICIENTE.R2 SKEW = COEFICIENTE.ASIMETRIA SKEW.P = COEFICIENTE.ASIMETRIA.P SLOPE = PENDIENTE SMALL = K.ESIMO.MENOR STANDARDIZE = NORMALIZACION STDEV.P = DESVEST.P STDEV.S = DESVEST.M STDEVA = DESVESTA STDEVPA = DESVESTPA STEYX = ERROR.TIPICO.XY T.DIST = DISTR.T.N T.DIST.2T = DISTR.T.2C T.DIST.RT = DISTR.T.CD T.INV = INV.T T.INV.2T = INV.T.2C T.TEST = PRUEBA.T.N TREND = TENDENCIA TRIMMEAN = MEDIA.ACOTADA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = DISTR.WEIBULL Z.TEST = PRUEBA.Z.N ## ## Funciones de texto (Text Functions) ## BAHTTEXT = TEXTOBAHT CHAR = CARACTER CLEAN = LIMPIAR CODE = CODIGO CONCAT = CONCAT DOLLAR = MONEDA EXACT = IGUAL FIND = ENCONTRAR FIXED = DECIMAL ISTHAIDIGIT = ESDIGITOTAI LEFT = IZQUIERDA LEN = LARGO LOWER = MINUSC MID = EXTRAE NUMBERSTRING = CADENA.NUMERO NUMBERVALUE = VALOR.NUMERO PHONETIC = FONETICO PROPER = NOMPROPIO REPLACE = REEMPLAZAR REPT = REPETIR RIGHT = DERECHA SEARCH = HALLAR SUBSTITUTE = SUSTITUIR T = T TEXT = TEXTO TEXTJOIN = UNIRCADENAS THAIDIGIT = DIGITOTAI THAINUMSOUND = SONNUMTAI THAINUMSTRING = CADENANUMTAI THAISTRINGLENGTH = LONGCADENATAI TRIM = ESPACIOS UNICHAR = UNICAR UNICODE = UNICODE UPPER = MAYUSC VALUE = VALOR ## ## Funciones web (Web Functions) ## ENCODEURL = URLCODIF FILTERXML = XMLFILTRO WEBSERVICE = SERVICIOWEB ## ## Funciones de compatibilidad (Compatibility Functions) ## BETADIST = DISTR.BETA BETAINV = DISTR.BETA.INV BINOMDIST = DISTR.BINOM CEILING = MULTIPLO.SUPERIOR CHIDIST = DISTR.CHI CHIINV = PRUEBA.CHI.INV CHITEST = PRUEBA.CHI CONCATENATE = CONCATENAR CONFIDENCE = INTERVALO.CONFIANZA COVAR = COVAR CRITBINOM = BINOM.CRIT EXPONDIST = DISTR.EXP FDIST = DISTR.F FINV = DISTR.F.INV FLOOR = MULTIPLO.INFERIOR FORECAST = PRONOSTICO FTEST = PRUEBA.F GAMMADIST = DISTR.GAMMA GAMMAINV = DISTR.GAMMA.INV HYPGEOMDIST = DISTR.HIPERGEOM LOGINV = DISTR.LOG.INV LOGNORMDIST = DISTR.LOG.NORM MODE = MODA NEGBINOMDIST = NEGBINOMDIST NORMDIST = DISTR.NORM NORMINV = DISTR.NORM.INV NORMSDIST = DISTR.NORM.ESTAND NORMSINV = DISTR.NORM.ESTAND.INV PERCENTILE = PERCENTIL PERCENTRANK = RANGO.PERCENTIL POISSON = POISSON QUARTILE = CUARTIL RANK = JERARQUIA STDEV = DESVEST STDEVP = DESVESTP TDIST = DISTR.T TINV = DISTR.T.INV TTEST = PRUEBA.T VAR = VAR VARP = VARP WEIBULL = DIST.WEIBULL ZTEST = PRUEBA.Z ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/fi/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Suomi (Finnish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #TYHJÄ! DIV0 = #JAKO/0! VALUE = #ARVO! REF = #VIITTAUS! NAME = #NIMI? NUM = #LUKU! NA = #PUUTTUU! ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/fi/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Suomi (Finnish) ## ############################################################ ## ## Kuutiofunktiot (Cube Functions) ## CUBEKPIMEMBER = KUUTIOKPIJÄSEN CUBEMEMBER = KUUTIONJÄSEN CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN CUBESET = KUUTIOJOUKKO CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ CUBEVALUE = KUUTIONARVO ## ## Tietokantafunktiot (Database Functions) ## DAVERAGE = TKESKIARVO DCOUNT = TLASKE DCOUNTA = TLASKEA DGET = TNOUDA DMAX = TMAKS DMIN = TMIN DPRODUCT = TTULO DSTDEV = TKESKIHAJONTA DSTDEVP = TKESKIHAJONTAP DSUM = TSUMMA DVAR = TVARIANSSI DVARP = TVARIANSSIP ## ## Päivämäärä- ja aikafunktiot (Date & Time Functions) ## DATE = PÄIVÄYS DATEDIF = PVMERO DATESTRING = PVMMERKKIJONO DATEVALUE = PÄIVÄYSARVO DAY = PÄIVÄ DAYS = PÄIVÄT DAYS360 = PÄIVÄT360 EDATE = PÄIVÄ.KUUKAUSI EOMONTH = KUUKAUSI.LOPPU HOUR = TUNNIT ISOWEEKNUM = VIIKKO.ISO.NRO MINUTE = MINUUTIT MONTH = KUUKAUSI NETWORKDAYS = TYÖPÄIVÄT NETWORKDAYS.INTL = TYÖPÄIVÄT.KANSVÄL NOW = NYT SECOND = SEKUNNIT THAIDAYOFWEEK = THAI.VIIKONPÄIVÄ THAIMONTHOFYEAR = THAI.KUUKAUSI THAIYEAR = THAI.VUOSI TIME = AIKA TIMEVALUE = AIKA_ARVO TODAY = TÄMÄ.PÄIVÄ WEEKDAY = VIIKONPÄIVÄ WEEKNUM = VIIKKO.NRO WORKDAY = TYÖPÄIVÄ WORKDAY.INTL = TYÖPÄIVÄ.KANSVÄL YEAR = VUOSI YEARFRAC = VUOSI.OSA ## ## Tekniset funktiot (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINDES BIN2HEX = BINHEKSA BIN2OCT = BINOKT BITAND = BITTI.JA BITLSHIFT = BITTI.SIIRTO.V BITOR = BITTI.TAI BITRSHIFT = BITTI.SIIRTO.O BITXOR = BITTI.EHDOTON.TAI COMPLEX = KOMPLEKSI CONVERT = MUUNNA DEC2BIN = DESBIN DEC2HEX = DESHEKSA DEC2OCT = DESOKT DELTA = SAMA.ARVO ERF = VIRHEFUNKTIO ERF.PRECISE = VIRHEFUNKTIO.TARKKA ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ERFC.PRECISE = VIRHEFUNKTIO.KOMPLEMENTTI.TARKKA GESTEP = RAJA HEX2BIN = HEKSABIN HEX2DEC = HEKSADES HEX2OCT = HEKSAOKT IMABS = KOMPLEKSI.ABS IMAGINARY = KOMPLEKSI.IMAG IMARGUMENT = KOMPLEKSI.ARG IMCONJUGATE = KOMPLEKSI.KONJ IMCOS = KOMPLEKSI.COS IMCOSH = IMCOSH IMCOT = KOMPLEKSI.COT IMCSC = KOMPLEKSI.KOSEK IMCSCH = KOMPLEKSI.KOSEKH IMDIV = KOMPLEKSI.OSAM IMEXP = KOMPLEKSI.EKSP IMLN = KOMPLEKSI.LN IMLOG10 = KOMPLEKSI.LOG10 IMLOG2 = KOMPLEKSI.LOG2 IMPOWER = KOMPLEKSI.POT IMPRODUCT = KOMPLEKSI.TULO IMREAL = KOMPLEKSI.REAALI IMSEC = KOMPLEKSI.SEK IMSECH = KOMPLEKSI.SEKH IMSIN = KOMPLEKSI.SIN IMSINH = KOMPLEKSI.SINH IMSQRT = KOMPLEKSI.NELIÖJ IMSUB = KOMPLEKSI.EROTUS IMSUM = KOMPLEKSI.SUM IMTAN = KOMPLEKSI.TAN OCT2BIN = OKTBIN OCT2DEC = OKTDES OCT2HEX = OKTHEKSA ## ## Rahoitusfunktiot (Financial Functions) ## ACCRINT = KERTYNYT.KORKO ACCRINTM = KERTYNYT.KORKO.LOPUSSA AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KORKOPÄIVÄT.ALUSTA COUPDAYS = KORKOPÄIVÄT COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA COUPNCD = KORKOPÄIVÄ.SEURAAVA COUPNUM = KORKOPÄIVÄ.JAKSOT COUPPCD = KORKOPÄIVÄ.EDELLINEN CUMIPMT = MAKSETTU.KORKO CUMPRINC = MAKSETTU.LYHENNYS DB = DB DDB = DDB DISC = DISKONTTOKORKO DOLLARDE = VALUUTTA.DES DOLLARFR = VALUUTTA.MURTO DURATION = KESTO EFFECT = KORKO.EFEKT FV = TULEVA.ARVO FVSCHEDULE = TULEVA.ARVO.ERIKORKO INTRATE = KORKO.ARVOPAPERI IPMT = IPMT IRR = SISÄINEN.KORKO ISPMT = ISPMT MDURATION = KESTO.MUUNN MIRR = MSISÄINEN NOMINAL = KORKO.VUOSI NPER = NJAKSO NPV = NNA ODDFPRICE = PARITON.ENS.NIMELLISARVO ODDFYIELD = PARITON.ENS.TUOTTO ODDLPRICE = PARITON.VIIM.NIMELLISARVO ODDLYIELD = PARITON.VIIM.TUOTTO PDURATION = KESTO.JAKSO PMT = MAKSU PPMT = PPMT PRICE = HINTA PRICEDISC = HINTA.DISK PRICEMAT = HINTA.LUNASTUS PV = NA RATE = KORKO RECEIVED = SAATU.HINTA RRI = TOT.ROI SLN = STP SYD = VUOSIPOISTO TBILLEQ = OBLIG.TUOTTOPROS TBILLPRICE = OBLIG.HINTA TBILLYIELD = OBLIG.TUOTTO VDB = VDB XIRR = SISÄINEN.KORKO.JAKSOTON XNPV = NNA.JAKSOTON YIELD = TUOTTO YIELDDISC = TUOTTO.DISK YIELDMAT = TUOTTO.ERÄP ## ## Tietofunktiot (Information Functions) ## CELL = SOLU ERROR.TYPE = VIRHEEN.LAJI INFO = KUVAUS ISBLANK = ONTYHJÄ ISERR = ONVIRH ISERROR = ONVIRHE ISEVEN = ONPARILLINEN ISFORMULA = ONKAAVA ISLOGICAL = ONTOTUUS ISNA = ONPUUTTUU ISNONTEXT = ONEI_TEKSTI ISNUMBER = ONLUKU ISODD = ONPARITON ISREF = ONVIITT ISTEXT = ONTEKSTI N = N NA = PUUTTUU SHEET = TAULUKKO SHEETS = TAULUKOT TYPE = TYYPPI ## ## Loogiset funktiot (Logical Functions) ## AND = JA FALSE = EPÄTOSI IF = JOS IFERROR = JOSVIRHE IFNA = JOSPUUTTUU IFS = JOSS NOT = EI OR = TAI SWITCH = MUUTA TRUE = TOSI XOR = EHDOTON.TAI ## ## Haku- ja viitefunktiot (Lookup & Reference Functions) ## ADDRESS = OSOITE AREAS = ALUEET CHOOSE = VALITSE.INDEKSI COLUMN = SARAKE COLUMNS = SARAKKEET FORMULATEXT = KAAVA.TEKSTI GETPIVOTDATA = NOUDA.PIVOT.TIEDOT HLOOKUP = VHAKU HYPERLINK = HYPERLINKKI INDEX = INDEKSI INDIRECT = EPÄSUORA LOOKUP = HAKU MATCH = VASTINE OFFSET = SIIRTYMÄ ROW = RIVI ROWS = RIVIT RTD = RTD TRANSPOSE = TRANSPONOI VLOOKUP = PHAKU *RC = RS ## ## Matemaattiset ja trigonometriset funktiot (Math & Trig Functions) ## ABS = ITSEISARVO ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = KOOSTE ARABIC = ARABIA ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = PERUS CEILING.MATH = PYÖRISTÄ.KERR.YLÖS.MATEMAATTINEN CEILING.PRECISE = PYÖRISTÄ.KERR.YLÖS.TARKKA COMBIN = KOMBINAATIO COMBINA = KOMBINAATIOA COS = COS COSH = COSH COT = COT COTH = COTH CSC = KOSEK CSCH = KOSEKH DECIMAL = DESIMAALI DEGREES = ASTEET ECMA.CEILING = ECMA.PYÖRISTÄ.KERR.YLÖS EVEN = PARILLINEN EXP = EKSPONENTTI FACT = KERTOMA FACTDOUBLE = KERTOMA.OSA FLOOR.MATH = PYÖRISTÄ.KERR.ALAS.MATEMAATTINEN FLOOR.PRECISE = PYÖRISTÄ.KERR.ALAS.TARKKA GCD = SUURIN.YHT.TEKIJÄ INT = KOKONAISLUKU ISO.CEILING = ISO.PYÖRISTÄ.KERR.YLÖS LCM = PIENIN.YHT.JAETTAVA LN = LUONNLOG LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MKÄÄNTEINEN MMULT = MKERRO MOD = JAKOJ MROUND = PYÖRISTÄ.KERR MULTINOMIAL = MULTINOMI MUNIT = YKSIKKÖM ODD = PARITON PI = PII POWER = POTENSSI PRODUCT = TULO QUOTIENT = OSAMÄÄRÄ RADIANS = RADIAANIT RAND = SATUNNAISLUKU RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ROMAN = ROMAN ROUND = PYÖRISTÄ ROUNDBAHTDOWN = PYÖRISTÄ.BAHT.ALAS ROUNDBAHTUP = PYÖRISTÄ.BAHT.YLÖS ROUNDDOWN = PYÖRISTÄ.DES.ALAS ROUNDUP = PYÖRISTÄ.DES.YLÖS SEC = SEK SECH = SEKH SERIESSUM = SARJA.SUMMA SIGN = ETUMERKKI SIN = SIN SINH = SINH SQRT = NELIÖJUURI SQRTPI = NELIÖJUURI.PII SUBTOTAL = VÄLISUMMA SUM = SUMMA SUMIF = SUMMA.JOS SUMIFS = SUMMA.JOS.JOUKKO SUMPRODUCT = TULOJEN.SUMMA SUMSQ = NELIÖSUMMA SUMX2MY2 = NELIÖSUMMIEN.EROTUS SUMX2PY2 = NELIÖSUMMIEN.SUMMA SUMXMY2 = EROTUSTEN.NELIÖSUMMA TAN = TAN TANH = TANH TRUNC = KATKAISE ## ## Tilastolliset funktiot (Statistical Functions) ## AVEDEV = KESKIPOIKKEAMA AVERAGE = KESKIARVO AVERAGEA = KESKIARVOA AVERAGEIF = KESKIARVO.JOS AVERAGEIFS = KESKIARVO.JOS.JOUKKO BETA.DIST = BEETA.JAKAUMA BETA.INV = BEETA.KÄÄNT BINOM.DIST = BINOMI.JAKAUMA BINOM.DIST.RANGE = BINOMI.JAKAUMA.ALUE BINOM.INV = BINOMIJAKAUMA.KÄÄNT CHISQ.DIST = CHINELIÖ.JAKAUMA CHISQ.DIST.RT = CHINELIÖ.JAKAUMA.OH CHISQ.INV = CHINELIÖ.KÄÄNT CHISQ.INV.RT = CHINELIÖ.KÄÄNT.OH CHISQ.TEST = CHINELIÖ.TESTI CONFIDENCE.NORM = LUOTTAMUSVÄLI.NORM CONFIDENCE.T = LUOTTAMUSVÄLI.T CORREL = KORRELAATIO COUNT = LASKE COUNTA = LASKE.A COUNTBLANK = LASKE.TYHJÄT COUNTIF = LASKE.JOS COUNTIFS = LASKE.JOS.JOUKKO COVARIANCE.P = KOVARIANSSI.P COVARIANCE.S = KOVARIANSSI.S DEVSQ = OIKAISTU.NELIÖSUMMA EXPON.DIST = EKSPONENTIAALI.JAKAUMA F.DIST = F.JAKAUMA F.DIST.RT = F.JAKAUMA.OH F.INV = F.KÄÄNT F.INV.RT = F.KÄÄNT.OH F.TEST = F.TESTI FISHER = FISHER FISHERINV = FISHER.KÄÄNT FORECAST.ETS = ENNUSTE.ETS FORECAST.ETS.CONFINT = ENNUSTE.ETS.CONFINT FORECAST.ETS.SEASONALITY = ENNUSTE.ETS.KAUSIVAIHTELU FORECAST.ETS.STAT = ENNUSTE.ETS.STAT FORECAST.LINEAR = ENNUSTE.LINEAARINEN FREQUENCY = TAAJUUS GAMMA = GAMMA GAMMA.DIST = GAMMA.JAKAUMA GAMMA.INV = GAMMA.JAKAUMA.KÄÄNT GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.TARKKA GAUSS = GAUSS GEOMEAN = KESKIARVO.GEOM GROWTH = KASVU HARMEAN = KESKIARVO.HARM HYPGEOM.DIST = HYPERGEOM_JAKAUMA INTERCEPT = LEIKKAUSPISTE KURT = KURT LARGE = SUURI LINEST = LINREGR LOGEST = LOGREGR LOGNORM.DIST = LOGNORM_JAKAUMA LOGNORM.INV = LOGNORM.KÄÄNT MAX = MAKS MAXA = MAKSA MAXIFS = MAKS.JOS MEDIAN = MEDIAANI MIN = MIN MINA = MINA MINIFS = MIN.JOS MODE.MULT = MOODI.USEA MODE.SNGL = MOODI.YKSI NEGBINOM.DIST = BINOMI.JAKAUMA.NEG NORM.DIST = NORMAALI.JAKAUMA NORM.INV = NORMAALI.JAKAUMA.KÄÄNT NORM.S.DIST = NORM_JAKAUMA.NORMIT NORM.S.INV = NORM_JAKAUMA.KÄÄNT PEARSON = PEARSON PERCENTILE.EXC = PROSENTTIPISTE.ULK PERCENTILE.INC = PROSENTTIPISTE.SIS PERCENTRANK.EXC = PROSENTTIJÄRJESTYS.ULK PERCENTRANK.INC = PROSENTTIJÄRJESTYS.SIS PERMUT = PERMUTAATIO PERMUTATIONA = PERMUTAATIOA PHI = FII POISSON.DIST = POISSON.JAKAUMA PROB = TODENNÄKÖISYYS QUARTILE.EXC = NELJÄNNES.ULK QUARTILE.INC = NELJÄNNES.SIS RANK.AVG = ARVON.MUKAAN.KESKIARVO RANK.EQ = ARVON.MUKAAN.TASAN RSQ = PEARSON.NELIÖ SKEW = JAKAUMAN.VINOUS SKEW.P = JAKAUMAN.VINOUS.POP SLOPE = KULMAKERROIN SMALL = PIENI STANDARDIZE = NORMITA STDEV.P = KESKIHAJONTA.P STDEV.S = KESKIHAJONTA.S STDEVA = KESKIHAJONTAA STDEVPA = KESKIHAJONTAPA STEYX = KESKIVIRHE T.DIST = T.JAKAUMA T.DIST.2T = T.JAKAUMA.2S T.DIST.RT = T.JAKAUMA.OH T.INV = T.KÄÄNT T.INV.2T = T.KÄÄNT.2S T.TEST = T.TESTI TREND = SUUNTAUS TRIMMEAN = KESKIARVO.TASATTU VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.JAKAUMA Z.TEST = Z.TESTI ## ## Tekstifunktiot (Text Functions) ## BAHTTEXT = BAHTTEKSTI CHAR = MERKKI CLEAN = SIIVOA CODE = KOODI CONCAT = YHDISTÄ DOLLAR = VALUUTTA EXACT = VERTAA FIND = ETSI FIXED = KIINTEÄ ISTHAIDIGIT = ON.THAI.NUMERO LEFT = VASEN LEN = PITUUS LOWER = PIENET MID = POIMI.TEKSTI NUMBERSTRING = NROMERKKIJONO NUMBERVALUE = NROARVO PHONETIC = FONEETTINEN PROPER = ERISNIMI REPLACE = KORVAA REPT = TOISTA RIGHT = OIKEA SEARCH = KÄY.LÄPI SUBSTITUTE = VAIHDA T = T TEXT = TEKSTI TEXTJOIN = TEKSTI.YHDISTÄ THAIDIGIT = THAI.NUMERO THAINUMSOUND = THAI.LUKU.ÄÄNI THAINUMSTRING = THAI.LUKU.MERKKIJONO THAISTRINGLENGTH = THAI.MERKKIJONON.PITUUS TRIM = POISTA.VÄLIT UNICHAR = UNICODEMERKKI UNICODE = UNICODE UPPER = ISOT VALUE = ARVO ## ## Verkkofunktiot (Web Functions) ## ENCODEURL = URLKOODAUS FILTERXML = SUODATA.XML WEBSERVICE = VERKKOPALVELU ## ## Yhteensopivuusfunktiot (Compatibility Functions) ## BETADIST = BEETAJAKAUMA BETAINV = BEETAJAKAUMA.KÄÄNT BINOMDIST = BINOMIJAKAUMA CEILING = PYÖRISTÄ.KERR.YLÖS CHIDIST = CHIJAKAUMA CHIINV = CHIJAKAUMA.KÄÄNT CHITEST = CHITESTI CONCATENATE = KETJUTA CONFIDENCE = LUOTTAMUSVÄLI COVAR = KOVARIANSSI CRITBINOM = BINOMIJAKAUMA.KRIT EXPONDIST = EKSPONENTIAALIJAKAUMA FDIST = FJAKAUMA FINV = FJAKAUMA.KÄÄNT FLOOR = PYÖRISTÄ.KERR.ALAS FORECAST = ENNUSTE FTEST = FTESTI GAMMADIST = GAMMAJAKAUMA GAMMAINV = GAMMAJAKAUMA.KÄÄNT HYPGEOMDIST = HYPERGEOM.JAKAUMA LOGINV = LOGNORM.JAKAUMA.KÄÄNT LOGNORMDIST = LOGNORM.JAKAUMA MODE = MOODI NEGBINOMDIST = BINOMIJAKAUMA.NEG NORMDIST = NORM.JAKAUMA NORMINV = NORM.JAKAUMA.KÄÄNT NORMSDIST = NORM.JAKAUMA.NORMIT NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT PERCENTILE = PROSENTTIPISTE PERCENTRANK = PROSENTTIJÄRJESTYS POISSON = POISSON QUARTILE = NELJÄNNES RANK = ARVON.MUKAAN STDEV = KESKIHAJONTA STDEVP = KESKIHAJONTAP TDIST = TJAKAUMA TINV = TJAKAUMA.KÄÄNT TTEST = TTESTI VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = ZTESTI ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/fr/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Français (French) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NUL! DIV0 VALUE = #VALEUR! REF NAME = #NOM? NUM = #NOMBRE! NA ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/fr/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Français (French) ## ############################################################ ## ## Fonctions Cube (Cube Functions) ## CUBEKPIMEMBER = MEMBREKPICUBE CUBEMEMBER = MEMBRECUBE CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE CUBERANKEDMEMBER = RANGMEMBRECUBE CUBESET = JEUCUBE CUBESETCOUNT = NBJEUCUBE CUBEVALUE = VALEURCUBE ## ## Fonctions de base de données (Database Functions) ## DAVERAGE = BDMOYENNE DCOUNT = BDNB DCOUNTA = BDNBVAL DGET = BDLIRE DMAX = BDMAX DMIN = BDMIN DPRODUCT = BDPRODUIT DSTDEV = BDECARTYPE DSTDEVP = BDECARTYPEP DSUM = BDSOMME DVAR = BDVAR DVARP = BDVARP ## ## Fonctions de date et d’heure (Date & Time Functions) ## DATE = DATE DATEVALUE = DATEVAL DAY = JOUR DAYS = JOURS DAYS360 = JOURS360 EDATE = MOIS.DECALER EOMONTH = FIN.MOIS HOUR = HEURE ISOWEEKNUM = NO.SEMAINE.ISO MINUTE = MINUTE MONTH = MOIS NETWORKDAYS = NB.JOURS.OUVRES NETWORKDAYS.INTL = NB.JOURS.OUVRES.INTL NOW = MAINTENANT SECOND = SECONDE TIME = TEMPS TIMEVALUE = TEMPSVAL TODAY = AUJOURDHUI WEEKDAY = JOURSEM WEEKNUM = NO.SEMAINE WORKDAY = SERIE.JOUR.OUVRE WORKDAY.INTL = SERIE.JOUR.OUVRE.INTL YEAR = ANNEE YEARFRAC = FRACTION.ANNEE ## ## Fonctions d’ingénierie (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINDEC BIN2HEX = BINHEX BIN2OCT = BINOCT BITAND = BITET BITLSHIFT = BITDECALG BITOR = BITOU BITRSHIFT = BITDECALD BITXOR = BITOUEXCLUSIF COMPLEX = COMPLEXE CONVERT = CONVERT DEC2BIN = DECBIN DEC2HEX = DECHEX DEC2OCT = DECOCT DELTA = DELTA ERF = ERF ERF.PRECISE = ERF.PRECIS ERFC = ERFC ERFC.PRECISE = ERFC.PRECIS GESTEP = SUP.SEUIL HEX2BIN = HEXBIN HEX2DEC = HEXDEC HEX2OCT = HEXOCT IMABS = COMPLEXE.MODULE IMAGINARY = COMPLEXE.IMAGINAIRE IMARGUMENT = COMPLEXE.ARGUMENT IMCONJUGATE = COMPLEXE.CONJUGUE IMCOS = COMPLEXE.COS IMCOSH = COMPLEXE.COSH IMCOT = COMPLEXE.COT IMCSC = COMPLEXE.CSC IMCSCH = COMPLEXE.CSCH IMDIV = COMPLEXE.DIV IMEXP = COMPLEXE.EXP IMLN = COMPLEXE.LN IMLOG10 = COMPLEXE.LOG10 IMLOG2 = COMPLEXE.LOG2 IMPOWER = COMPLEXE.PUISSANCE IMPRODUCT = COMPLEXE.PRODUIT IMREAL = COMPLEXE.REEL IMSEC = COMPLEXE.SEC IMSECH = COMPLEXE.SECH IMSIN = COMPLEXE.SIN IMSINH = COMPLEXE.SINH IMSQRT = COMPLEXE.RACINE IMSUB = COMPLEXE.DIFFERENCE IMSUM = COMPLEXE.SOMME IMTAN = COMPLEXE.TAN OCT2BIN = OCTBIN OCT2DEC = OCTDEC OCT2HEX = OCTHEX ## ## Fonctions financières (Financial Functions) ## ACCRINT = INTERET.ACC ACCRINTM = INTERET.ACC.MAT AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = NB.JOURS.COUPON.PREC COUPDAYS = NB.JOURS.COUPONS COUPDAYSNC = NB.JOURS.COUPON.SUIV COUPNCD = DATE.COUPON.SUIV COUPNUM = NB.COUPONS COUPPCD = DATE.COUPON.PREC CUMIPMT = CUMUL.INTER CUMPRINC = CUMUL.PRINCPER DB = DB DDB = DDB DISC = TAUX.ESCOMPTE DOLLARDE = PRIX.DEC DOLLARFR = PRIX.FRAC DURATION = DUREE EFFECT = TAUX.EFFECTIF FV = VC FVSCHEDULE = VC.PAIEMENTS INTRATE = TAUX.INTERET IPMT = INTPER IRR = TRI ISPMT = ISPMT MDURATION = DUREE.MODIFIEE MIRR = TRIM NOMINAL = TAUX.NOMINAL NPER = NPM NPV = VAN ODDFPRICE = PRIX.PCOUPON.IRREG ODDFYIELD = REND.PCOUPON.IRREG ODDLPRICE = PRIX.DCOUPON.IRREG ODDLYIELD = REND.DCOUPON.IRREG PDURATION = PDUREE PMT = VPM PPMT = PRINCPER PRICE = PRIX.TITRE PRICEDISC = VALEUR.ENCAISSEMENT PRICEMAT = PRIX.TITRE.ECHEANCE PV = VA RATE = TAUX RECEIVED = VALEUR.NOMINALE RRI = TAUX.INT.EQUIV SLN = AMORLIN SYD = SYD TBILLEQ = TAUX.ESCOMPTE.R TBILLPRICE = PRIX.BON.TRESOR TBILLYIELD = RENDEMENT.BON.TRESOR VDB = VDB XIRR = TRI.PAIEMENTS XNPV = VAN.PAIEMENTS YIELD = RENDEMENT.TITRE YIELDDISC = RENDEMENT.SIMPLE YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## ## Fonctions d’information (Information Functions) ## CELL = CELLULE ERROR.TYPE = TYPE.ERREUR INFO = INFORMATIONS ISBLANK = ESTVIDE ISERR = ESTERR ISERROR = ESTERREUR ISEVEN = EST.PAIR ISFORMULA = ESTFORMULE ISLOGICAL = ESTLOGIQUE ISNA = ESTNA ISNONTEXT = ESTNONTEXTE ISNUMBER = ESTNUM ISODD = EST.IMPAIR ISREF = ESTREF ISTEXT = ESTTEXTE N = N NA = NA SHEET = FEUILLE SHEETS = FEUILLES TYPE = TYPE ## ## Fonctions logiques (Logical Functions) ## AND = ET FALSE = FAUX IF = SI IFERROR = SIERREUR IFNA = SI.NON.DISP IFS = SI.CONDITIONS NOT = NON OR = OU SWITCH = SI.MULTIPLE TRUE = VRAI XOR = OUX ## ## Fonctions de recherche et de référence (Lookup & Reference Functions) ## ADDRESS = ADRESSE AREAS = ZONES CHOOSE = CHOISIR COLUMN = COLONNE COLUMNS = COLONNES FORMULATEXT = FORMULETEXTE GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE HLOOKUP = RECHERCHEH HYPERLINK = LIEN_HYPERTEXTE INDEX = INDEX INDIRECT = INDIRECT LOOKUP = RECHERCHE MATCH = EQUIV OFFSET = DECALER ROW = LIGNE ROWS = LIGNES RTD = RTD TRANSPOSE = TRANSPOSE VLOOKUP = RECHERCHEV *RC = LC ## ## Fonctions mathématiques et trigonométriques (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAT ARABIC = CHIFFRE.ARABE ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = PLAFOND.MATH CEILING.PRECISE = PLAFOND.PRECIS COMBIN = COMBIN COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = DEGRES ECMA.CEILING = ECMA.PLAFOND EVEN = PAIR EXP = EXP FACT = FACT FACTDOUBLE = FACTDOUBLE FLOOR.MATH = PLANCHER.MATH FLOOR.PRECISE = PLANCHER.PRECIS GCD = PGCD INT = ENT ISO.CEILING = ISO.PLAFOND LCM = PPCM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = DETERMAT MINVERSE = INVERSEMAT MMULT = PRODUITMAT MOD = MOD MROUND = ARRONDI.AU.MULTIPLE MULTINOMIAL = MULTINOMIALE MUNIT = MATRICE.UNITAIRE ODD = IMPAIR PI = PI POWER = PUISSANCE PRODUCT = PRODUIT QUOTIENT = QUOTIENT RADIANS = RADIANS RAND = ALEA RANDBETWEEN = ALEA.ENTRE.BORNES ROMAN = ROMAIN ROUND = ARRONDI ROUNDDOWN = ARRONDI.INF ROUNDUP = ARRONDI.SUP SEC = SEC SECH = SECH SERIESSUM = SOMME.SERIES SIGN = SIGNE SIN = SIN SINH = SINH SQRT = RACINE SQRTPI = RACINE.PI SUBTOTAL = SOUS.TOTAL SUM = SOMME SUMIF = SOMME.SI SUMIFS = SOMME.SI.ENS SUMPRODUCT = SOMMEPROD SUMSQ = SOMME.CARRES SUMX2MY2 = SOMME.X2MY2 SUMX2PY2 = SOMME.X2PY2 SUMXMY2 = SOMME.XMY2 TAN = TAN TANH = TANH TRUNC = TRONQUE ## ## Fonctions statistiques (Statistical Functions) ## AVEDEV = ECART.MOYEN AVERAGE = MOYENNE AVERAGEA = AVERAGEA AVERAGEIF = MOYENNE.SI AVERAGEIFS = MOYENNE.SI.ENS BETA.DIST = LOI.BETA.N BETA.INV = BETA.INVERSE.N BINOM.DIST = LOI.BINOMIALE.N BINOM.DIST.RANGE = LOI.BINOMIALE.SERIE BINOM.INV = LOI.BINOMIALE.INVERSE CHISQ.DIST = LOI.KHIDEUX.N CHISQ.DIST.RT = LOI.KHIDEUX.DROITE CHISQ.INV = LOI.KHIDEUX.INVERSE CHISQ.INV.RT = LOI.KHIDEUX.INVERSE.DROITE CHISQ.TEST = CHISQ.TEST CONFIDENCE.NORM = INTERVALLE.CONFIANCE.NORMAL CONFIDENCE.T = INTERVALLE.CONFIANCE.STUDENT CORREL = COEFFICIENT.CORRELATION COUNT = NB COUNTA = NBVAL COUNTBLANK = NB.VIDE COUNTIF = NB.SI COUNTIFS = NB.SI.ENS COVARIANCE.P = COVARIANCE.PEARSON COVARIANCE.S = COVARIANCE.STANDARD DEVSQ = SOMME.CARRES.ECARTS EXPON.DIST = LOI.EXPONENTIELLE.N F.DIST = LOI.F.N F.DIST.RT = LOI.F.DROITE F.INV = INVERSE.LOI.F.N F.INV.RT = INVERSE.LOI.F.DROITE F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHER.INVERSE FORECAST.ETS = PREVISION.ETS FORECAST.ETS.CONFINT = PREVISION.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISION.ETS.CARACTERESAISONNIER FORECAST.ETS.STAT = PREVISION.ETS.STAT FORECAST.LINEAR = PREVISION.LINEAIRE FREQUENCY = FREQUENCE GAMMA = GAMMA GAMMA.DIST = LOI.GAMMA.N GAMMA.INV = LOI.GAMMA.INVERSE.N GAMMALN = LNGAMMA GAMMALN.PRECISE = LNGAMMA.PRECIS GAUSS = GAUSS GEOMEAN = MOYENNE.GEOMETRIQUE GROWTH = CROISSANCE HARMEAN = MOYENNE.HARMONIQUE HYPGEOM.DIST = LOI.HYPERGEOMETRIQUE.N INTERCEPT = ORDONNEE.ORIGINE KURT = KURTOSIS LARGE = GRANDE.VALEUR LINEST = DROITEREG LOGEST = LOGREG LOGNORM.DIST = LOI.LOGNORMALE.N LOGNORM.INV = LOI.LOGNORMALE.INVERSE.N MAX = MAX MAXA = MAXA MAXIFS = MAX.SI MEDIAN = MEDIANE MIN = MIN MINA = MINA MINIFS = MIN.SI MODE.MULT = MODE.MULTIPLE MODE.SNGL = MODE.SIMPLE NEGBINOM.DIST = LOI.BINOMIALE.NEG.N NORM.DIST = LOI.NORMALE.N NORM.INV = LOI.NORMALE.INVERSE.N NORM.S.DIST = LOI.NORMALE.STANDARD.N NORM.S.INV = LOI.NORMALE.STANDARD.INVERSE.N PEARSON = PEARSON PERCENTILE.EXC = CENTILE.EXCLURE PERCENTILE.INC = CENTILE.INCLURE PERCENTRANK.EXC = RANG.POURCENTAGE.EXCLURE PERCENTRANK.INC = RANG.POURCENTAGE.INCLURE PERMUT = PERMUTATION PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = LOI.POISSON.N PROB = PROBABILITE QUARTILE.EXC = QUARTILE.EXCLURE QUARTILE.INC = QUARTILE.INCLURE RANK.AVG = MOYENNE.RANG RANK.EQ = EQUATION.RANG RSQ = COEFFICIENT.DETERMINATION SKEW = COEFFICIENT.ASYMETRIE SKEW.P = COEFFICIENT.ASYMETRIE.P SLOPE = PENTE SMALL = PETITE.VALEUR STANDARDIZE = CENTREE.REDUITE STDEV.P = ECARTYPE.PEARSON STDEV.S = ECARTYPE.STANDARD STDEVA = STDEVA STDEVPA = STDEVPA STEYX = ERREUR.TYPE.XY T.DIST = LOI.STUDENT.N T.DIST.2T = LOI.STUDENT.BILATERALE T.DIST.RT = LOI.STUDENT.DROITE T.INV = LOI.STUDENT.INVERSE.N T.INV.2T = LOI.STUDENT.INVERSE.BILATERALE T.TEST = T.TEST TREND = TENDANCE TRIMMEAN = MOYENNE.REDUITE VAR.P = VAR.P.N VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = LOI.WEIBULL.N Z.TEST = Z.TEST ## ## Fonctions de texte (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = CAR CLEAN = EPURAGE CODE = CODE CONCAT = CONCAT DOLLAR = DEVISE EXACT = EXACT FIND = TROUVE FIXED = CTXT LEFT = GAUCHE LEN = NBCAR LOWER = MINUSCULE MID = STXT NUMBERVALUE = VALEURNOMBRE PHONETIC = PHONETIQUE PROPER = NOMPROPRE REPLACE = REMPLACER REPT = REPT RIGHT = DROITE SEARCH = CHERCHE SUBSTITUTE = SUBSTITUE T = T TEXT = TEXTE TEXTJOIN = JOINDRE.TEXTE TRIM = SUPPRESPACE UNICHAR = UNICAR UNICODE = UNICODE UPPER = MAJUSCULE VALUE = CNUM ## ## Fonctions web (Web Functions) ## ENCODEURL = URLENCODAGE FILTERXML = FILTRE.XML WEBSERVICE = SERVICEWEB ## ## Fonctions de compatibilité (Compatibility Functions) ## BETADIST = LOI.BETA BETAINV = BETA.INVERSE BINOMDIST = LOI.BINOMIALE CEILING = PLAFOND CHIDIST = LOI.KHIDEUX CHIINV = KHIDEUX.INVERSE CHITEST = TEST.KHIDEUX CONCATENATE = CONCATENER CONFIDENCE = INTERVALLE.CONFIANCE COVAR = COVARIANCE CRITBINOM = CRITERE.LOI.BINOMIALE EXPONDIST = LOI.EXPONENTIELLE FDIST = LOI.F FINV = INVERSE.LOI.F FLOOR = PLANCHER FORECAST = PREVISION FTEST = TEST.F GAMMADIST = LOI.GAMMA GAMMAINV = LOI.GAMMA.INVERSE HYPGEOMDIST = LOI.HYPERGEOMETRIQUE LOGINV = LOI.LOGNORMALE.INVERSE LOGNORMDIST = LOI.LOGNORMALE MODE = MODE NEGBINOMDIST = LOI.BINOMIALE.NEG NORMDIST = LOI.NORMALE NORMINV = LOI.NORMALE.INVERSE NORMSDIST = LOI.NORMALE.STANDARD NORMSINV = LOI.NORMALE.STANDARD.INVERSE PERCENTILE = CENTILE PERCENTRANK = RANG.POURCENTAGE POISSON = LOI.POISSON QUARTILE = QUARTILE RANK = RANG STDEV = ECARTYPE STDEVP = ECARTYPEP TDIST = LOI.STUDENT TINV = LOI.STUDENT.INVERSE TTEST = TEST.STUDENT VAR = VAR VARP = VAR.P WEIBULL = LOI.WEIBULL ZTEST = TEST.Z ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/hu/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Magyar (Hungarian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULLA! DIV0 = #ZÉRÓOSZTÓ! VALUE = #ÉRTÉK! REF = #HIV! NAME = #NÉV? NUM = #SZÁM! NA = #HIÁNYZIK ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/hu/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Magyar (Hungarian) ## ############################################################ ## ## Kockafüggvények (Cube Functions) ## CUBEKPIMEMBER = KOCKA.FŐTELJMUT CUBEMEMBER = KOCKA.TAG CUBEMEMBERPROPERTY = KOCKA.TAG.TUL CUBERANKEDMEMBER = KOCKA.HALM.ELEM CUBESET = KOCKA.HALM CUBESETCOUNT = KOCKA.HALM.DB CUBEVALUE = KOCKA.ÉRTÉK ## ## Adatbázis-kezelő függvények (Database Functions) ## DAVERAGE = AB.ÁTLAG DCOUNT = AB.DARAB DCOUNTA = AB.DARAB2 DGET = AB.MEZŐ DMAX = AB.MAX DMIN = AB.MIN DPRODUCT = AB.SZORZAT DSTDEV = AB.SZÓRÁS DSTDEVP = AB.SZÓRÁS2 DSUM = AB.SZUM DVAR = AB.VAR DVARP = AB.VAR2 ## ## Dátumfüggvények (Date & Time Functions) ## DATE = DÁTUM DATEDIF = DÁTUMTÓLIG DATESTRING = DÁTUMSZÖVEG DATEVALUE = DÁTUMÉRTÉK DAY = NAP DAYS = NAPOK DAYS360 = NAP360 EDATE = KALK.DÁTUM EOMONTH = HÓNAP.UTOLSÓ.NAP HOUR = ÓRA ISOWEEKNUM = ISO.HÉT.SZÁMA MINUTE = PERCEK MONTH = HÓNAP NETWORKDAYS = ÖSSZ.MUNKANAP NETWORKDAYS.INTL = ÖSSZ.MUNKANAP.INTL NOW = MOST SECOND = MPERC THAIDAYOFWEEK = THAIHÉTNAPJA THAIMONTHOFYEAR = THAIHÓNAP THAIYEAR = THAIÉV TIME = IDŐ TIMEVALUE = IDŐÉRTÉK TODAY = MA WEEKDAY = HÉT.NAPJA WEEKNUM = HÉT.SZÁMA WORKDAY = KALK.MUNKANAP WORKDAY.INTL = KALK.MUNKANAP.INTL YEAR = ÉV YEARFRAC = TÖRTÉV ## ## Mérnöki függvények (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.DEC BIN2HEX = BIN.HEX BIN2OCT = BIN.OKT BITAND = BIT.ÉS BITLSHIFT = BIT.BAL.ELTOL BITOR = BIT.VAGY BITRSHIFT = BIT.JOBB.ELTOL BITXOR = BIT.XVAGY COMPLEX = KOMPLEX CONVERT = KONVERTÁLÁS DEC2BIN = DEC.BIN DEC2HEX = DEC.HEX DEC2OCT = DEC.OKT DELTA = DELTA ERF = HIBAF ERF.PRECISE = HIBAF.PONTOS ERFC = HIBAF.KOMPLEMENTER ERFC.PRECISE = HIBAFKOMPLEMENTER.PONTOS GESTEP = KÜSZÖBNÉL.NAGYOBB HEX2BIN = HEX.BIN HEX2DEC = HEX.DEC HEX2OCT = HEX.OKT IMABS = KÉPZ.ABSZ IMAGINARY = KÉPZETES IMARGUMENT = KÉPZ.ARGUMENT IMCONJUGATE = KÉPZ.KONJUGÁLT IMCOS = KÉPZ.COS IMCOSH = KÉPZ.COSH IMCOT = KÉPZ.COT IMCSC = KÉPZ.CSC IMCSCH = KÉPZ.CSCH IMDIV = KÉPZ.HÁNYAD IMEXP = KÉPZ.EXP IMLN = KÉPZ.LN IMLOG10 = KÉPZ.LOG10 IMLOG2 = KÉPZ.LOG2 IMPOWER = KÉPZ.HATV IMPRODUCT = KÉPZ.SZORZAT IMREAL = KÉPZ.VALÓS IMSEC = KÉPZ.SEC IMSECH = KÉPZ.SECH IMSIN = KÉPZ.SIN IMSINH = KÉPZ.SINH IMSQRT = KÉPZ.GYÖK IMSUB = KÉPZ.KÜL IMSUM = KÉPZ.ÖSSZEG IMTAN = KÉPZ.TAN OCT2BIN = OKT.BIN OCT2DEC = OKT.DEC OCT2HEX = OKT.HEX ## ## Pénzügyi függvények (Financial Functions) ## ACCRINT = IDŐSZAKI.KAMAT ACCRINTM = LEJÁRATI.KAMAT AMORDEGRC = ÉRTÉKCSÖKK.TÉNYEZŐVEL AMORLINC = ÉRTÉKCSÖKK COUPDAYBS = SZELVÉNYIDŐ.KEZDETTŐL COUPDAYS = SZELVÉNYIDŐ COUPDAYSNC = SZELVÉNYIDŐ.KIFIZETÉSTŐL COUPNCD = ELSŐ.SZELVÉNYDÁTUM COUPNUM = SZELVÉNYSZÁM COUPPCD = UTOLSÓ.SZELVÉNYDÁTUM CUMIPMT = ÖSSZES.KAMAT CUMPRINC = ÖSSZES.TŐKERÉSZ DB = KCS2 DDB = KCSA DISC = LESZÁM DOLLARDE = FORINT.DEC DOLLARFR = FORINT.TÖRT DURATION = KAMATÉRZ EFFECT = TÉNYLEGES FV = JBÉ FVSCHEDULE = KJÉ INTRATE = KAMATRÁTA IPMT = RRÉSZLET IRR = BMR ISPMT = LRÉSZLETKAMAT MDURATION = MKAMATÉRZ MIRR = MEGTÉRÜLÉS NOMINAL = NÉVLEGES NPER = PER.SZÁM NPV = NMÉ ODDFPRICE = ELTÉRŐ.EÁR ODDFYIELD = ELTÉRŐ.EHOZAM ODDLPRICE = ELTÉRŐ.UÁR ODDLYIELD = ELTÉRŐ.UHOZAM PDURATION = KAMATÉRZ.PER PMT = RÉSZLET PPMT = PRÉSZLET PRICE = ÁR PRICEDISC = ÁR.LESZÁM PRICEMAT = ÁR.LEJÁRAT PV = MÉ RATE = RÁTA RECEIVED = KAPOTT RRI = MR SLN = LCSA SYD = ÉSZÖ TBILLEQ = KJEGY.EGYENÉRT TBILLPRICE = KJEGY.ÁR TBILLYIELD = KJEGY.HOZAM VDB = ÉCSRI XIRR = XBMR XNPV = XNJÉ YIELD = HOZAM YIELDDISC = HOZAM.LESZÁM YIELDMAT = HOZAM.LEJÁRAT ## ## Információs függvények (Information Functions) ## CELL = CELLA ERROR.TYPE = HIBA.TÍPUS INFO = INFÓ ISBLANK = ÜRES ISERR = HIBA.E ISERROR = HIBÁS ISEVEN = PÁROSE ISFORMULA = KÉPLET ISLOGICAL = LOGIKAI ISNA = NINCS ISNONTEXT = NEM.SZÖVEG ISNUMBER = SZÁM ISODD = PÁRATLANE ISREF = HIVATKOZÁS ISTEXT = SZÖVEG.E N = S NA = HIÁNYZIK SHEET = LAP SHEETS = LAPOK TYPE = TÍPUS ## ## Logikai függvények (Logical Functions) ## AND = ÉS FALSE = HAMIS IF = HA IFERROR = HAHIBA IFNA = HAHIÁNYZIK IFS = HAELSŐIGAZ NOT = NEM OR = VAGY SWITCH = ÁTVÁLT TRUE = IGAZ XOR = XVAGY ## ## Keresési és hivatkozási függvények (Lookup & Reference Functions) ## ADDRESS = CÍM AREAS = TERÜLET CHOOSE = VÁLASZT COLUMN = OSZLOP COLUMNS = OSZLOPOK FORMULATEXT = KÉPLETSZÖVEG GETPIVOTDATA = KIMUTATÁSADATOT.VESZ HLOOKUP = VKERES HYPERLINK = HIPERHIVATKOZÁS INDEX = INDEX INDIRECT = INDIREKT LOOKUP = KERES MATCH = HOL.VAN OFFSET = ELTOLÁS ROW = SOR ROWS = SOROK RTD = VIA TRANSPOSE = TRANSZPONÁLÁS VLOOKUP = FKERES *RC = SO ## ## Matematikai és trigonometrikus függvények (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ACOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = ÖSSZESÍT ARABIC = ARAB ASIN = ARCSIN ASINH = ASINH ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ATANH BASE = ALAP CEILING.MATH = PLAFON.MAT CEILING.PRECISE = PLAFON.PONTOS COMBIN = KOMBINÁCIÓK COMBINA = KOMBINÁCIÓK.ISM COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = TIZEDES DEGREES = FOK ECMA.CEILING = ECMA.PLAFON EVEN = PÁROS EXP = KITEVŐ FACT = FAKT FACTDOUBLE = FAKTDUPLA FLOOR.MATH = PADLÓ.MAT FLOOR.PRECISE = PADLÓ.PONTOS GCD = LKO INT = INT ISO.CEILING = ISO.PLAFON LCM = LKT LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = INVERZ.MÁTRIX MMULT = MSZORZAT MOD = MARADÉK MROUND = TÖBBSZ.KEREKÍT MULTINOMIAL = SZORHÁNYFAKT MUNIT = MMÁTRIX ODD = PÁRATLAN PI = PI POWER = HATVÁNY PRODUCT = SZORZAT QUOTIENT = KVÓCIENS RADIANS = RADIÁN RAND = VÉL RANDBETWEEN = VÉLETLEN.KÖZÖTT ROMAN = RÓMAI ROUND = KEREKÍTÉS ROUNDBAHTDOWN = BAHTKEREK.LE ROUNDBAHTUP = BAHTKEREK.FEL ROUNDDOWN = KEREK.LE ROUNDUP = KEREK.FEL SEC = SEC SECH = SECH SERIESSUM = SORÖSSZEG SIGN = ELŐJEL SIN = SIN SINH = SINH SQRT = GYÖK SQRTPI = GYÖKPI SUBTOTAL = RÉSZÖSSZEG SUM = SZUM SUMIF = SZUMHA SUMIFS = SZUMHATÖBB SUMPRODUCT = SZORZATÖSSZEG SUMSQ = NÉGYZETÖSSZEG SUMX2MY2 = SZUMX2BŐLY2 SUMX2PY2 = SZUMX2MEGY2 SUMXMY2 = SZUMXBŐLY2 TAN = TAN TANH = TANH TRUNC = CSONK ## ## Statisztikai függvények (Statistical Functions) ## AVEDEV = ÁTL.ELTÉRÉS AVERAGE = ÁTLAG AVERAGEA = ÁTLAGA AVERAGEIF = ÁTLAGHA AVERAGEIFS = ÁTLAGHATÖBB BETA.DIST = BÉTA.ELOSZL BETA.INV = BÉTA.INVERZ BINOM.DIST = BINOM.ELOSZL BINOM.DIST.RANGE = BINOM.ELOSZL.TART BINOM.INV = BINOM.INVERZ CHISQ.DIST = KHINÉGYZET.ELOSZLÁS CHISQ.DIST.RT = KHINÉGYZET.ELOSZLÁS.JOBB CHISQ.INV = KHINÉGYZET.INVERZ CHISQ.INV.RT = KHINÉGYZET.INVERZ.JOBB CHISQ.TEST = KHINÉGYZET.PRÓBA CONFIDENCE.NORM = MEGBÍZHATÓSÁG.NORM CONFIDENCE.T = MEGBÍZHATÓSÁG.T CORREL = KORREL COUNT = DARAB COUNTA = DARAB2 COUNTBLANK = DARABÜRES COUNTIF = DARABTELI COUNTIFS = DARABHATÖBB COVARIANCE.P = KOVARIANCIA.S COVARIANCE.S = KOVARIANCIA.M DEVSQ = SQ EXPON.DIST = EXP.ELOSZL F.DIST = F.ELOSZL F.DIST.RT = F.ELOSZLÁS.JOBB F.INV = F.INVERZ F.INV.RT = F.INVERZ.JOBB F.TEST = F.PRÓB FISHER = FISHER FISHERINV = INVERZ.FISHER FORECAST.ETS = ELŐREJELZÉS.ESIM FORECAST.ETS.CONFINT = ELŐREJELZÉS.ESIM.KONFINT FORECAST.ETS.SEASONALITY = ELŐREJELZÉS.ESIM.SZEZONALITÁS FORECAST.ETS.STAT = ELŐREJELZÉS.ESIM.STAT FORECAST.LINEAR = ELŐREJELZÉS.LINEÁRIS FREQUENCY = GYAKORISÁG GAMMA = GAMMA GAMMA.DIST = GAMMA.ELOSZL GAMMA.INV = GAMMA.INVERZ GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.PONTOS GAUSS = GAUSS GEOMEAN = MÉRTANI.KÖZÉP GROWTH = NÖV HARMEAN = HARM.KÖZÉP HYPGEOM.DIST = HIPGEOM.ELOSZLÁS INTERCEPT = METSZ KURT = CSÚCSOSSÁG LARGE = NAGY LINEST = LIN.ILL LOGEST = LOG.ILL LOGNORM.DIST = LOGNORM.ELOSZLÁS LOGNORM.INV = LOGNORM.INVERZ MAX = MAX MAXA = MAXA MAXIFS = MAXHA MEDIAN = MEDIÁN MIN = MIN MINA = MIN2 MINIFS = MINHA MODE.MULT = MÓDUSZ.TÖBB MODE.SNGL = MÓDUSZ.EGY NEGBINOM.DIST = NEGBINOM.ELOSZLÁS NORM.DIST = NORM.ELOSZLÁS NORM.INV = NORM.INVERZ NORM.S.DIST = NORM.S.ELOSZLÁS NORM.S.INV = NORM.S.INVERZ PEARSON = PEARSON PERCENTILE.EXC = PERCENTILIS.KIZÁR PERCENTILE.INC = PERCENTILIS.TARTALMAZ PERCENTRANK.EXC = SZÁZALÉKRANG.KIZÁR PERCENTRANK.INC = SZÁZALÉKRANG.TARTALMAZ PERMUT = VARIÁCIÓK PERMUTATIONA = VARIÁCIÓK.ISM PHI = FI POISSON.DIST = POISSON.ELOSZLÁS PROB = VALÓSZÍNŰSÉG QUARTILE.EXC = KVARTILIS.KIZÁR QUARTILE.INC = KVARTILIS.TARTALMAZ RANK.AVG = RANG.ÁTL RANK.EQ = RANG.EGY RSQ = RNÉGYZET SKEW = FERDESÉG SKEW.P = FERDESÉG.P SLOPE = MEREDEKSÉG SMALL = KICSI STANDARDIZE = NORMALIZÁLÁS STDEV.P = SZÓR.S STDEV.S = SZÓR.M STDEVA = SZÓRÁSA STDEVPA = SZÓRÁSPA STEYX = STHIBAYX T.DIST = T.ELOSZL T.DIST.2T = T.ELOSZLÁS.2SZ T.DIST.RT = T.ELOSZLÁS.JOBB T.INV = T.INVERZ T.INV.2T = T.INVERZ.2SZ T.TEST = T.PRÓB TREND = TREND TRIMMEAN = RÉSZÁTLAG VAR.P = VAR.S VAR.S = VAR.M VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.ELOSZLÁS Z.TEST = Z.PRÓB ## ## Szövegműveletekhez használható függvények (Text Functions) ## BAHTTEXT = BAHTSZÖVEG CHAR = KARAKTER CLEAN = TISZTÍT CODE = KÓD CONCAT = FŰZ DOLLAR = FORINT EXACT = AZONOS FIND = SZÖVEG.TALÁL FIXED = FIX ISTHAIDIGIT = ON.THAI.NUMERO LEFT = BAL LEN = HOSSZ LOWER = KISBETŰ MID = KÖZÉP NUMBERSTRING = SZÁM.BETŰVEL NUMBERVALUE = SZÁMÉRTÉK PHONETIC = FONETIKUS PROPER = TNÉV REPLACE = CSERE REPT = SOKSZOR RIGHT = JOBB SEARCH = SZÖVEG.KERES SUBSTITUTE = HELYETTE T = T TEXT = SZÖVEG TEXTJOIN = SZÖVEGÖSSZEFŰZÉS THAIDIGIT = THAISZÁM THAINUMSOUND = THAISZÁMHANG THAINUMSTRING = THAISZÁMKAR THAISTRINGLENGTH = THAIKARHOSSZ TRIM = KIMETSZ UNICHAR = UNIKARAKTER UNICODE = UNICODE UPPER = NAGYBETŰS VALUE = ÉRTÉK ## ## Webes függvények (Web Functions) ## ENCODEURL = URL.KÓDOL FILTERXML = XMLSZŰRÉS WEBSERVICE = WEBSZOLGÁLTATÁS ## ## Kompatibilitási függvények (Compatibility Functions) ## BETADIST = BÉTA.ELOSZLÁS BETAINV = INVERZ.BÉTA BINOMDIST = BINOM.ELOSZLÁS CEILING = PLAFON CHIDIST = KHI.ELOSZLÁS CHIINV = INVERZ.KHI CHITEST = KHI.PRÓBA CONCATENATE = ÖSSZEFŰZ CONFIDENCE = MEGBÍZHATÓSÁG COVAR = KOVAR CRITBINOM = KRITBINOM EXPONDIST = EXP.ELOSZLÁS FDIST = F.ELOSZLÁS FINV = INVERZ.F FLOOR = PADLÓ FORECAST = ELŐREJELZÉS FTEST = F.PRÓBA GAMMADIST = GAMMA.ELOSZLÁS GAMMAINV = INVERZ.GAMMA HYPGEOMDIST = HIPERGEOM.ELOSZLÁS LOGINV = INVERZ.LOG.ELOSZLÁS LOGNORMDIST = LOG.ELOSZLÁS MODE = MÓDUSZ NEGBINOMDIST = NEGBINOM.ELOSZL NORMDIST = NORM.ELOSZL NORMINV = INVERZ.NORM NORMSDIST = STNORMELOSZL NORMSINV = INVERZ.STNORM PERCENTILE = PERCENTILIS PERCENTRANK = SZÁZALÉKRANG POISSON = POISSON QUARTILE = KVARTILIS RANK = SORSZÁM STDEV = SZÓRÁS STDEVP = SZÓRÁSP TDIST = T.ELOSZLÁS TINV = INVERZ.T TTEST = T.PRÓBA VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = Z.PRÓBA ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/it/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Italiano (Italian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #VALORE! REF = #RIF! NAME = #NOME? NUM NA = #N/D ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/it/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Italiano (Italian) ## ############################################################ ## ## Funzioni cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBRO.KPI.CUBO CUBEMEMBER = MEMBRO.CUBO CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO CUBESET = SET.CUBO CUBESETCOUNT = CONTA.SET.CUBO CUBEVALUE = VALORE.CUBO ## ## Funzioni di database (Database Functions) ## DAVERAGE = DB.MEDIA DCOUNT = DB.CONTA.NUMERI DCOUNTA = DB.CONTA.VALORI DGET = DB.VALORI DMAX = DB.MAX DMIN = DB.MIN DPRODUCT = DB.PRODOTTO DSTDEV = DB.DEV.ST DSTDEVP = DB.DEV.ST.POP DSUM = DB.SOMMA DVAR = DB.VAR DVARP = DB.VAR.POP ## ## Funzioni data e ora (Date & Time Functions) ## DATE = DATA DATEDIF = DATA.DIFF DATESTRING = DATA.STRINGA DATEVALUE = DATA.VALORE DAY = GIORNO DAYS = GIORNI DAYS360 = GIORNO360 EDATE = DATA.MESE EOMONTH = FINE.MESE HOUR = ORA ISOWEEKNUM = NUM.SETTIMANA.ISO MINUTE = MINUTO MONTH = MESE NETWORKDAYS = GIORNI.LAVORATIVI.TOT NETWORKDAYS.INTL = GIORNI.LAVORATIVI.TOT.INTL NOW = ADESSO SECOND = SECONDO THAIDAYOFWEEK = THAIGIORNODELLASETTIMANA THAIMONTHOFYEAR = THAIMESEDELLANNO THAIYEAR = THAIANNO TIME = ORARIO TIMEVALUE = ORARIO.VALORE TODAY = OGGI WEEKDAY = GIORNO.SETTIMANA WEEKNUM = NUM.SETTIMANA WORKDAY = GIORNO.LAVORATIVO WORKDAY.INTL = GIORNO.LAVORATIVO.INTL YEAR = ANNO YEARFRAC = FRAZIONE.ANNO ## ## Funzioni ingegneristiche (Engineering Functions) ## BESSELI = BESSEL.I BESSELJ = BESSEL.J BESSELK = BESSEL.K BESSELY = BESSEL.Y BIN2DEC = BINARIO.DECIMALE BIN2HEX = BINARIO.HEX BIN2OCT = BINARIO.OCT BITAND = BITAND BITLSHIFT = BIT.SPOSTA.SX BITOR = BITOR BITRSHIFT = BIT.SPOSTA.DX BITXOR = BITXOR COMPLEX = COMPLESSO CONVERT = CONVERTI DEC2BIN = DECIMALE.BINARIO DEC2HEX = DECIMALE.HEX DEC2OCT = DECIMALE.OCT DELTA = DELTA ERF = FUNZ.ERRORE ERF.PRECISE = FUNZ.ERRORE.PRECISA ERFC = FUNZ.ERRORE.COMP ERFC.PRECISE = FUNZ.ERRORE.COMP.PRECISA GESTEP = SOGLIA HEX2BIN = HEX.BINARIO HEX2DEC = HEX.DECIMALE HEX2OCT = HEX.OCT IMABS = COMP.MODULO IMAGINARY = COMP.IMMAGINARIO IMARGUMENT = COMP.ARGOMENTO IMCONJUGATE = COMP.CONIUGATO IMCOS = COMP.COS IMCOSH = COMP.COSH IMCOT = COMP.COT IMCSC = COMP.CSC IMCSCH = COMP.CSCH IMDIV = COMP.DIV IMEXP = COMP.EXP IMLN = COMP.LN IMLOG10 = COMP.LOG10 IMLOG2 = COMP.LOG2 IMPOWER = COMP.POTENZA IMPRODUCT = COMP.PRODOTTO IMREAL = COMP.PARTE.REALE IMSEC = COMP.SEC IMSECH = COMP.SECH IMSIN = COMP.SEN IMSINH = COMP.SENH IMSQRT = COMP.RADQ IMSUB = COMP.DIFF IMSUM = COMP.SOMMA IMTAN = COMP.TAN OCT2BIN = OCT.BINARIO OCT2DEC = OCT.DECIMALE OCT2HEX = OCT.HEX ## ## Funzioni finanziarie (Financial Functions) ## ACCRINT = INT.MATURATO.PER ACCRINTM = INT.MATURATO.SCAD AMORDEGRC = AMMORT.DEGR AMORLINC = AMMORT.PER COUPDAYBS = GIORNI.CED.INIZ.LIQ COUPDAYS = GIORNI.CED COUPDAYSNC = GIORNI.CED.NUOVA COUPNCD = DATA.CED.SUCC COUPNUM = NUM.CED COUPPCD = DATA.CED.PREC CUMIPMT = INT.CUMUL CUMPRINC = CAP.CUM DB = AMMORT.FISSO DDB = AMMORT DISC = TASSO.SCONTO DOLLARDE = VALUTA.DEC DOLLARFR = VALUTA.FRAZ DURATION = DURATA EFFECT = EFFETTIVO FV = VAL.FUT FVSCHEDULE = VAL.FUT.CAPITALE INTRATE = TASSO.INT IPMT = INTERESSI IRR = TIR.COST ISPMT = INTERESSE.RATA MDURATION = DURATA.M MIRR = TIR.VAR NOMINAL = NOMINALE NPER = NUM.RATE NPV = VAN ODDFPRICE = PREZZO.PRIMO.IRR ODDFYIELD = REND.PRIMO.IRR ODDLPRICE = PREZZO.ULTIMO.IRR ODDLYIELD = REND.ULTIMO.IRR PDURATION = DURATA.P PMT = RATA PPMT = P.RATA PRICE = PREZZO PRICEDISC = PREZZO.SCONT PRICEMAT = PREZZO.SCAD PV = VA RATE = TASSO RECEIVED = RICEV.SCAD RRI = RIT.INVEST.EFFETT SLN = AMMORT.COST SYD = AMMORT.ANNUO TBILLEQ = BOT.EQUIV TBILLPRICE = BOT.PREZZO TBILLYIELD = BOT.REND VDB = AMMORT.VAR XIRR = TIR.X XNPV = VAN.X YIELD = REND YIELDDISC = REND.TITOLI.SCONT YIELDMAT = REND.SCAD ## ## Funzioni relative alle informazioni (Information Functions) ## CELL = CELLA ERROR.TYPE = ERRORE.TIPO INFO = AMBIENTE.INFO ISBLANK = VAL.VUOTO ISERR = VAL.ERR ISERROR = VAL.ERRORE ISEVEN = VAL.PARI ISFORMULA = VAL.FORMULA ISLOGICAL = VAL.LOGICO ISNA = VAL.NON.DISP ISNONTEXT = VAL.NON.TESTO ISNUMBER = VAL.NUMERO ISODD = VAL.DISPARI ISREF = VAL.RIF ISTEXT = VAL.TESTO N = NUM NA = NON.DISP SHEET = FOGLIO SHEETS = FOGLI TYPE = TIPO ## ## Funzioni logiche (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SE.ERRORE IFNA = SE.NON.DISP. IFS = PIÙ.SE NOT = NON OR = O SWITCH = SWITCH TRUE = VERO XOR = XOR ## ## Funzioni di ricerca e di riferimento (Lookup & Reference Functions) ## ADDRESS = INDIRIZZO AREAS = AREE CHOOSE = SCEGLI COLUMN = RIF.COLONNA COLUMNS = COLONNE FORMULATEXT = TESTO.FORMULA GETPIVOTDATA = INFO.DATI.TAB.PIVOT HLOOKUP = CERCA.ORIZZ HYPERLINK = COLLEG.IPERTESTUALE INDEX = INDICE INDIRECT = INDIRETTO LOOKUP = CERCA MATCH = CONFRONTA OFFSET = SCARTO ROW = RIF.RIGA ROWS = RIGHE RTD = DATITEMPOREALE TRANSPOSE = MATR.TRASPOSTA VLOOKUP = CERCA.VERT ## ## Funzioni matematiche e trigonometriche (Math & Trig Functions) ## ABS = ASS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = AGGREGA ARABIC = ARABO ASIN = ARCSEN ASINH = ARCSENH ATAN = ARCTAN ATAN2 = ARCTAN.2 ATANH = ARCTANH BASE = BASE CEILING.MATH = ARROTONDA.ECCESSO.MAT CEILING.PRECISE = ARROTONDA.ECCESSO.PRECISA COMBIN = COMBINAZIONE COMBINA = COMBINAZIONE.VALORI COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMALE DEGREES = GRADI ECMA.CEILING = ECMA.ARROTONDA.ECCESSO EVEN = PARI EXP = EXP FACT = FATTORIALE FACTDOUBLE = FATT.DOPPIO FLOOR.MATH = ARROTONDA.DIFETTO.MAT FLOOR.PRECISE = ARROTONDA.DIFETTO.PRECISA GCD = MCD INT = INT ISO.CEILING = ISO.ARROTONDA.ECCESSO LCM = MCM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATR.DETERM MINVERSE = MATR.INVERSA MMULT = MATR.PRODOTTO MOD = RESTO MROUND = ARROTONDA.MULTIPLO MULTINOMIAL = MULTINOMIALE MUNIT = MATR.UNIT ODD = DISPARI PI = PI.GRECO POWER = POTENZA PRODUCT = PRODOTTO QUOTIENT = QUOZIENTE RADIANS = RADIANTI RAND = CASUALE RANDBETWEEN = CASUALE.TRA ROMAN = ROMANO ROUND = ARROTONDA ROUNDBAHTDOWN = ARROTBAHTGIU ROUNDBAHTUP = ARROTBAHTSU ROUNDDOWN = ARROTONDA.PER.DIF ROUNDUP = ARROTONDA.PER.ECC SEC = SEC SECH = SECH SERIESSUM = SOMMA.SERIE SIGN = SEGNO SIN = SEN SINH = SENH SQRT = RADQ SQRTPI = RADQ.PI.GRECO SUBTOTAL = SUBTOTALE SUM = SOMMA SUMIF = SOMMA.SE SUMIFS = SOMMA.PIÙ.SE SUMPRODUCT = MATR.SOMMA.PRODOTTO SUMSQ = SOMMA.Q SUMX2MY2 = SOMMA.DIFF.Q SUMX2PY2 = SOMMA.SOMMA.Q SUMXMY2 = SOMMA.Q.DIFF TAN = TAN TANH = TANH TRUNC = TRONCA ## ## Funzioni statistiche (Statistical Functions) ## AVEDEV = MEDIA.DEV AVERAGE = MEDIA AVERAGEA = MEDIA.VALORI AVERAGEIF = MEDIA.SE AVERAGEIFS = MEDIA.PIÙ.SE BETA.DIST = DISTRIB.BETA.N BETA.INV = INV.BETA.N BINOM.DIST = DISTRIB.BINOM.N BINOM.DIST.RANGE = INTERVALLO.DISTRIB.BINOM.N. BINOM.INV = INV.BINOM CHISQ.DIST = DISTRIB.CHI.QUAD CHISQ.DIST.RT = DISTRIB.CHI.QUAD.DS CHISQ.INV = INV.CHI.QUAD CHISQ.INV.RT = INV.CHI.QUAD.DS CHISQ.TEST = TEST.CHI.QUAD CONFIDENCE.NORM = CONFIDENZA.NORM CONFIDENCE.T = CONFIDENZA.T CORREL = CORRELAZIONE COUNT = CONTA.NUMERI COUNTA = CONTA.VALORI COUNTBLANK = CONTA.VUOTE COUNTIF = CONTA.SE COUNTIFS = CONTA.PIÙ.SE COVARIANCE.P = COVARIANZA.P COVARIANCE.S = COVARIANZA.C DEVSQ = DEV.Q EXPON.DIST = DISTRIB.EXP.N F.DIST = DISTRIBF F.DIST.RT = DISTRIB.F.DS F.INV = INVF F.INV.RT = INV.F.DS F.TEST = TESTF FISHER = FISHER FISHERINV = INV.FISHER FORECAST.ETS = PREVISIONE.ETS FORECAST.ETS.CONFINT = PREVISIONE.ETS.INTCONF FORECAST.ETS.SEASONALITY = PREVISIONE.ETS.STAGIONALITÀ FORECAST.ETS.STAT = PREVISIONE.ETS.STAT FORECAST.LINEAR = PREVISIONE.LINEARE FREQUENCY = FREQUENZA GAMMA = GAMMA GAMMA.DIST = DISTRIB.GAMMA.N GAMMA.INV = INV.GAMMA.N GAMMALN = LN.GAMMA GAMMALN.PRECISE = LN.GAMMA.PRECISA GAUSS = GAUSS GEOMEAN = MEDIA.GEOMETRICA GROWTH = CRESCITA HARMEAN = MEDIA.ARMONICA HYPGEOM.DIST = DISTRIB.IPERGEOM.N INTERCEPT = INTERCETTA KURT = CURTOSI LARGE = GRANDE LINEST = REGR.LIN LOGEST = REGR.LOG LOGNORM.DIST = DISTRIB.LOGNORM.N LOGNORM.INV = INV.LOGNORM.N MAX = MAX MAXA = MAX.VALORI MAXIFS = MAX.PIÙ.SE MEDIAN = MEDIANA MIN = MIN MINA = MIN.VALORI MINIFS = MIN.PIÙ.SE MODE.MULT = MODA.MULT MODE.SNGL = MODA.SNGL NEGBINOM.DIST = DISTRIB.BINOM.NEG.N NORM.DIST = DISTRIB.NORM.N NORM.INV = INV.NORM.N NORM.S.DIST = DISTRIB.NORM.ST.N NORM.S.INV = INV.NORM.S PEARSON = PEARSON PERCENTILE.EXC = ESC.PERCENTILE PERCENTILE.INC = INC.PERCENTILE PERCENTRANK.EXC = ESC.PERCENT.RANGO PERCENTRANK.INC = INC.PERCENT.RANGO PERMUT = PERMUTAZIONE PERMUTATIONA = PERMUTAZIONE.VALORI PHI = PHI POISSON.DIST = DISTRIB.POISSON PROB = PROBABILITÀ QUARTILE.EXC = ESC.QUARTILE QUARTILE.INC = INC.QUARTILE RANK.AVG = RANGO.MEDIA RANK.EQ = RANGO.UG RSQ = RQ SKEW = ASIMMETRIA SKEW.P = ASIMMETRIA.P SLOPE = PENDENZA SMALL = PICCOLO STANDARDIZE = NORMALIZZA STDEV.P = DEV.ST.P STDEV.S = DEV.ST.C STDEVA = DEV.ST.VALORI STDEVPA = DEV.ST.POP.VALORI STEYX = ERR.STD.YX T.DIST = DISTRIB.T.N T.DIST.2T = DISTRIB.T.2T T.DIST.RT = DISTRIB.T.DS T.INV = INVT T.INV.2T = INV.T.2T T.TEST = TESTT TREND = TENDENZA TRIMMEAN = MEDIA.TRONCATA VAR.P = VAR.P VAR.S = VAR.C VARA = VAR.VALORI VARPA = VAR.POP.VALORI WEIBULL.DIST = DISTRIB.WEIBULL Z.TEST = TESTZ ## ## Funzioni di testo (Text Functions) ## BAHTTEXT = BAHTTESTO CHAR = CODICE.CARATT CLEAN = LIBERA CODE = CODICE CONCAT = CONCAT DOLLAR = VALUTA EXACT = IDENTICO FIND = TROVA FIXED = FISSO ISTHAIDIGIT = ÈTHAICIFRA LEFT = SINISTRA LEN = LUNGHEZZA LOWER = MINUSC MID = STRINGA.ESTRAI NUMBERSTRING = NUMERO.STRINGA NUMBERVALUE = NUMERO.VALORE PHONETIC = FURIGANA PROPER = MAIUSC.INIZ REPLACE = RIMPIAZZA REPT = RIPETI RIGHT = DESTRA SEARCH = RICERCA SUBSTITUTE = SOSTITUISCI T = T TEXT = TESTO TEXTJOIN = TESTO.UNISCI THAIDIGIT = THAICIFRA THAINUMSOUND = THAINUMSUONO THAINUMSTRING = THAISZÁMKAR THAISTRINGLENGTH = THAILUNGSTRINGA TRIM = ANNULLA.SPAZI UNICHAR = CARATT.UNI UNICODE = UNICODE UPPER = MAIUSC VALUE = VALORE ## ## Funzioni Web (Web Functions) ## ENCODEURL = CODIFICA.URL FILTERXML = FILTRO.XML WEBSERVICE = SERVIZIO.WEB ## ## Funzioni di compatibilità (Compatibility Functions) ## BETADIST = DISTRIB.BETA BETAINV = INV.BETA BINOMDIST = DISTRIB.BINOM CEILING = ARROTONDA.ECCESSO CHIDIST = DISTRIB.CHI CHIINV = INV.CHI CHITEST = TEST.CHI CONCATENATE = CONCATENA CONFIDENCE = CONFIDENZA COVAR = COVARIANZA CRITBINOM = CRIT.BINOM EXPONDIST = DISTRIB.EXP FDIST = DISTRIB.F FINV = INV.F FLOOR = ARROTONDA.DIFETTO FORECAST = PREVISIONE FTEST = TEST.F GAMMADIST = DISTRIB.GAMMA GAMMAINV = INV.GAMMA HYPGEOMDIST = DISTRIB.IPERGEOM LOGINV = INV.LOGNORM LOGNORMDIST = DISTRIB.LOGNORM MODE = MODA NEGBINOMDIST = DISTRIB.BINOM.NEG NORMDIST = DISTRIB.NORM NORMINV = INV.NORM NORMSDIST = DISTRIB.NORM.ST NORMSINV = INV.NORM.ST PERCENTILE = PERCENTILE PERCENTRANK = PERCENT.RANGO POISSON = POISSON QUARTILE = QUARTILE RANK = RANGO STDEV = DEV.ST STDEVP = DEV.ST.POP TDIST = DISTRIB.T TINV = INV.T TTEST = TEST.T VAR = VAR VARP = VAR.POP WEIBULL = WEIBULL ZTEST = TEST.Z ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/nb/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Norsk Bokmål (Norwegian Bokmål) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #VERDI! REF NAME = #NAVN? NUM NA = #N/D ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/nb/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Norsk Bokmål (Norwegian Bokmål) ## ############################################################ ## ## Kubefunksjoner (Cube Functions) ## CUBEKPIMEMBER = KUBEKPIMEDLEM CUBEMEMBER = KUBEMEDLEM CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP CUBERANKEDMEMBER = KUBERANGERTMEDLEM CUBESET = KUBESETT CUBESETCOUNT = KUBESETTANTALL CUBEVALUE = KUBEVERDI ## ## Databasefunksjoner (Database Functions) ## DAVERAGE = DGJENNOMSNITT DCOUNT = DANTALL DCOUNTA = DANTALLA DGET = DHENT DMAX = DMAKS DMIN = DMIN DPRODUCT = DPRODUKT DSTDEV = DSTDAV DSTDEVP = DSTDAVP DSUM = DSUMMER DVAR = DVARIANS DVARP = DVARIANSP ## ## Dato- og tidsfunksjoner (Date & Time Functions) ## DATE = DATO DATEDIF = DATODIFF DATESTRING = DATOSTRENG DATEVALUE = DATOVERDI DAY = DAG DAYS = DAGER DAYS360 = DAGER360 EDATE = DAG.ETTER EOMONTH = MÅNEDSSLUTT HOUR = TIME ISOWEEKNUM = ISOUKENR MINUTE = MINUTT MONTH = MÅNED NETWORKDAYS = NETT.ARBEIDSDAGER NETWORKDAYS.INTL = NETT.ARBEIDSDAGER.INTL NOW = NÅ SECOND = SEKUND THAIDAYOFWEEK = THAIUKEDAG THAIMONTHOFYEAR = THAIMÅNED THAIYEAR = THAIÅR TIME = TID TIMEVALUE = TIDSVERDI TODAY = IDAG WEEKDAY = UKEDAG WEEKNUM = UKENR WORKDAY = ARBEIDSDAG WORKDAY.INTL = ARBEIDSDAG.INTL YEAR = ÅR YEARFRAC = ÅRDEL ## ## Tekniske funksjoner (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINTILDES BIN2HEX = BINTILHEKS BIN2OCT = BINTILOKT BITAND = BITOG BITLSHIFT = BITVFORSKYV BITOR = BITELLER BITRSHIFT = BITHFORSKYV BITXOR = BITEKSKLUSIVELLER COMPLEX = KOMPLEKS CONVERT = KONVERTER DEC2BIN = DESTILBIN DEC2HEX = DESTILHEKS DEC2OCT = DESTILOKT DELTA = DELTA ERF = FEILF ERF.PRECISE = FEILF.PRESIS ERFC = FEILFK ERFC.PRECISE = FEILFK.PRESIS GESTEP = GRENSEVERDI HEX2BIN = HEKSTILBIN HEX2DEC = HEKSTILDES HEX2OCT = HEKSTILOKT IMABS = IMABS IMAGINARY = IMAGINÆR IMARGUMENT = IMARGUMENT IMCONJUGATE = IMKONJUGERT IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEKSP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMOPPHØY IMPRODUCT = IMPRODUKT IMREAL = IMREELL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMROT IMSUB = IMSUB IMSUM = IMSUMMER IMTAN = IMTAN OCT2BIN = OKTTILBIN OCT2DEC = OKTTILDES OCT2HEX = OKTTILHEKS ## ## Økonomiske funksjoner (Financial Functions) ## ACCRINT = PÅLØPT.PERIODISK.RENTE ACCRINTM = PÅLØPT.FORFALLSRENTE AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = OBLIG.DAGER.FF COUPDAYS = OBLIG.DAGER COUPDAYSNC = OBLIG.DAGER.NF COUPNCD = OBLIG.DAGER.EF COUPNUM = OBLIG.ANTALL COUPPCD = OBLIG.DAG.FORRIGE CUMIPMT = SAMLET.RENTE CUMPRINC = SAMLET.HOVEDSTOL DB = DAVSKR DDB = DEGRAVS DISC = DISKONTERT DOLLARDE = DOLLARDE DOLLARFR = DOLLARBR DURATION = VARIGHET EFFECT = EFFEKTIV.RENTE FV = SLUTTVERDI FVSCHEDULE = SVPLAN INTRATE = RENTESATS IPMT = RAVDRAG IRR = IR ISPMT = ER.AVDRAG MDURATION = MVARIGHET MIRR = MODIR NOMINAL = NOMINELL NPER = PERIODER NPV = NNV ODDFPRICE = AVVIKFP.PRIS ODDFYIELD = AVVIKFP.AVKASTNING ODDLPRICE = AVVIKSP.PRIS ODDLYIELD = AVVIKSP.AVKASTNING PDURATION = PVARIGHET PMT = AVDRAG PPMT = AMORT PRICE = PRIS PRICEDISC = PRIS.DISKONTERT PRICEMAT = PRIS.FORFALL PV = NÅVERDI RATE = RENTE RECEIVED = MOTTATT.AVKAST RRI = REALISERT.AVKASTNING SLN = LINAVS SYD = ÅRSAVS TBILLEQ = TBILLEKV TBILLPRICE = TBILLPRIS TBILLYIELD = TBILLAVKASTNING VDB = VERDIAVS XIRR = XIR XNPV = XNNV YIELD = AVKAST YIELDDISC = AVKAST.DISKONTERT YIELDMAT = AVKAST.FORFALL ## ## Informasjonsfunksjoner (Information Functions) ## CELL = CELLE ERROR.TYPE = FEIL.TYPE INFO = INFO ISBLANK = ERTOM ISERR = ERF ISERROR = ERFEIL ISEVEN = ERPARTALL ISFORMULA = ERFORMEL ISLOGICAL = ERLOGISK ISNA = ERIT ISNONTEXT = ERIKKETEKST ISNUMBER = ERTALL ISODD = ERODDE ISREF = ERREF ISTEXT = ERTEKST N = N NA = IT SHEET = ARK SHEETS = ANTALL.ARK TYPE = VERDITYPE ## ## Logiske funksjoner (Logical Functions) ## AND = OG FALSE = USANN IF = HVIS IFERROR = HVISFEIL IFNA = HVIS.IT IFS = HVIS.SETT NOT = IKKE OR = ELLER SWITCH = BRYTER TRUE = SANN XOR = EKSKLUSIVELLER ## ## Oppslag- og referansefunksjoner (Lookup & Reference Functions) ## ADDRESS = ADRESSE AREAS = OMRÅDER CHOOSE = VELG COLUMN = KOLONNE COLUMNS = KOLONNER FORMULATEXT = FORMELTEKST GETPIVOTDATA = HENTPIVOTDATA HLOOKUP = FINN.KOLONNE HYPERLINK = HYPERKOBLING INDEX = INDEKS INDIRECT = INDIREKTE LOOKUP = SLÅ.OPP MATCH = SAMMENLIGNE OFFSET = FORSKYVNING ROW = RAD ROWS = RADER RTD = RTD TRANSPOSE = TRANSPONER VLOOKUP = FINN.RAD *RC = RK ## ## Matematikk- og trigonometrifunksjoner (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = MENGDE ARABIC = ARABISK ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ARCTANH BASE = GRUNNTALL CEILING.MATH = AVRUND.GJELDENDE.MULTIPLUM.OPP.MATEMATISK CEILING.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.PRESIS COMBIN = KOMBINASJON COMBINA = KOMBINASJONA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DESIMAL DEGREES = GRADER ECMA.CEILING = ECMA.AVRUND.GJELDENDE.MULTIPLUM EVEN = AVRUND.TIL.PARTALL EXP = EKSP FACT = FAKULTET FACTDOUBLE = DOBBELFAKT FLOOR.MATH = AVRUND.GJELDENDE.MULTIPLUM.NED.MATEMATISK FLOOR.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.NED.PRESIS GCD = SFF INT = HELTALL ISO.CEILING = ISO.AVRUND.GJELDENDE.MULTIPLUM LCM = MFM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERS MMULT = MMULT MOD = REST MROUND = MRUND MULTINOMIAL = MULTINOMINELL MUNIT = MENHET ODD = AVRUND.TIL.ODDETALL PI = PI POWER = OPPHØYD.I PRODUCT = PRODUKT QUOTIENT = KVOTIENT RADIANS = RADIANER RAND = TILFELDIG RANDBETWEEN = TILFELDIGMELLOM ROMAN = ROMERTALL ROUND = AVRUND ROUNDBAHTDOWN = RUNDAVBAHTNEDOVER ROUNDBAHTUP = RUNDAVBAHTOPPOVER ROUNDDOWN = AVRUND.NED ROUNDUP = AVRUND.OPP SEC = SEC SECH = SECH SERIESSUM = SUMMER.REKKE SIGN = FORTEGN SIN = SIN SINH = SINH SQRT = ROT SQRTPI = ROTPI SUBTOTAL = DELSUM SUM = SUMMER SUMIF = SUMMERHVIS SUMIFS = SUMMER.HVIS.SETT SUMPRODUCT = SUMMERPRODUKT SUMSQ = SUMMERKVADRAT SUMX2MY2 = SUMMERX2MY2 SUMX2PY2 = SUMMERX2PY2 SUMXMY2 = SUMMERXMY2 TAN = TAN TANH = TANH TRUNC = AVKORT ## ## Statistiske funksjoner (Statistical Functions) ## AVEDEV = GJENNOMSNITTSAVVIK AVERAGE = GJENNOMSNITT AVERAGEA = GJENNOMSNITTA AVERAGEIF = GJENNOMSNITTHVIS AVERAGEIFS = GJENNOMSNITT.HVIS.SETT BETA.DIST = BETA.FORDELING.N BETA.INV = BETA.INV BINOM.DIST = BINOM.FORDELING.N BINOM.DIST.RANGE = BINOM.FORDELING.OMRÅDE BINOM.INV = BINOM.INV CHISQ.DIST = KJIKVADRAT.FORDELING CHISQ.DIST.RT = KJIKVADRAT.FORDELING.H CHISQ.INV = KJIKVADRAT.INV CHISQ.INV.RT = KJIKVADRAT.INV.H CHISQ.TEST = KJIKVADRAT.TEST CONFIDENCE.NORM = KONFIDENS.NORM CONFIDENCE.T = KONFIDENS.T CORREL = KORRELASJON COUNT = ANTALL COUNTA = ANTALLA COUNTBLANK = TELLBLANKE COUNTIF = ANTALL.HVIS COUNTIFS = ANTALL.HVIS.SETT COVARIANCE.P = KOVARIANS.P COVARIANCE.S = KOVARIANS.S DEVSQ = AVVIK.KVADRERT EXPON.DIST = EKSP.FORDELING.N F.DIST = F.FORDELING F.DIST.RT = F.FORDELING.H F.INV = F.INV F.INV.RT = F.INV.H F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PROGNOSE.ETS FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SESONGAVHENGIGHET FORECAST.ETS.STAT = PROGNOSE.ETS.STAT FORECAST.LINEAR = PROGNOSE.LINEÆR FREQUENCY = FREKVENS GAMMA = GAMMA GAMMA.DIST = GAMMA.FORDELING GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.PRESIS GAUSS = GAUSS GEOMEAN = GJENNOMSNITT.GEOMETRISK GROWTH = VEKST HARMEAN = GJENNOMSNITT.HARMONISK HYPGEOM.DIST = HYPGEOM.FORDELING.N INTERCEPT = SKJÆRINGSPUNKT KURT = KURT LARGE = N.STØRST LINEST = RETTLINJE LOGEST = KURVE LOGNORM.DIST = LOGNORM.FORDELING LOGNORM.INV = LOGNORM.INV MAX = STØRST MAXA = MAKSA MAXIFS = MAKS.HVIS.SETT MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MIN.HVIS.SETT MODE.MULT = MODUS.MULT MODE.SNGL = MODUS.SNGL NEGBINOM.DIST = NEGBINOM.FORDELING.N NORM.DIST = NORM.FORDELING NORM.INV = NORM.INV NORM.S.DIST = NORM.S.FORDELING NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERSENTIL.EKS PERCENTILE.INC = PERSENTIL.INK PERCENTRANK.EXC = PROSENTDEL.EKS PERCENTRANK.INC = PROSENTDEL.INK PERMUT = PERMUTER PERMUTATIONA = PERMUTASJONA PHI = PHI POISSON.DIST = POISSON.FORDELING PROB = SANNSYNLIG QUARTILE.EXC = KVARTIL.EKS QUARTILE.INC = KVARTIL.INK RANK.AVG = RANG.GJSN RANK.EQ = RANG.EKV RSQ = RKVADRAT SKEW = SKJEVFORDELING SKEW.P = SKJEVFORDELING.P SLOPE = STIGNINGSTALL SMALL = N.MINST STANDARDIZE = NORMALISER STDEV.P = STDAV.P STDEV.S = STDAV.S STDEVA = STDAVVIKA STDEVPA = STDAVVIKPA STEYX = STANDARDFEIL T.DIST = T.FORDELING T.DIST.2T = T.FORDELING.2T T.DIST.RT = T.FORDELING.H T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = TREND TRIMMEAN = TRIMMET.GJENNOMSNITT VAR.P = VARIANS.P VAR.S = VARIANS.S VARA = VARIANSA VARPA = VARIANSPA WEIBULL.DIST = WEIBULL.DIST.N Z.TEST = Z.TEST ## ## Tekstfunksjoner (Text Functions) ## ASC = STIGENDE BAHTTEXT = BAHTTEKST CHAR = TEGNKODE CLEAN = RENSK CODE = KODE CONCAT = KJED.SAMMEN DOLLAR = VALUTA EXACT = EKSAKT FIND = FINN FIXED = FASTSATT ISTHAIDIGIT = ERTHAISIFFER LEFT = VENSTRE LEN = LENGDE LOWER = SMÅ MID = DELTEKST NUMBERSTRING = TALLSTRENG NUMBERVALUE = TALLVERDI PHONETIC = FURIGANA PROPER = STOR.FORBOKSTAV REPLACE = ERSTATT REPT = GJENTA RIGHT = HØYRE SEARCH = SØK SUBSTITUTE = BYTT.UT T = T TEXT = TEKST TEXTJOIN = TEKST.KOMBINER THAIDIGIT = THAISIFFER THAINUMSOUND = THAINUMLYD THAINUMSTRING = THAINUMSTRENG THAISTRINGLENGTH = THAISTRENGLENGDE TRIM = TRIMME UNICHAR = UNICODETEGN UNICODE = UNICODE UPPER = STORE VALUE = VERDI ## ## Nettfunksjoner (Web Functions) ## ENCODEURL = URL.KODE FILTERXML = FILTRERXML WEBSERVICE = NETTJENESTE ## ## Kompatibilitetsfunksjoner (Compatibility Functions) ## BETADIST = BETA.FORDELING BETAINV = INVERS.BETA.FORDELING BINOMDIST = BINOM.FORDELING CEILING = AVRUND.GJELDENDE.MULTIPLUM CHIDIST = KJI.FORDELING CHIINV = INVERS.KJI.FORDELING CHITEST = KJI.TEST CONCATENATE = KJEDE.SAMMEN CONFIDENCE = KONFIDENS COVAR = KOVARIANS CRITBINOM = GRENSE.BINOM EXPONDIST = EKSP.FORDELING FDIST = FFORDELING FINV = FFORDELING.INVERS FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED FORECAST = PROGNOSE FTEST = FTEST GAMMADIST = GAMMAFORDELING GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOM.FORDELING LOGINV = LOGINV LOGNORMDIST = LOGNORMFORD MODE = MODUS NEGBINOMDIST = NEGBINOM.FORDELING NORMDIST = NORMALFORDELING NORMINV = NORMINV NORMSDIST = NORMSFORDELING NORMSINV = NORMSINV PERCENTILE = PERSENTIL PERCENTRANK = PROSENTDEL POISSON = POISSON QUARTILE = KVARTIL RANK = RANG STDEV = STDAV STDEVP = STDAVP TDIST = TFORDELING TINV = TINV TTEST = TTEST VAR = VARIANS VARP = VARIANSP WEIBULL = WEIBULL.FORDELING ZTEST = ZTEST ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/nl/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Nederlands (Dutch) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #LEEG! DIV0 = #DEEL/0! VALUE = #WAARDE! REF = #VERW! NAME = #NAAM? NUM = #GETAL! NA = #N/B ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/nl/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Nederlands (Dutch) ## ############################################################ ## ## Kubusfuncties (Cube Functions) ## CUBEKPIMEMBER = KUBUSKPILID CUBEMEMBER = KUBUSLID CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP CUBERANKEDMEMBER = KUBUSGERANGSCHIKTLID CUBESET = KUBUSSET CUBESETCOUNT = KUBUSSETAANTAL CUBEVALUE = KUBUSWAARDE ## ## Databasefuncties (Database Functions) ## DAVERAGE = DBGEMIDDELDE DCOUNT = DBAANTAL DCOUNTA = DBAANTALC DGET = DBLEZEN DMAX = DBMAX DMIN = DBMIN DPRODUCT = DBPRODUCT DSTDEV = DBSTDEV DSTDEVP = DBSTDEVP DSUM = DBSOM DVAR = DBVAR DVARP = DBVARP ## ## Datum- en tijdfuncties (Date & Time Functions) ## DATE = DATUM DATEDIF = DATUMVERSCHIL DATESTRING = DATUMNOTATIE DATEVALUE = DATUMWAARDE DAY = DAG DAYS = DAGEN DAYS360 = DAGEN360 EDATE = ZELFDE.DAG EOMONTH = LAATSTE.DAG HOUR = UUR ISOWEEKNUM = ISO.WEEKNUMMER MINUTE = MINUUT MONTH = MAAND NETWORKDAYS = NETTO.WERKDAGEN NETWORKDAYS.INTL = NETWERKDAGEN.INTL NOW = NU SECOND = SECONDE THAIDAYOFWEEK = THAIS.WEEKDAG THAIMONTHOFYEAR = THAIS.MAAND.VAN.JAAR THAIYEAR = THAIS.JAAR TIME = TIJD TIMEVALUE = TIJDWAARDE TODAY = VANDAAG WEEKDAY = WEEKDAG WEEKNUM = WEEKNUMMER WORKDAY = WERKDAG WORKDAY.INTL = WERKDAG.INTL YEAR = JAAR YEARFRAC = JAAR.DEEL ## ## Technische functies (Engineering Functions) ## BESSELI = BESSEL.I BESSELJ = BESSEL.J BESSELK = BESSEL.K BESSELY = BESSEL.Y BIN2DEC = BIN.N.DEC BIN2HEX = BIN.N.HEX BIN2OCT = BIN.N.OCT BITAND = BIT.EN BITLSHIFT = BIT.VERSCHUIF.LINKS BITOR = BIT.OF BITRSHIFT = BIT.VERSCHUIF.RECHTS BITXOR = BIT.EX.OF COMPLEX = COMPLEX CONVERT = CONVERTEREN DEC2BIN = DEC.N.BIN DEC2HEX = DEC.N.HEX DEC2OCT = DEC.N.OCT DELTA = DELTA ERF = FOUTFUNCTIE ERF.PRECISE = FOUTFUNCTIE.NAUWKEURIG ERFC = FOUT.COMPLEMENT ERFC.PRECISE = FOUT.COMPLEMENT.NAUWKEURIG GESTEP = GROTER.DAN HEX2BIN = HEX.N.BIN HEX2DEC = HEX.N.DEC HEX2OCT = HEX.N.OCT IMABS = C.ABS IMAGINARY = C.IM.DEEL IMARGUMENT = C.ARGUMENT IMCONJUGATE = C.TOEGEVOEGD IMCOS = C.COS IMCOSH = C.COSH IMCOT = C.COT IMCSC = C.COSEC IMCSCH = C.COSECH IMDIV = C.QUOTIENT IMEXP = C.EXP IMLN = C.LN IMLOG10 = C.LOG10 IMLOG2 = C.LOG2 IMPOWER = C.MACHT IMPRODUCT = C.PRODUCT IMREAL = C.REEEL.DEEL IMSEC = C.SEC IMSECH = C.SECH IMSIN = C.SIN IMSINH = C.SINH IMSQRT = C.WORTEL IMSUB = C.VERSCHIL IMSUM = C.SOM IMTAN = C.TAN OCT2BIN = OCT.N.BIN OCT2DEC = OCT.N.DEC OCT2HEX = OCT.N.HEX ## ## Financiële functies (Financial Functions) ## ACCRINT = SAMENG.RENTE ACCRINTM = SAMENG.RENTE.V AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = COUP.DAGEN.BB COUPDAYS = COUP.DAGEN COUPDAYSNC = COUP.DAGEN.VV COUPNCD = COUP.DATUM.NB COUPNUM = COUP.AANTAL COUPPCD = COUP.DATUM.VB CUMIPMT = CUM.RENTE CUMPRINC = CUM.HOOFDSOM DB = DB DDB = DDB DISC = DISCONTO DOLLARDE = EURO.DE DOLLARFR = EURO.BR DURATION = DUUR EFFECT = EFFECT.RENTE FV = TW FVSCHEDULE = TOEK.WAARDE2 INTRATE = RENTEPERCENTAGE IPMT = IBET IRR = IR ISPMT = ISBET MDURATION = AANG.DUUR MIRR = GIR NOMINAL = NOMINALE.RENTE NPER = NPER NPV = NHW ODDFPRICE = AFW.ET.PRIJS ODDFYIELD = AFW.ET.REND ODDLPRICE = AFW.LT.PRIJS ODDLYIELD = AFW.LT.REND PDURATION = PDUUR PMT = BET PPMT = PBET PRICE = PRIJS.NOM PRICEDISC = PRIJS.DISCONTO PRICEMAT = PRIJS.VERVALDAG PV = HW RATE = RENTE RECEIVED = OPBRENGST RRI = RRI SLN = LIN.AFSCHR SYD = SYD TBILLEQ = SCHATK.OBL TBILLPRICE = SCHATK.PRIJS TBILLYIELD = SCHATK.REND VDB = VDB XIRR = IR.SCHEMA XNPV = NHW2 YIELD = RENDEMENT YIELDDISC = REND.DISCONTO YIELDMAT = REND.VERVAL ## ## Informatiefuncties (Information Functions) ## CELL = CEL ERROR.TYPE = TYPE.FOUT INFO = INFO ISBLANK = ISLEEG ISERR = ISFOUT2 ISERROR = ISFOUT ISEVEN = IS.EVEN ISFORMULA = ISFORMULE ISLOGICAL = ISLOGISCH ISNA = ISNB ISNONTEXT = ISGEENTEKST ISNUMBER = ISGETAL ISODD = IS.ONEVEN ISREF = ISVERWIJZING ISTEXT = ISTEKST N = N NA = NB SHEET = BLAD SHEETS = BLADEN TYPE = TYPE ## ## Logische functies (Logical Functions) ## AND = EN FALSE = ONWAAR IF = ALS IFERROR = ALS.FOUT IFNA = ALS.NB IFS = ALS.VOORWAARDEN NOT = NIET OR = OF SWITCH = SCHAKELEN TRUE = WAAR XOR = EX.OF ## ## Zoek- en verwijzingsfuncties (Lookup & Reference Functions) ## ADDRESS = ADRES AREAS = BEREIKEN CHOOSE = KIEZEN COLUMN = KOLOM COLUMNS = KOLOMMEN FORMULATEXT = FORMULETEKST GETPIVOTDATA = DRAAITABEL.OPHALEN HLOOKUP = HORIZ.ZOEKEN HYPERLINK = HYPERLINK INDEX = INDEX INDIRECT = INDIRECT LOOKUP = ZOEKEN MATCH = VERGELIJKEN OFFSET = VERSCHUIVING ROW = RIJ ROWS = RIJEN RTD = RTG TRANSPOSE = TRANSPONEREN VLOOKUP = VERT.ZOEKEN *RC = RK ## ## Wiskundige en trigonometrische functies (Math & Trig Functions) ## ABS = ABS ACOS = BOOGCOS ACOSH = BOOGCOSH ACOT = BOOGCOT ACOTH = BOOGCOTH AGGREGATE = AGGREGAAT ARABIC = ARABISCH ASIN = BOOGSIN ASINH = BOOGSINH ATAN = BOOGTAN ATAN2 = BOOGTAN2 ATANH = BOOGTANH BASE = BASIS CEILING.MATH = AFRONDEN.BOVEN.WISK CEILING.PRECISE = AFRONDEN.BOVEN.NAUWKEURIG COMBIN = COMBINATIES COMBINA = COMBIN.A COS = COS COSH = COSH COT = COT COTH = COTH CSC = COSEC CSCH = COSECH DECIMAL = DECIMAAL DEGREES = GRADEN ECMA.CEILING = ECMA.AFRONDEN.BOVEN EVEN = EVEN EXP = EXP FACT = FACULTEIT FACTDOUBLE = DUBBELE.FACULTEIT FLOOR.MATH = AFRONDEN.BENEDEN.WISK FLOOR.PRECISE = AFRONDEN.BENEDEN.NAUWKEURIG GCD = GGD INT = INTEGER ISO.CEILING = ISO.AFRONDEN.BOVEN LCM = KGV LN = LN LOG = LOG LOG10 = LOG10 MDETERM = DETERMINANTMAT MINVERSE = INVERSEMAT MMULT = PRODUCTMAT MOD = REST MROUND = AFRONDEN.N.VEELVOUD MULTINOMIAL = MULTINOMIAAL MUNIT = EENHEIDMAT ODD = ONEVEN PI = PI POWER = MACHT PRODUCT = PRODUCT QUOTIENT = QUOTIENT RADIANS = RADIALEN RAND = ASELECT RANDBETWEEN = ASELECTTUSSEN ROMAN = ROMEINS ROUND = AFRONDEN ROUNDBAHTDOWN = BAHT.AFR.NAAR.BENEDEN ROUNDBAHTUP = BAHT.AFR.NAAR.BOVEN ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ROUNDUP = AFRONDEN.NAAR.BOVEN SEC = SEC SECH = SECH SERIESSUM = SOM.MACHTREEKS SIGN = POS.NEG SIN = SIN SINH = SINH SQRT = WORTEL SQRTPI = WORTEL.PI SUBTOTAL = SUBTOTAAL SUM = SOM SUMIF = SOM.ALS SUMIFS = SOMMEN.ALS SUMPRODUCT = SOMPRODUCT SUMSQ = KWADRATENSOM SUMX2MY2 = SOM.X2MINY2 SUMX2PY2 = SOM.X2PLUSY2 SUMXMY2 = SOM.XMINY.2 TAN = TAN TANH = TANH TRUNC = GEHEEL ## ## Statistische functies (Statistical Functions) ## AVEDEV = GEM.DEVIATIE AVERAGE = GEMIDDELDE AVERAGEA = GEMIDDELDEA AVERAGEIF = GEMIDDELDE.ALS AVERAGEIFS = GEMIDDELDEN.ALS BETA.DIST = BETA.VERD BETA.INV = BETA.INV BINOM.DIST = BINOM.VERD BINOM.DIST.RANGE = BINOM.VERD.BEREIK BINOM.INV = BINOMIALE.INV CHISQ.DIST = CHIKW.VERD CHISQ.DIST.RT = CHIKW.VERD.RECHTS CHISQ.INV = CHIKW.INV CHISQ.INV.RT = CHIKW.INV.RECHTS CHISQ.TEST = CHIKW.TEST CONFIDENCE.NORM = VERTROUWELIJKHEID.NORM CONFIDENCE.T = VERTROUWELIJKHEID.T CORREL = CORRELATIE COUNT = AANTAL COUNTA = AANTALARG COUNTBLANK = AANTAL.LEGE.CELLEN COUNTIF = AANTAL.ALS COUNTIFS = AANTALLEN.ALS COVARIANCE.P = COVARIANTIE.P COVARIANCE.S = COVARIANTIE.S DEVSQ = DEV.KWAD EXPON.DIST = EXPON.VERD.N F.DIST = F.VERD F.DIST.RT = F.VERD.RECHTS F.INV = F.INV F.INV.RT = F.INV.RECHTS F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHER.INV FORECAST.ETS = VOORSPELLEN.ETS FORECAST.ETS.CONFINT = VOORSPELLEN.ETS.CONFINT FORECAST.ETS.SEASONALITY = VOORSPELLEN.ETS.SEASONALITY FORECAST.ETS.STAT = FORECAST.ETS.STAT FORECAST.LINEAR = VOORSPELLEN.LINEAR FREQUENCY = INTERVAL GAMMA = GAMMA GAMMA.DIST = GAMMA.VERD.N GAMMA.INV = GAMMA.INV.N GAMMALN = GAMMA.LN GAMMALN.PRECISE = GAMMA.LN.NAUWKEURIG GAUSS = GAUSS GEOMEAN = MEETK.GEM GROWTH = GROEI HARMEAN = HARM.GEM HYPGEOM.DIST = HYPGEOM.VERD INTERCEPT = SNIJPUNT KURT = KURTOSIS LARGE = GROOTSTE LINEST = LIJNSCH LOGEST = LOGSCH LOGNORM.DIST = LOGNORM.VERD LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAX.ALS.VOORWAARDEN MEDIAN = MEDIAAN MIN = MIN MINA = MINA MINIFS = MIN.ALS.VOORWAARDEN MODE.MULT = MODUS.MEERV MODE.SNGL = MODUS.ENKELV NEGBINOM.DIST = NEGBINOM.VERD NORM.DIST = NORM.VERD.N NORM.INV = NORM.INV.N NORM.S.DIST = NORM.S.VERD NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIEL.EXC PERCENTILE.INC = PERCENTIEL.INC PERCENTRANK.EXC = PROCENTRANG.EXC PERCENTRANK.INC = PROCENTRANG.INC PERMUT = PERMUTATIES PERMUTATIONA = PERMUTATIE.A PHI = PHI POISSON.DIST = POISSON.VERD PROB = KANS QUARTILE.EXC = KWARTIEL.EXC QUARTILE.INC = KWARTIEL.INC RANK.AVG = RANG.GEMIDDELDE RANK.EQ = RANG.GELIJK RSQ = R.KWADRAAT SKEW = SCHEEFHEID SKEW.P = SCHEEFHEID.P SLOPE = RICHTING SMALL = KLEINSTE STANDARDIZE = NORMALISEREN STDEV.P = STDEV.P STDEV.S = STDEV.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STAND.FOUT.YX T.DIST = T.DIST T.DIST.2T = T.VERD.2T T.DIST.RT = T.VERD.RECHTS T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = TREND TRIMMEAN = GETRIMD.GEM VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.VERD Z.TEST = Z.TEST ## ## Tekstfuncties (Text Functions) ## BAHTTEXT = BAHT.TEKST CHAR = TEKEN CLEAN = WISSEN.CONTROL CODE = CODE CONCAT = TEKST.SAMENV DOLLAR = EURO EXACT = GELIJK FIND = VIND.ALLES FIXED = VAST ISTHAIDIGIT = IS.THAIS.CIJFER LEFT = LINKS LEN = LENGTE LOWER = KLEINE.LETTERS MID = DEEL NUMBERSTRING = GETALNOTATIE NUMBERVALUE = NUMERIEKE.WAARDE PHONETIC = FONETISCH PROPER = BEGINLETTERS REPLACE = VERVANGEN REPT = HERHALING RIGHT = RECHTS SEARCH = VIND.SPEC SUBSTITUTE = SUBSTITUEREN T = T TEXT = TEKST TEXTJOIN = TEKST.COMBINEREN THAIDIGIT = THAIS.CIJFER THAINUMSOUND = THAIS.GETAL.GELUID THAINUMSTRING = THAIS.GETAL.REEKS THAISTRINGLENGTH = THAIS.REEKS.LENGTE TRIM = SPATIES.WISSEN UNICHAR = UNITEKEN UNICODE = UNICODE UPPER = HOOFDLETTERS VALUE = WAARDE ## ## Webfuncties (Web Functions) ## ENCODEURL = URL.CODEREN FILTERXML = XML.FILTEREN WEBSERVICE = WEBSERVICE ## ## Compatibiliteitsfuncties (Compatibility Functions) ## BETADIST = BETAVERD BETAINV = BETAINV BINOMDIST = BINOMIALE.VERD CEILING = AFRONDEN.BOVEN CHIDIST = CHI.KWADRAAT CHIINV = CHI.KWADRAAT.INV CHITEST = CHI.TOETS CONCATENATE = TEKST.SAMENVOEGEN CONFIDENCE = BETROUWBAARHEID COVAR = COVARIANTIE CRITBINOM = CRIT.BINOM EXPONDIST = EXPON.VERD FDIST = F.VERDELING FINV = F.INVERSE FLOOR = AFRONDEN.BENEDEN FORECAST = VOORSPELLEN FTEST = F.TOETS GAMMADIST = GAMMA.VERD GAMMAINV = GAMMA.INV HYPGEOMDIST = HYPERGEO.VERD LOGINV = LOG.NORM.INV LOGNORMDIST = LOG.NORM.VERD MODE = MODUS NEGBINOMDIST = NEG.BINOM.VERD NORMDIST = NORM.VERD NORMINV = NORM.INV NORMSDIST = STAND.NORM.VERD NORMSINV = STAND.NORM.INV PERCENTILE = PERCENTIEL PERCENTRANK = PERCENT.RANG POISSON = POISSON QUARTILE = KWARTIEL RANK = RANG STDEV = STDEV STDEVP = STDEVP TDIST = T.VERD TINV = TINV TTEST = T.TOETS VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = Z.TOETS ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/pl/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Jezyk polski (Polish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #ZERO! DIV0 = #DZIEL/0! VALUE = #ARG! REF = #ADR! NAME = #NAZWA? NUM = #LICZBA! NA = #N/D! ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/pl/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Jezyk polski (Polish) ## ############################################################ ## ## Funkcje baz danych (Cube Functions) ## CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU CUBEMEMBER = ELEMENT.MODUŁU CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU CUBESET = ZESTAW.MODUŁÓW CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU CUBEVALUE = WARTOŚĆ.MODUŁU ## ## Funkcje baz danych (Database Functions) ## DAVERAGE = BD.ŚREDNIA DCOUNT = BD.ILE.REKORDÓW DCOUNTA = BD.ILE.REKORDÓW.A DGET = BD.POLE DMAX = BD.MAX DMIN = BD.MIN DPRODUCT = BD.ILOCZYN DSTDEV = BD.ODCH.STANDARD DSTDEVP = BD.ODCH.STANDARD.POPUL DSUM = BD.SUMA DVAR = BD.WARIANCJA DVARP = BD.WARIANCJA.POPUL ## ## Funkcje daty i godziny (Date & Time Functions) ## DATE = DATA DATEDIF = DATA.RÓŻNICA DATESTRING = DATA.CIĄG.ZNAK DATEVALUE = DATA.WARTOŚĆ DAY = DZIEŃ DAYS = DNI DAYS360 = DNI.360 EDATE = NR.SER.DATY EOMONTH = NR.SER.OST.DN.MIES HOUR = GODZINA ISOWEEKNUM = ISO.NUM.TYG MINUTE = MINUTA MONTH = MIESIĄC NETWORKDAYS = DNI.ROBOCZE NETWORKDAYS.INTL = DNI.ROBOCZE.NIESTAND NOW = TERAZ SECOND = SEKUNDA THAIDAYOFWEEK = TAJ.DZIEŃ.TYGODNIA THAIMONTHOFYEAR = TAJ.MIESIĄC.ROKU THAIYEAR = TAJ.ROK TIME = CZAS TIMEVALUE = CZAS.WARTOŚĆ TODAY = DZIŚ WEEKDAY = DZIEŃ.TYG WEEKNUM = NUM.TYG WORKDAY = DZIEŃ.ROBOCZY WORKDAY.INTL = DZIEŃ.ROBOCZY.NIESTAND YEAR = ROK YEARFRAC = CZĘŚĆ.ROKU ## ## Funkcje inżynierskie (Engineering Functions) ## BESSELI = BESSEL.I BESSELJ = BESSEL.J BESSELK = BESSEL.K BESSELY = BESSEL.Y BIN2DEC = DWÓJK.NA.DZIES BIN2HEX = DWÓJK.NA.SZESN BIN2OCT = DWÓJK.NA.ÓSM BITAND = BITAND BITLSHIFT = BIT.PRZESUNIĘCIE.W.LEWO BITOR = BITOR BITRSHIFT = BIT.PRZESUNIĘCIE.W.PRAWO BITXOR = BITXOR COMPLEX = LICZBA.ZESP CONVERT = KONWERTUJ DEC2BIN = DZIES.NA.DWÓJK DEC2HEX = DZIES.NA.SZESN DEC2OCT = DZIES.NA.ÓSM DELTA = CZY.RÓWNE ERF = FUNKCJA.BŁ ERF.PRECISE = FUNKCJA.BŁ.DOKŁ ERFC = KOMP.FUNKCJA.BŁ ERFC.PRECISE = KOMP.FUNKCJA.BŁ.DOKŁ GESTEP = SPRAWDŹ.PRÓG HEX2BIN = SZESN.NA.DWÓJK HEX2DEC = SZESN.NA.DZIES HEX2OCT = SZESN.NA.ÓSM IMABS = MODUŁ.LICZBY.ZESP IMAGINARY = CZ.UROJ.LICZBY.ZESP IMARGUMENT = ARG.LICZBY.ZESP IMCONJUGATE = SPRZĘŻ.LICZBY.ZESP IMCOS = COS.LICZBY.ZESP IMCOSH = COSH.LICZBY.ZESP IMCOT = COT.LICZBY.ZESP IMCSC = CSC.LICZBY.ZESP IMCSCH = CSCH.LICZBY.ZESP IMDIV = ILORAZ.LICZB.ZESP IMEXP = EXP.LICZBY.ZESP IMLN = LN.LICZBY.ZESP IMLOG10 = LOG10.LICZBY.ZESP IMLOG2 = LOG2.LICZBY.ZESP IMPOWER = POTĘGA.LICZBY.ZESP IMPRODUCT = ILOCZYN.LICZB.ZESP IMREAL = CZ.RZECZ.LICZBY.ZESP IMSEC = SEC.LICZBY.ZESP IMSECH = SECH.LICZBY.ZESP IMSIN = SIN.LICZBY.ZESP IMSINH = SINH.LICZBY.ZESP IMSQRT = PIERWIASTEK.LICZBY.ZESP IMSUB = RÓŻN.LICZB.ZESP IMSUM = SUMA.LICZB.ZESP IMTAN = TAN.LICZBY.ZESP OCT2BIN = ÓSM.NA.DWÓJK OCT2DEC = ÓSM.NA.DZIES OCT2HEX = ÓSM.NA.SZESN ## ## Funkcje finansowe (Financial Functions) ## ACCRINT = NAL.ODS ACCRINTM = NAL.ODS.WYKUP AMORDEGRC = AMORT.NIELIN AMORLINC = AMORT.LIN COUPDAYBS = WYPŁ.DNI.OD.POCZ COUPDAYS = WYPŁ.DNI COUPDAYSNC = WYPŁ.DNI.NAST COUPNCD = WYPŁ.DATA.NAST COUPNUM = WYPŁ.LICZBA COUPPCD = WYPŁ.DATA.POPRZ CUMIPMT = SPŁAC.ODS CUMPRINC = SPŁAC.KAPIT DB = DB DDB = DDB DISC = STOPA.DYSK DOLLARDE = CENA.DZIES DOLLARFR = CENA.UŁAM DURATION = ROCZ.PRZYCH EFFECT = EFEKTYWNA FV = FV FVSCHEDULE = WART.PRZYSZŁ.KAP INTRATE = STOPA.PROC IPMT = IPMT IRR = IRR ISPMT = ISPMT MDURATION = ROCZ.PRZYCH.M MIRR = MIRR NOMINAL = NOMINALNA NPER = NPER NPV = NPV ODDFPRICE = CENA.PIERW.OKR ODDFYIELD = RENT.PIERW.OKR ODDLPRICE = CENA.OST.OKR ODDLYIELD = RENT.OST.OKR PDURATION = O.CZAS.TRWANIA PMT = PMT PPMT = PPMT PRICE = CENA PRICEDISC = CENA.DYSK PRICEMAT = CENA.WYKUP PV = PV RATE = RATE RECEIVED = KWOTA.WYKUP RRI = RÓWNOW.STOPA.PROC SLN = SLN SYD = SYD TBILLEQ = RENT.EKW.BS TBILLPRICE = CENA.BS TBILLYIELD = RENT.BS VDB = VDB XIRR = XIRR XNPV = XNPV YIELD = RENTOWNOŚĆ YIELDDISC = RENT.DYSK YIELDMAT = RENT.WYKUP ## ## Funkcje informacyjne (Information Functions) ## CELL = KOMÓRKA ERROR.TYPE = NR.BŁĘDU INFO = INFO ISBLANK = CZY.PUSTA ISERR = CZY.BŁ ISERROR = CZY.BŁĄD ISEVEN = CZY.PARZYSTE ISFORMULA = CZY.FORMUŁA ISLOGICAL = CZY.LOGICZNA ISNA = CZY.BRAK ISNONTEXT = CZY.NIE.TEKST ISNUMBER = CZY.LICZBA ISODD = CZY.NIEPARZYSTE ISREF = CZY.ADR ISTEXT = CZY.TEKST N = N NA = BRAK SHEET = ARKUSZ SHEETS = ARKUSZE TYPE = TYP ## ## Funkcje logiczne (Logical Functions) ## AND = ORAZ FALSE = FAŁSZ IF = JEŻELI IFERROR = JEŻELI.BŁĄD IFNA = JEŻELI.ND IFS = WARUNKI NOT = NIE OR = LUB SWITCH = PRZEŁĄCZ TRUE = PRAWDA XOR = XOR ## ## Funkcje wyszukiwania i odwołań (Lookup & Reference Functions) ## ADDRESS = ADRES AREAS = OBSZARY CHOOSE = WYBIERZ COLUMN = NR.KOLUMNY COLUMNS = LICZBA.KOLUMN FORMULATEXT = FORMUŁA.TEKST GETPIVOTDATA = WEŹDANETABELI HLOOKUP = WYSZUKAJ.POZIOMO HYPERLINK = HIPERŁĄCZE INDEX = INDEKS INDIRECT = ADR.POŚR LOOKUP = WYSZUKAJ MATCH = PODAJ.POZYCJĘ OFFSET = PRZESUNIĘCIE ROW = WIERSZ ROWS = ILE.WIERSZY RTD = DANE.CZASU.RZECZ TRANSPOSE = TRANSPONUJ VLOOKUP = WYSZUKAJ.PIONOWO ## ## Funkcje matematyczne i trygonometryczne (Math & Trig Functions) ## ABS = MODUŁ.LICZBY ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGUJ ARABIC = ARABSKIE ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = PODSTAWA CEILING.MATH = ZAOKR.W.GÓRĘ.MATEMATYCZNE CEILING.PRECISE = ZAOKR.W.GÓRĘ.DOKŁ COMBIN = KOMBINACJE COMBINA = KOMBINACJE.A COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DZIESIĘTNA DEGREES = STOPNIE ECMA.CEILING = ECMA.ZAOKR.W.GÓRĘ EVEN = ZAOKR.DO.PARZ EXP = EXP FACT = SILNIA FACTDOUBLE = SILNIA.DWUKR FLOOR.MATH = ZAOKR.W.DÓŁ.MATEMATYCZNE FLOOR.PRECISE = ZAOKR.W.DÓŁ.DOKŁ GCD = NAJW.WSP.DZIEL INT = ZAOKR.DO.CAŁK ISO.CEILING = ISO.ZAOKR.W.GÓRĘ LCM = NAJMN.WSP.WIEL LN = LN LOG = LOG LOG10 = LOG10 MDETERM = WYZNACZNIK.MACIERZY MINVERSE = MACIERZ.ODW MMULT = MACIERZ.ILOCZYN MOD = MOD MROUND = ZAOKR.DO.WIELOKR MULTINOMIAL = WIELOMIAN MUNIT = MACIERZ.JEDNOSTKOWA ODD = ZAOKR.DO.NPARZ PI = PI POWER = POTĘGA PRODUCT = ILOCZYN QUOTIENT = CZ.CAŁK.DZIELENIA RADIANS = RADIANY RAND = LOS RANDBETWEEN = LOS.ZAKR ROMAN = RZYMSKIE ROUND = ZAOKR ROUNDBAHTDOWN = ZAOKR.DÓŁ.BAT ROUNDBAHTUP = ZAOKR.GÓRA.BAT ROUNDDOWN = ZAOKR.DÓŁ ROUNDUP = ZAOKR.GÓRA SEC = SEC SECH = SECH SERIESSUM = SUMA.SZER.POT SIGN = ZNAK.LICZBY SIN = SIN SINH = SINH SQRT = PIERWIASTEK SQRTPI = PIERW.PI SUBTOTAL = SUMY.CZĘŚCIOWE SUM = SUMA SUMIF = SUMA.JEŻELI SUMIFS = SUMA.WARUNKÓW SUMPRODUCT = SUMA.ILOCZYNÓW SUMSQ = SUMA.KWADRATÓW SUMX2MY2 = SUMA.X2.M.Y2 SUMX2PY2 = SUMA.X2.P.Y2 SUMXMY2 = SUMA.XMY.2 TAN = TAN TANH = TANH TRUNC = LICZBA.CAŁK ## ## Funkcje statystyczne (Statistical Functions) ## AVEDEV = ODCH.ŚREDNIE AVERAGE = ŚREDNIA AVERAGEA = ŚREDNIA.A AVERAGEIF = ŚREDNIA.JEŻELI AVERAGEIFS = ŚREDNIA.WARUNKÓW BETA.DIST = ROZKŁ.BETA BETA.INV = ROZKŁ.BETA.ODWR BINOM.DIST = ROZKŁ.DWUM BINOM.DIST.RANGE = ROZKŁ.DWUM.ZAKRES BINOM.INV = ROZKŁ.DWUM.ODWR CHISQ.DIST = ROZKŁ.CHI CHISQ.DIST.RT = ROZKŁ.CHI.PS CHISQ.INV = ROZKŁ.CHI.ODWR CHISQ.INV.RT = ROZKŁ.CHI.ODWR.PS CHISQ.TEST = CHI.TEST CONFIDENCE.NORM = UFNOŚĆ.NORM CONFIDENCE.T = UFNOŚĆ.T CORREL = WSP.KORELACJI COUNT = ILE.LICZB COUNTA = ILE.NIEPUSTYCH COUNTBLANK = LICZ.PUSTE COUNTIF = LICZ.JEŻELI COUNTIFS = LICZ.WARUNKI COVARIANCE.P = KOWARIANCJA.POPUL COVARIANCE.S = KOWARIANCJA.PRÓBKI DEVSQ = ODCH.KWADRATOWE EXPON.DIST = ROZKŁ.EXP F.DIST = ROZKŁ.F F.DIST.RT = ROZKŁ.F.PS F.INV = ROZKŁ.F.ODWR F.INV.RT = ROZKŁ.F.ODWR.PS F.TEST = F.TEST FISHER = ROZKŁAD.FISHER FISHERINV = ROZKŁAD.FISHER.ODW FORECAST.ETS = REGLINX.ETS FORECAST.ETS.CONFINT = REGLINX.ETS.CONFINT FORECAST.ETS.SEASONALITY = REGLINX.ETS.SEZONOWOŚĆ FORECAST.ETS.STAT = REGLINX.ETS.STATYSTYKA FORECAST.LINEAR = REGLINX.LINIOWA FREQUENCY = CZĘSTOŚĆ GAMMA = GAMMA GAMMA.DIST = ROZKŁ.GAMMA GAMMA.INV = ROZKŁ.GAMMA.ODWR GAMMALN = ROZKŁAD.LIN.GAMMA GAMMALN.PRECISE = ROZKŁAD.LIN.GAMMA.DOKŁ GAUSS = GAUSS GEOMEAN = ŚREDNIA.GEOMETRYCZNA GROWTH = REGEXPW HARMEAN = ŚREDNIA.HARMONICZNA HYPGEOM.DIST = ROZKŁ.HIPERGEOM INTERCEPT = ODCIĘTA KURT = KURTOZA LARGE = MAX.K LINEST = REGLINP LOGEST = REGEXPP LOGNORM.DIST = ROZKŁ.LOG LOGNORM.INV = ROZKŁ.LOG.ODWR MAX = MAX MAXA = MAX.A MAXIFS = MAKS.WARUNKÓW MEDIAN = MEDIANA MIN = MIN MINA = MIN.A MINIFS = MIN.WARUNKÓW MODE.MULT = WYST.NAJCZĘŚCIEJ.TABL MODE.SNGL = WYST.NAJCZĘŚCIEJ.WART NEGBINOM.DIST = ROZKŁ.DWUM.PRZEC NORM.DIST = ROZKŁ.NORMALNY NORM.INV = ROZKŁ.NORMALNY.ODWR NORM.S.DIST = ROZKŁ.NORMALNY.S NORM.S.INV = ROZKŁ.NORMALNY.S.ODWR PEARSON = PEARSON PERCENTILE.EXC = PERCENTYL.PRZEDZ.OTW PERCENTILE.INC = PERCENTYL.PRZEDZ.ZAMK PERCENTRANK.EXC = PROC.POZ.PRZEDZ.OTW PERCENTRANK.INC = PROC.POZ.PRZEDZ.ZAMK PERMUT = PERMUTACJE PERMUTATIONA = PERMUTACJE.A PHI = PHI POISSON.DIST = ROZKŁ.POISSON PROB = PRAWDPD QUARTILE.EXC = KWARTYL.PRZEDZ.OTW QUARTILE.INC = KWARTYL.PRZEDZ.ZAMK RANK.AVG = POZYCJA.ŚR RANK.EQ = POZYCJA.NAJW RSQ = R.KWADRAT SKEW = SKOŚNOŚĆ SKEW.P = SKOŚNOŚĆ.P SLOPE = NACHYLENIE SMALL = MIN.K STANDARDIZE = NORMALIZUJ STDEV.P = ODCH.STAND.POPUL STDEV.S = ODCH.STANDARD.PRÓBKI STDEVA = ODCH.STANDARDOWE.A STDEVPA = ODCH.STANDARD.POPUL.A STEYX = REGBŁSTD T.DIST = ROZKŁ.T T.DIST.2T = ROZKŁ.T.DS T.DIST.RT = ROZKŁ.T.PS T.INV = ROZKŁ.T.ODWR T.INV.2T = ROZKŁ.T.ODWR.DS T.TEST = T.TEST TREND = REGLINW TRIMMEAN = ŚREDNIA.WEWN VAR.P = WARIANCJA.POP VAR.S = WARIANCJA.PRÓBKI VARA = WARIANCJA.A VARPA = WARIANCJA.POPUL.A WEIBULL.DIST = ROZKŁ.WEIBULL Z.TEST = Z.TEST ## ## Funkcje tekstowe (Text Functions) ## BAHTTEXT = BAT.TEKST CHAR = ZNAK CLEAN = OCZYŚĆ CODE = KOD CONCAT = ZŁĄCZ.TEKST DOLLAR = KWOTA EXACT = PORÓWNAJ FIND = ZNAJDŹ FIXED = ZAOKR.DO.TEKST ISTHAIDIGIT = CZY.CYFRA.TAJ LEFT = LEWY LEN = DŁ LOWER = LITERY.MAŁE MID = FRAGMENT.TEKSTU NUMBERSTRING = LICZBA.CIĄG.ZNAK NUMBERVALUE = WARTOŚĆ.LICZBOWA PROPER = Z.WIELKIEJ.LITERY REPLACE = ZASTĄP REPT = POWT RIGHT = PRAWY SEARCH = SZUKAJ.TEKST SUBSTITUTE = PODSTAW T = T TEXT = TEKST TEXTJOIN = POŁĄCZ.TEKSTY THAIDIGIT = TAJ.CYFRA THAINUMSOUND = TAJ.DŹWIĘK.NUM THAINUMSTRING = TAJ.CIĄG.NUM THAISTRINGLENGTH = TAJ.DŁUGOŚĆ.CIĄGU TRIM = USUŃ.ZBĘDNE.ODSTĘPY UNICHAR = ZNAK.UNICODE UNICODE = UNICODE UPPER = LITERY.WIELKIE VALUE = WARTOŚĆ ## ## Funkcje sieci Web (Web Functions) ## ENCODEURL = ENCODEURL FILTERXML = FILTERXML WEBSERVICE = WEBSERVICE ## ## Funkcje zgodności (Compatibility Functions) ## BETADIST = ROZKŁAD.BETA BETAINV = ROZKŁAD.BETA.ODW BINOMDIST = ROZKŁAD.DWUM CEILING = ZAOKR.W.GÓRĘ CHIDIST = ROZKŁAD.CHI CHIINV = ROZKŁAD.CHI.ODW CHITEST = TEST.CHI CONCATENATE = ZŁĄCZ.TEKSTY CONFIDENCE = UFNOŚĆ COVAR = KOWARIANCJA CRITBINOM = PRÓG.ROZKŁAD.DWUM EXPONDIST = ROZKŁAD.EXP FDIST = ROZKŁAD.F FINV = ROZKŁAD.F.ODW FLOOR = ZAOKR.W.DÓŁ FORECAST = REGLINX FTEST = TEST.F GAMMADIST = ROZKŁAD.GAMMA GAMMAINV = ROZKŁAD.GAMMA.ODW HYPGEOMDIST = ROZKŁAD.HIPERGEOM LOGINV = ROZKŁAD.LOG.ODW LOGNORMDIST = ROZKŁAD.LOG MODE = WYST.NAJCZĘŚCIEJ NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC NORMDIST = ROZKŁAD.NORMALNY NORMINV = ROZKŁAD.NORMALNY.ODW NORMSDIST = ROZKŁAD.NORMALNY.S NORMSINV = ROZKŁAD.NORMALNY.S.ODW PERCENTILE = PERCENTYL PERCENTRANK = PROCENT.POZYCJA POISSON = ROZKŁAD.POISSON QUARTILE = KWARTYL RANK = POZYCJA STDEV = ODCH.STANDARDOWE STDEVP = ODCH.STANDARD.POPUL TDIST = ROZKŁAD.T TINV = ROZKŁAD.T.ODW TTEST = TEST.T VAR = WARIANCJA VARP = WARIANCJA.POPUL WEIBULL = ROZKŁAD.WEIBULL ZTEST = TEST.Z ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/pt/br/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Português Brasileiro (Brazilian Portuguese) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULO! DIV0 VALUE = #VALOR! REF NAME = #NOME? NUM = #NÚM! NA = #N/D ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/pt/br/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Português Brasileiro (Brazilian Portuguese) ## ############################################################ ## ## Funções de cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBROKPICUBO CUBEMEMBER = MEMBROCUBO CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = CONTAGEMCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funções de banco de dados (Database Functions) ## DAVERAGE = BDMÉDIA DCOUNT = BDCONTAR DCOUNTA = BDCONTARA DGET = BDEXTRAIR DMAX = BDMÁX DMIN = BDMÍN DPRODUCT = BDMULTIPL DSTDEV = BDEST DSTDEVP = BDDESVPA DSUM = BDSOMA DVAR = BDVAREST DVARP = BDVARP ## ## Funções de data e hora (Date & Time Functions) ## DATE = DATA DATEDIF = DATADIF DATESTRING = DATA.SÉRIE DATEVALUE = DATA.VALOR DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = DATAM EOMONTH = FIMMÊS HOUR = HORA ISOWEEKNUM = NÚMSEMANAISO MINUTE = MINUTO MONTH = MÊS NETWORKDAYS = DIATRABALHOTOTAL NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL NOW = AGORA SECOND = SEGUNDO TIME = TEMPO TIMEVALUE = VALOR.TEMPO TODAY = HOJE WEEKDAY = DIA.DA.SEMANA WEEKNUM = NÚMSEMANA WORKDAY = DIATRABALHO WORKDAY.INTL = DIATRABALHO.INTL YEAR = ANO YEARFRAC = FRAÇÃOANO ## ## Funções de engenharia (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINADEC BIN2HEX = BINAHEX BIN2OCT = BINAOCT BITAND = BITAND BITLSHIFT = DESLOCESQBIT BITOR = BITOR BITRSHIFT = DESLOCDIRBIT BITXOR = BITXOR COMPLEX = COMPLEXO CONVERT = CONVERTER DEC2BIN = DECABIN DEC2HEX = DECAHEX DEC2OCT = DECAOCT DELTA = DELTA ERF = FUNERRO ERF.PRECISE = FUNERRO.PRECISO ERFC = FUNERROCOMPL ERFC.PRECISE = FUNERROCOMPL.PRECISO GESTEP = DEGRAU HEX2BIN = HEXABIN HEX2DEC = HEXADEC HEX2OCT = HEXAOCT IMABS = IMABS IMAGINARY = IMAGINÁRIO IMARGUMENT = IMARG IMCONJUGATE = IMCONJ IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCOSEC IMCSCH = IMCOSECH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOT IMPRODUCT = IMPROD IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSENO IMSINH = IMSENH IMSQRT = IMRAIZ IMSUB = IMSUBTR IMSUM = IMSOMA IMTAN = IMTAN OCT2BIN = OCTABIN OCT2DEC = OCTADEC OCT2HEX = OCTAHEX ## ## Funções financeiras (Financial Functions) ## ACCRINT = JUROSACUM ACCRINTM = JUROSACUMV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = CUPDIASINLIQ COUPDAYS = CUPDIAS COUPDAYSNC = CUPDIASPRÓX COUPNCD = CUPDATAPRÓX COUPNUM = CUPNÚM COUPPCD = CUPDATAANT CUMIPMT = PGTOJURACUM CUMPRINC = PGTOCAPACUM DB = BD DDB = BDD DISC = DESC DOLLARDE = MOEDADEC DOLLARFR = MOEDAFRA DURATION = DURAÇÃO EFFECT = EFETIVA FV = VF FVSCHEDULE = VFPLANO INTRATE = TAXAJUROS IPMT = IPGTO IRR = TIR ISPMT = ÉPGTO MDURATION = MDURAÇÃO MIRR = MTIR NOMINAL = NOMINAL NPER = NPER NPV = VPL ODDFPRICE = PREÇOPRIMINC ODDFYIELD = LUCROPRIMINC ODDLPRICE = PREÇOÚLTINC ODDLYIELD = LUCROÚLTINC PDURATION = DURAÇÃOP PMT = PGTO PPMT = PPGTO PRICE = PREÇO PRICEDISC = PREÇODESC PRICEMAT = PREÇOVENC PV = VP RATE = TAXA RECEIVED = RECEBER RRI = TAXAJURO SLN = DPD SYD = SDA TBILLEQ = OTN TBILLPRICE = OTNVALOR TBILLYIELD = OTNLUCRO VDB = BDV XIRR = XTIR XNPV = XVPL YIELD = LUCRO YIELDDISC = LUCRODESC YIELDMAT = LUCROVENC ## ## Funções de informação (Information Functions) ## CELL = CÉL ERROR.TYPE = TIPO.ERRO INFO = INFORMAÇÃO ISBLANK = ÉCÉL.VAZIA ISERR = ÉERRO ISERROR = ÉERROS ISEVEN = ÉPAR ISFORMULA = ÉFÓRMULA ISLOGICAL = ÉLÓGICO ISNA = É.NÃO.DISP ISNONTEXT = É.NÃO.TEXTO ISNUMBER = ÉNÚM ISODD = ÉIMPAR ISREF = ÉREF ISTEXT = ÉTEXTO N = N NA = NÃO.DISP SHEET = PLAN SHEETS = PLANS TYPE = TIPO ## ## Funções lógicas (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SEERRO IFNA = SENÃODISP IFS = SES NOT = NÃO OR = OU SWITCH = PARÂMETRO TRUE = VERDADEIRO XOR = XOR ## ## Funções de pesquisa e referência (Lookup & Reference Functions) ## ADDRESS = ENDEREÇO AREAS = ÁREAS CHOOSE = ESCOLHER COLUMN = COL COLUMNS = COLS FORMULATEXT = FÓRMULATEXTO GETPIVOTDATA = INFODADOSTABELADINÂMICA HLOOKUP = PROCH HYPERLINK = HIPERLINK INDEX = ÍNDICE INDIRECT = INDIRETO LOOKUP = PROC MATCH = CORRESP OFFSET = DESLOC ROW = LIN ROWS = LINS RTD = RTD TRANSPOSE = TRANSPOR VLOOKUP = PROCV *RC = LC ## ## Funções matemáticas e trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = ARÁBICO ASIN = ASEN ASINH = ASENH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = TETO.MAT CEILING.PRECISE = TETO.PRECISO COMBIN = COMBIN COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = COSEC CSCH = COSECH DECIMAL = DECIMAL DEGREES = GRAUS ECMA.CEILING = ECMA.TETO EVEN = PAR EXP = EXP FACT = FATORIAL FACTDOUBLE = FATDUPLO FLOOR.MATH = ARREDMULTB.MAT FLOOR.PRECISE = ARREDMULTB.PRECISO GCD = MDC INT = INT ISO.CEILING = ISO.TETO LCM = MMC LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATRIZ.DETERM MINVERSE = MATRIZ.INVERSO MMULT = MATRIZ.MULT MOD = MOD MROUND = MARRED MULTINOMIAL = MULTINOMIAL MUNIT = MUNIT ODD = ÍMPAR PI = PI POWER = POTÊNCIA PRODUCT = MULT QUOTIENT = QUOCIENTE RADIANS = RADIANOS RAND = ALEATÓRIO RANDBETWEEN = ALEATÓRIOENTRE ROMAN = ROMANO ROUND = ARRED ROUNDDOWN = ARREDONDAR.PARA.BAIXO ROUNDUP = ARREDONDAR.PARA.CIMA SEC = SEC SECH = SECH SERIESSUM = SOMASEQÜÊNCIA SIGN = SINAL SIN = SEN SINH = SENH SQRT = RAIZ SQRTPI = RAIZPI SUBTOTAL = SUBTOTAL SUM = SOMA SUMIF = SOMASE SUMIFS = SOMASES SUMPRODUCT = SOMARPRODUTO SUMSQ = SOMAQUAD SUMX2MY2 = SOMAX2DY2 SUMX2PY2 = SOMAX2SY2 SUMXMY2 = SOMAXMY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funções estatísticas (Statistical Functions) ## AVEDEV = DESV.MÉDIO AVERAGE = MÉDIA AVERAGEA = MÉDIAA AVERAGEIF = MÉDIASE AVERAGEIFS = MÉDIASES BETA.DIST = DIST.BETA BETA.INV = INV.BETA BINOM.DIST = DISTR.BINOM BINOM.DIST.RANGE = INTERV.DISTR.BINOM BINOM.INV = INV.BINOM CHISQ.DIST = DIST.QUIQUA CHISQ.DIST.RT = DIST.QUIQUA.CD CHISQ.INV = INV.QUIQUA CHISQ.INV.RT = INV.QUIQUA.CD CHISQ.TEST = TESTE.QUIQUA CONFIDENCE.NORM = INT.CONFIANÇA.NORM CONFIDENCE.T = INT.CONFIANÇA.T CORREL = CORREL COUNT = CONT.NÚM COUNTA = CONT.VALORES COUNTBLANK = CONTAR.VAZIO COUNTIF = CONT.SE COUNTIFS = CONT.SES COVARIANCE.P = COVARIAÇÃO.P COVARIANCE.S = COVARIAÇÃO.S DEVSQ = DESVQ EXPON.DIST = DISTR.EXPON F.DIST = DIST.F F.DIST.RT = DIST.F.CD F.INV = INV.F F.INV.RT = INV.F.CD F.TEST = TESTE.F FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PREVISÃO.ETS FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE FORECAST.ETS.STAT = PREVISÃO.ETS.STAT FORECAST.LINEAR = PREVISÃO.LINEAR FREQUENCY = FREQÜÊNCIA GAMMA = GAMA GAMMA.DIST = DIST.GAMA GAMMA.INV = INV.GAMA GAMMALN = LNGAMA GAMMALN.PRECISE = LNGAMA.PRECISO GAUSS = GAUSS GEOMEAN = MÉDIA.GEOMÉTRICA GROWTH = CRESCIMENTO HARMEAN = MÉDIA.HARMÔNICA HYPGEOM.DIST = DIST.HIPERGEOM.N INTERCEPT = INTERCEPÇÃO KURT = CURT LARGE = MAIOR LINEST = PROJ.LIN LOGEST = PROJ.LOG LOGNORM.DIST = DIST.LOGNORMAL.N LOGNORM.INV = INV.LOGNORMAL MAX = MÁXIMO MAXA = MÁXIMOA MAXIFS = MÁXIMOSES MEDIAN = MED MIN = MÍNIMO MINA = MÍNIMOA MINIFS = MÍNIMOSES MODE.MULT = MODO.MULT MODE.SNGL = MODO.ÚNICO NEGBINOM.DIST = DIST.BIN.NEG.N NORM.DIST = DIST.NORM.N NORM.INV = INV.NORM.N NORM.S.DIST = DIST.NORMP.N NORM.S.INV = INV.NORMP.N PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = ORDEM.PORCENTUAL.EXC PERCENTRANK.INC = ORDEM.PORCENTUAL.INC PERMUT = PERMUT PERMUTATIONA = PERMUTAS PHI = PHI POISSON.DIST = DIST.POISSON PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = ORDEM.MÉD RANK.EQ = ORDEM.EQ RSQ = RQUAD SKEW = DISTORÇÃO SKEW.P = DISTORÇÃO.P SLOPE = INCLINAÇÃO SMALL = MENOR STANDARDIZE = PADRONIZAR STDEV.P = DESVPAD.P STDEV.S = DESVPAD.A STDEVA = DESVPADA STDEVPA = DESVPADPA STEYX = EPADYX T.DIST = DIST.T T.DIST.2T = DIST.T.BC T.DIST.RT = DIST.T.CD T.INV = INV.T T.INV.2T = INV.T.BC T.TEST = TESTE.T TREND = TENDÊNCIA TRIMMEAN = MÉDIA.INTERNA VAR.P = VAR.P VAR.S = VAR.A VARA = VARA VARPA = VARPA WEIBULL.DIST = DIST.WEIBULL Z.TEST = TESTE.Z ## ## Funções de texto (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = CARACT CLEAN = TIRAR CODE = CÓDIGO CONCAT = CONCAT DOLLAR = MOEDA EXACT = EXATO FIND = PROCURAR FIXED = DEF.NÚM.DEC LEFT = ESQUERDA LEN = NÚM.CARACT LOWER = MINÚSCULA MID = EXT.TEXTO NUMBERSTRING = SEQÜÊNCIA.NÚMERO NUMBERVALUE = VALORNUMÉRICO PHONETIC = FONÉTICA PROPER = PRI.MAIÚSCULA REPLACE = MUDAR REPT = REPT RIGHT = DIREITA SEARCH = LOCALIZAR SUBSTITUTE = SUBSTITUIR T = T TEXT = TEXTO TEXTJOIN = UNIRTEXTO TRIM = ARRUMAR UNICHAR = CARACTUNICODE UNICODE = UNICODE UPPER = MAIÚSCULA VALUE = VALOR ## ## Funções da Web (Web Functions) ## ENCODEURL = CODIFURL FILTERXML = FILTROXML WEBSERVICE = SERVIÇOWEB ## ## Funções de compatibilidade (Compatibility Functions) ## BETADIST = DISTBETA BETAINV = BETA.ACUM.INV BINOMDIST = DISTRBINOM CEILING = TETO CHIDIST = DIST.QUI CHIINV = INV.QUI CHITEST = TESTE.QUI CONCATENATE = CONCATENAR CONFIDENCE = INT.CONFIANÇA COVAR = COVAR CRITBINOM = CRIT.BINOM EXPONDIST = DISTEXPON FDIST = DISTF FINV = INVF FLOOR = ARREDMULTB FORECAST = PREVISÃO FTEST = TESTEF GAMMADIST = DISTGAMA GAMMAINV = INVGAMA HYPGEOMDIST = DIST.HIPERGEOM LOGINV = INVLOG LOGNORMDIST = DIST.LOGNORMAL MODE = MODO NEGBINOMDIST = DIST.BIN.NEG NORMDIST = DISTNORM NORMINV = INV.NORM NORMSDIST = DISTNORMP NORMSINV = INV.NORMP PERCENTILE = PERCENTIL PERCENTRANK = ORDEM.PORCENTUAL POISSON = POISSON QUARTILE = QUARTIL RANK = ORDEM STDEV = DESVPAD STDEVP = DESVPADP TDIST = DISTT TINV = INVT TTEST = TESTET VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = TESTEZ ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/pt/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Português (Portuguese) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULO! DIV0 VALUE = #VALOR! REF NAME = #NOME? NUM = #NÚM! NA = #N/D ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/pt/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Português (Portuguese) ## ############################################################ ## ## Funções de cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBROKPICUBO CUBEMEMBER = MEMBROCUBO CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = CONTARCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funções de base de dados (Database Functions) ## DAVERAGE = BDMÉDIA DCOUNT = BDCONTAR DCOUNTA = BDCONTAR.VAL DGET = BDOBTER DMAX = BDMÁX DMIN = BDMÍN DPRODUCT = BDMULTIPL DSTDEV = BDDESVPAD DSTDEVP = BDDESVPADP DSUM = BDSOMA DVAR = BDVAR DVARP = BDVARP ## ## Funções de data e hora (Date & Time Functions) ## DATE = DATA DATEDIF = DATADIF DATESTRING = DATA.CADEIA DATEVALUE = DATA.VALOR DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = DATAM EOMONTH = FIMMÊS HOUR = HORA ISOWEEKNUM = NUMSEMANAISO MINUTE = MINUTO MONTH = MÊS NETWORKDAYS = DIATRABALHOTOTAL NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL NOW = AGORA SECOND = SEGUNDO THAIDAYOFWEEK = DIA.DA.SEMANA.TAILANDÊS THAIMONTHOFYEAR = MÊS.DO.ANO.TAILANDÊS THAIYEAR = ANO.TAILANDÊS TIME = TEMPO TIMEVALUE = VALOR.TEMPO TODAY = HOJE WEEKDAY = DIA.SEMANA WEEKNUM = NÚMSEMANA WORKDAY = DIATRABALHO WORKDAY.INTL = DIATRABALHO.INTL YEAR = ANO YEARFRAC = FRAÇÃOANO ## ## Funções de engenharia (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINADEC BIN2HEX = BINAHEX BIN2OCT = BINAOCT BITAND = BIT.E BITLSHIFT = BITDESL.ESQ BITOR = BIT.OU BITRSHIFT = BITDESL.DIR BITXOR = BIT.XOU COMPLEX = COMPLEXO CONVERT = CONVERTER DEC2BIN = DECABIN DEC2HEX = DECAHEX DEC2OCT = DECAOCT DELTA = DELTA ERF = FUNCERRO ERF.PRECISE = FUNCERRO.PRECISO ERFC = FUNCERROCOMPL ERFC.PRECISE = FUNCERROCOMPL.PRECISO GESTEP = DEGRAU HEX2BIN = HEXABIN HEX2DEC = HEXADEC HEX2OCT = HEXAOCT IMABS = IMABS IMAGINARY = IMAGINÁRIO IMARGUMENT = IMARG IMCONJUGATE = IMCONJ IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOT IMPRODUCT = IMPROD IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSENO IMSINH = IMSENOH IMSQRT = IMRAIZ IMSUB = IMSUBTR IMSUM = IMSOMA IMTAN = IMTAN OCT2BIN = OCTABIN OCT2DEC = OCTADEC OCT2HEX = OCTAHEX ## ## Funções financeiras (Financial Functions) ## ACCRINT = JUROSACUM ACCRINTM = JUROSACUMV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = CUPDIASINLIQ COUPDAYS = CUPDIAS COUPDAYSNC = CUPDIASPRÓX COUPNCD = CUPDATAPRÓX COUPNUM = CUPNÚM COUPPCD = CUPDATAANT CUMIPMT = PGTOJURACUM CUMPRINC = PGTOCAPACUM DB = BD DDB = BDD DISC = DESC DOLLARDE = MOEDADEC DOLLARFR = MOEDAFRA DURATION = DURAÇÃO EFFECT = EFETIVA FV = VF FVSCHEDULE = VFPLANO INTRATE = TAXAJUROS IPMT = IPGTO IRR = TIR ISPMT = É.PGTO MDURATION = MDURAÇÃO MIRR = MTIR NOMINAL = NOMINAL NPER = NPER NPV = VAL ODDFPRICE = PREÇOPRIMINC ODDFYIELD = LUCROPRIMINC ODDLPRICE = PREÇOÚLTINC ODDLYIELD = LUCROÚLTINC PDURATION = PDURAÇÃO PMT = PGTO PPMT = PPGTO PRICE = PREÇO PRICEDISC = PREÇODESC PRICEMAT = PREÇOVENC PV = VA RATE = TAXA RECEIVED = RECEBER RRI = DEVOLVERTAXAJUROS SLN = AMORT SYD = AMORTD TBILLEQ = OTN TBILLPRICE = OTNVALOR TBILLYIELD = OTNLUCRO VDB = BDV XIRR = XTIR XNPV = XVAL YIELD = LUCRO YIELDDISC = LUCRODESC YIELDMAT = LUCROVENC ## ## Funções de informação (Information Functions) ## CELL = CÉL ERROR.TYPE = TIPO.ERRO INFO = INFORMAÇÃO ISBLANK = É.CÉL.VAZIA ISERR = É.ERROS ISERROR = É.ERRO ISEVEN = ÉPAR ISFORMULA = É.FORMULA ISLOGICAL = É.LÓGICO ISNA = É.NÃO.DISP ISNONTEXT = É.NÃO.TEXTO ISNUMBER = É.NÚM ISODD = ÉÍMPAR ISREF = É.REF ISTEXT = É.TEXTO N = N NA = NÃO.DISP SHEET = FOLHA SHEETS = FOLHAS TYPE = TIPO ## ## Funções lógicas (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SE.ERRO IFNA = SEND IFS = SE.S NOT = NÃO OR = OU SWITCH = PARÂMETRO TRUE = VERDADEIRO XOR = XOU ## ## Funções de pesquisa e referência (Lookup & Reference Functions) ## ADDRESS = ENDEREÇO AREAS = ÁREAS CHOOSE = SELECIONAR COLUMN = COL COLUMNS = COLS FORMULATEXT = FÓRMULA.TEXTO GETPIVOTDATA = OBTERDADOSDIN HLOOKUP = PROCH HYPERLINK = HIPERLIGAÇÃO INDEX = ÍNDICE INDIRECT = INDIRETO LOOKUP = PROC MATCH = CORRESP OFFSET = DESLOCAMENTO ROW = LIN ROWS = LINS RTD = RTD TRANSPOSE = TRANSPOR VLOOKUP = PROCV *RC = LC ## ## Funções matemáticas e trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = ÁRABE ASIN = ASEN ASINH = ASENH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = ARRED.EXCESSO.MAT CEILING.PRECISE = ARRED.EXCESSO.PRECISO COMBIN = COMBIN COMBINA = COMBIN.R COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRAUS ECMA.CEILING = ARRED.EXCESSO.ECMA EVEN = PAR EXP = EXP FACT = FATORIAL FACTDOUBLE = FATDUPLO FLOOR.MATH = ARRED.DEFEITO.MAT FLOOR.PRECISE = ARRED.DEFEITO.PRECISO GCD = MDC INT = INT ISO.CEILING = ARRED.EXCESSO.ISO LCM = MMC LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATRIZ.DETERM MINVERSE = MATRIZ.INVERSA MMULT = MATRIZ.MULT MOD = RESTO MROUND = MARRED MULTINOMIAL = POLINOMIAL MUNIT = UNIDM ODD = ÍMPAR PI = PI POWER = POTÊNCIA PRODUCT = PRODUTO QUOTIENT = QUOCIENTE RADIANS = RADIANOS RAND = ALEATÓRIO RANDBETWEEN = ALEATÓRIOENTRE ROMAN = ROMANO ROUND = ARRED ROUNDBAHTDOWN = ARREDOND.BAHT.BAIXO ROUNDBAHTUP = ARREDOND.BAHT.CIMA ROUNDDOWN = ARRED.PARA.BAIXO ROUNDUP = ARRED.PARA.CIMA SEC = SEC SECH = SECH SERIESSUM = SOMASÉRIE SIGN = SINAL SIN = SEN SINH = SENH SQRT = RAIZQ SQRTPI = RAIZPI SUBTOTAL = SUBTOTAL SUM = SOMA SUMIF = SOMA.SE SUMIFS = SOMA.SE.S SUMPRODUCT = SOMARPRODUTO SUMSQ = SOMARQUAD SUMX2MY2 = SOMAX2DY2 SUMX2PY2 = SOMAX2SY2 SUMXMY2 = SOMAXMY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funções estatísticas (Statistical Functions) ## AVEDEV = DESV.MÉDIO AVERAGE = MÉDIA AVERAGEA = MÉDIAA AVERAGEIF = MÉDIA.SE AVERAGEIFS = MÉDIA.SE.S BETA.DIST = DIST.BETA BETA.INV = INV.BETA BINOM.DIST = DISTR.BINOM BINOM.DIST.RANGE = DIST.BINOM.INTERVALO BINOM.INV = INV.BINOM CHISQ.DIST = DIST.CHIQ CHISQ.DIST.RT = DIST.CHIQ.DIR CHISQ.INV = INV.CHIQ CHISQ.INV.RT = INV.CHIQ.DIR CHISQ.TEST = TESTE.CHIQ CONFIDENCE.NORM = INT.CONFIANÇA.NORM CONFIDENCE.T = INT.CONFIANÇA.T CORREL = CORREL COUNT = CONTAR COUNTA = CONTAR.VAL COUNTBLANK = CONTAR.VAZIO COUNTIF = CONTAR.SE COUNTIFS = CONTAR.SE.S COVARIANCE.P = COVARIÂNCIA.P COVARIANCE.S = COVARIÂNCIA.S DEVSQ = DESVQ EXPON.DIST = DIST.EXPON F.DIST = DIST.F F.DIST.RT = DIST.F.DIR F.INV = INV.F F.INV.RT = INV.F.DIR F.TEST = TESTE.F FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PREVISÃO.ETS FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE FORECAST.ETS.STAT = PREVISÃO.ETS.ESTATÍSTICA FORECAST.LINEAR = PREVISÃO.LINEAR FREQUENCY = FREQUÊNCIA GAMMA = GAMA GAMMA.DIST = DIST.GAMA GAMMA.INV = INV.GAMA GAMMALN = LNGAMA GAMMALN.PRECISE = LNGAMA.PRECISO GAUSS = GAUSS GEOMEAN = MÉDIA.GEOMÉTRICA GROWTH = CRESCIMENTO HARMEAN = MÉDIA.HARMÓNICA HYPGEOM.DIST = DIST.HIPGEOM INTERCEPT = INTERCETAR KURT = CURT LARGE = MAIOR LINEST = PROJ.LIN LOGEST = PROJ.LOG LOGNORM.DIST = DIST.NORMLOG LOGNORM.INV = INV.NORMALLOG MAX = MÁXIMO MAXA = MÁXIMOA MAXIFS = MÁXIMO.SE.S MEDIAN = MED MIN = MÍNIMO MINA = MÍNIMOA MINIFS = MÍNIMO.SE.S MODE.MULT = MODO.MÚLT MODE.SNGL = MODO.SIMPLES NEGBINOM.DIST = DIST.BINOM.NEG NORM.DIST = DIST.NORMAL NORM.INV = INV.NORMAL NORM.S.DIST = DIST.S.NORM NORM.S.INV = INV.S.NORM PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = ORDEM.PERCENTUAL.EXC PERCENTRANK.INC = ORDEM.PERCENTUAL.INC PERMUT = PERMUTAR PERMUTATIONA = PERMUTAR.R PHI = PHI POISSON.DIST = DIST.POISSON PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = ORDEM.MÉD RANK.EQ = ORDEM.EQ RSQ = RQUAD SKEW = DISTORÇÃO SKEW.P = DISTORÇÃO.P SLOPE = DECLIVE SMALL = MENOR STANDARDIZE = NORMALIZAR STDEV.P = DESVPAD.P STDEV.S = DESVPAD.S STDEVA = DESVPADA STDEVPA = DESVPADPA STEYX = EPADYX T.DIST = DIST.T T.DIST.2T = DIST.T.2C T.DIST.RT = DIST.T.DIR T.INV = INV.T T.INV.2T = INV.T.2C T.TEST = TESTE.T TREND = TENDÊNCIA TRIMMEAN = MÉDIA.INTERNA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = DIST.WEIBULL Z.TEST = TESTE.Z ## ## Funções de texto (Text Functions) ## BAHTTEXT = TEXTO.BAHT CHAR = CARÁT CLEAN = LIMPARB CODE = CÓDIGO CONCAT = CONCAT DOLLAR = MOEDA EXACT = EXATO FIND = LOCALIZAR FIXED = FIXA ISTHAIDIGIT = É.DÍGITO.TAILANDÊS LEFT = ESQUERDA LEN = NÚM.CARAT LOWER = MINÚSCULAS MID = SEG.TEXTO NUMBERSTRING = NÚMERO.CADEIA NUMBERVALUE = VALOR.NÚMERO PHONETIC = FONÉTICA PROPER = INICIAL.MAIÚSCULA REPLACE = SUBSTITUIR REPT = REPETIR RIGHT = DIREITA SEARCH = PROCURAR SUBSTITUTE = SUBST T = T TEXT = TEXTO TEXTJOIN = UNIRTEXTO THAIDIGIT = DÍGITO.TAILANDÊS THAINUMSOUND = SOM.NÚM.TAILANDÊS THAINUMSTRING = CADEIA.NÚM.TAILANDÊS THAISTRINGLENGTH = COMP.CADEIA.TAILANDÊS TRIM = COMPACTAR UNICHAR = UNICARÁT UNICODE = UNICODE UPPER = MAIÚSCULAS VALUE = VALOR ## ## Funções da Web (Web Functions) ## ENCODEURL = CODIFICAÇÃOURL FILTERXML = FILTRARXML WEBSERVICE = SERVIÇOWEB ## ## Funções de compatibilidade (Compatibility Functions) ## BETADIST = DISTBETA BETAINV = BETA.ACUM.INV BINOMDIST = DISTRBINOM CEILING = ARRED.EXCESSO CHIDIST = DIST.CHI CHIINV = INV.CHI CHITEST = TESTE.CHI CONCATENATE = CONCATENAR CONFIDENCE = INT.CONFIANÇA COVAR = COVAR CRITBINOM = CRIT.BINOM EXPONDIST = DISTEXPON FDIST = DISTF FINV = INVF FLOOR = ARRED.DEFEITO FORECAST = PREVISÃO FTEST = TESTEF GAMMADIST = DISTGAMA GAMMAINV = INVGAMA HYPGEOMDIST = DIST.HIPERGEOM LOGINV = INVLOG LOGNORMDIST = DIST.NORMALLOG MODE = MODA NEGBINOMDIST = DIST.BIN.NEG NORMDIST = DIST.NORM NORMINV = INV.NORM NORMSDIST = DIST.NORMP NORMSINV = INV.NORMP PERCENTILE = PERCENTIL PERCENTRANK = ORDEM.PERCENTUAL POISSON = POISSON QUARTILE = QUARTIL RANK = ORDEM STDEV = DESVPAD STDEVP = DESVPADP TDIST = DISTT TINV = INVT TTEST = TESTET VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = TESTEZ ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/ru/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## русский язык (Russian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #ПУСТО! DIV0 = #ДЕЛ/0! VALUE = #ЗНАЧ! REF = #ССЫЛКА! NAME = #ИМЯ? NUM = #ЧИСЛО! NA = #Н/Д ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/ru/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## русский язык (Russian) ## ############################################################ ## ## Функции кубов (Cube Functions) ## CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП CUBEMEMBER = КУБЭЛЕМЕНТ CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ CUBESET = КУБМНОЖ CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ CUBEVALUE = КУБЗНАЧЕНИЕ ## ## Функции для работы с базами данных (Database Functions) ## DAVERAGE = ДСРЗНАЧ DCOUNT = БСЧЁТ DCOUNTA = БСЧЁТА DGET = БИЗВЛЕЧЬ DMAX = ДМАКС DMIN = ДМИН DPRODUCT = БДПРОИЗВЕД DSTDEV = ДСТАНДОТКЛ DSTDEVP = ДСТАНДОТКЛП DSUM = БДСУММ DVAR = БДДИСП DVARP = БДДИСПП ## ## Функции даты и времени (Date & Time Functions) ## DATE = ДАТА DATEDIF = РАЗНДАТ DATESTRING = СТРОКАДАННЫХ DATEVALUE = ДАТАЗНАЧ DAY = ДЕНЬ DAYS = ДНИ DAYS360 = ДНЕЙ360 EDATE = ДАТАМЕС EOMONTH = КОНМЕСЯЦА HOUR = ЧАС ISOWEEKNUM = НОМНЕДЕЛИ.ISO MINUTE = МИНУТЫ MONTH = МЕСЯЦ NETWORKDAYS = ЧИСТРАБДНИ NETWORKDAYS.INTL = ЧИСТРАБДНИ.МЕЖД NOW = ТДАТА SECOND = СЕКУНДЫ THAIDAYOFWEEK = ТАЙДЕНЬНЕД THAIMONTHOFYEAR = ТАЙМЕСЯЦ THAIYEAR = ТАЙГОД TIME = ВРЕМЯ TIMEVALUE = ВРЕМЗНАЧ TODAY = СЕГОДНЯ WEEKDAY = ДЕНЬНЕД WEEKNUM = НОМНЕДЕЛИ WORKDAY = РАБДЕНЬ WORKDAY.INTL = РАБДЕНЬ.МЕЖД YEAR = ГОД YEARFRAC = ДОЛЯГОДА ## ## Инженерные функции (Engineering Functions) ## BESSELI = БЕССЕЛЬ.I BESSELJ = БЕССЕЛЬ.J BESSELK = БЕССЕЛЬ.K BESSELY = БЕССЕЛЬ.Y BIN2DEC = ДВ.В.ДЕС BIN2HEX = ДВ.В.ШЕСТН BIN2OCT = ДВ.В.ВОСЬМ BITAND = БИТ.И BITLSHIFT = БИТ.СДВИГЛ BITOR = БИТ.ИЛИ BITRSHIFT = БИТ.СДВИГП BITXOR = БИТ.ИСКЛИЛИ COMPLEX = КОМПЛЕКСН CONVERT = ПРЕОБР DEC2BIN = ДЕС.В.ДВ DEC2HEX = ДЕС.В.ШЕСТН DEC2OCT = ДЕС.В.ВОСЬМ DELTA = ДЕЛЬТА ERF = ФОШ ERF.PRECISE = ФОШ.ТОЧН ERFC = ДФОШ ERFC.PRECISE = ДФОШ.ТОЧН GESTEP = ПОРОГ HEX2BIN = ШЕСТН.В.ДВ HEX2DEC = ШЕСТН.В.ДЕС HEX2OCT = ШЕСТН.В.ВОСЬМ IMABS = МНИМ.ABS IMAGINARY = МНИМ.ЧАСТЬ IMARGUMENT = МНИМ.АРГУМЕНТ IMCONJUGATE = МНИМ.СОПРЯЖ IMCOS = МНИМ.COS IMCOSH = МНИМ.COSH IMCOT = МНИМ.COT IMCSC = МНИМ.CSC IMCSCH = МНИМ.CSCH IMDIV = МНИМ.ДЕЛ IMEXP = МНИМ.EXP IMLN = МНИМ.LN IMLOG10 = МНИМ.LOG10 IMLOG2 = МНИМ.LOG2 IMPOWER = МНИМ.СТЕПЕНЬ IMPRODUCT = МНИМ.ПРОИЗВЕД IMREAL = МНИМ.ВЕЩ IMSEC = МНИМ.SEC IMSECH = МНИМ.SECH IMSIN = МНИМ.SIN IMSINH = МНИМ.SINH IMSQRT = МНИМ.КОРЕНЬ IMSUB = МНИМ.РАЗН IMSUM = МНИМ.СУММ IMTAN = МНИМ.TAN OCT2BIN = ВОСЬМ.В.ДВ OCT2DEC = ВОСЬМ.В.ДЕС OCT2HEX = ВОСЬМ.В.ШЕСТН ## ## Финансовые функции (Financial Functions) ## ACCRINT = НАКОПДОХОД ACCRINTM = НАКОПДОХОДПОГАШ AMORDEGRC = АМОРУМ AMORLINC = АМОРУВ COUPDAYBS = ДНЕЙКУПОНДО COUPDAYS = ДНЕЙКУПОН COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ COUPNCD = ДАТАКУПОНПОСЛЕ COUPNUM = ЧИСЛКУПОН COUPPCD = ДАТАКУПОНДО CUMIPMT = ОБЩПЛАТ CUMPRINC = ОБЩДОХОД DB = ФУО DDB = ДДОБ DISC = СКИДКА DOLLARDE = РУБЛЬ.ДЕС DOLLARFR = РУБЛЬ.ДРОБЬ DURATION = ДЛИТ EFFECT = ЭФФЕКТ FV = БС FVSCHEDULE = БЗРАСПИС INTRATE = ИНОРМА IPMT = ПРПЛТ IRR = ВСД ISPMT = ПРОЦПЛАТ MDURATION = МДЛИТ MIRR = МВСД NOMINAL = НОМИНАЛ NPER = КПЕР NPV = ЧПС ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ODDFYIELD = ДОХОДПЕРВНЕРЕГ ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ODDLYIELD = ДОХОДПОСЛНЕРЕГ PDURATION = ПДЛИТ PMT = ПЛТ PPMT = ОСПЛТ PRICE = ЦЕНА PRICEDISC = ЦЕНАСКИДКА PRICEMAT = ЦЕНАПОГАШ PV = ПС RATE = СТАВКА RECEIVED = ПОЛУЧЕНО RRI = ЭКВ.СТАВКА SLN = АПЛ SYD = АСЧ TBILLEQ = РАВНОКЧЕК TBILLPRICE = ЦЕНАКЧЕК TBILLYIELD = ДОХОДКЧЕК USDOLLAR = ДОЛЛСША VDB = ПУО XIRR = ЧИСТВНДОХ XNPV = ЧИСТНЗ YIELD = ДОХОД YIELDDISC = ДОХОДСКИДКА YIELDMAT = ДОХОДПОГАШ ## ## Информационные функции (Information Functions) ## CELL = ЯЧЕЙКА ERROR.TYPE = ТИП.ОШИБКИ INFO = ИНФОРМ ISBLANK = ЕПУСТО ISERR = ЕОШ ISERROR = ЕОШИБКА ISEVEN = ЕЧЁТН ISFORMULA = ЕФОРМУЛА ISLOGICAL = ЕЛОГИЧ ISNA = ЕНД ISNONTEXT = ЕНЕТЕКСТ ISNUMBER = ЕЧИСЛО ISODD = ЕНЕЧЁТ ISREF = ЕССЫЛКА ISTEXT = ЕТЕКСТ N = Ч NA = НД SHEET = ЛИСТ SHEETS = ЛИСТЫ TYPE = ТИП ## ## Логические функции (Logical Functions) ## AND = И FALSE = ЛОЖЬ IF = ЕСЛИ IFERROR = ЕСЛИОШИБКА IFNA = ЕСНД IFS = УСЛОВИЯ NOT = НЕ OR = ИЛИ SWITCH = ПЕРЕКЛЮЧ TRUE = ИСТИНА XOR = ИСКЛИЛИ ## ## Функции ссылки и поиска (Lookup & Reference Functions) ## ADDRESS = АДРЕС AREAS = ОБЛАСТИ CHOOSE = ВЫБОР COLUMN = СТОЛБЕЦ COLUMNS = ЧИСЛСТОЛБ FILTER = ФИЛЬТР FORMULATEXT = Ф.ТЕКСТ GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ HLOOKUP = ГПР HYPERLINK = ГИПЕРССЫЛКА INDEX = ИНДЕКС INDIRECT = ДВССЫЛ LOOKUP = ПРОСМОТР MATCH = ПОИСКПОЗ OFFSET = СМЕЩ ROW = СТРОКА ROWS = ЧСТРОК RTD = ДРВ SORT = СОРТ SORTBY = СОРТПО TRANSPOSE = ТРАНСП UNIQUE = УНИК VLOOKUP = ВПР XLOOKUP = ПРОСМОТРX XMATCH = ПОИСКПОЗX ## ## Математические и тригонометрические функции (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = АГРЕГАТ ARABIC = АРАБСКОЕ ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = ОСНОВАНИЕ CEILING.MATH = ОКРВВЕРХ.МАТ CEILING.PRECISE = ОКРВВЕРХ.ТОЧН COMBIN = ЧИСЛКОМБ COMBINA = ЧИСЛКОМБА COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = ДЕС DEGREES = ГРАДУСЫ ECMA.CEILING = ECMA.ОКРВВЕРХ EVEN = ЧЁТН EXP = EXP FACT = ФАКТР FACTDOUBLE = ДВФАКТР FLOOR.MATH = ОКРВНИЗ.МАТ FLOOR.PRECISE = ОКРВНИЗ.ТОЧН GCD = НОД INT = ЦЕЛОЕ ISO.CEILING = ISO.ОКРВВЕРХ LCM = НОК LN = LN LOG = LOG LOG10 = LOG10 MDETERM = МОПРЕД MINVERSE = МОБР MMULT = МУМНОЖ MOD = ОСТАТ MROUND = ОКРУГЛТ MULTINOMIAL = МУЛЬТИНОМ MUNIT = МЕДИН ODD = НЕЧЁТ PI = ПИ POWER = СТЕПЕНЬ PRODUCT = ПРОИЗВЕД QUOTIENT = ЧАСТНОЕ RADIANS = РАДИАНЫ RAND = СЛЧИС RANDARRAY = СЛУЧМАССИВ RANDBETWEEN = СЛУЧМЕЖДУ ROMAN = РИМСКОЕ ROUND = ОКРУГЛ ROUNDBAHTDOWN = ОКРУГЛБАТВНИЗ ROUNDBAHTUP = ОКРУГЛБАТВВЕРХ ROUNDDOWN = ОКРУГЛВНИЗ ROUNDUP = ОКРУГЛВВЕРХ SEC = SEC SECH = SECH SERIESSUM = РЯД.СУММ SEQUENCE = ПОСЛЕДОВ SIGN = ЗНАК SIN = SIN SINH = SINH SQRT = КОРЕНЬ SQRTPI = КОРЕНЬПИ SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ SUM = СУММ SUMIF = СУММЕСЛИ SUMIFS = СУММЕСЛИМН SUMPRODUCT = СУММПРОИЗВ SUMSQ = СУММКВ SUMX2MY2 = СУММРАЗНКВ SUMX2PY2 = СУММСУММКВ SUMXMY2 = СУММКВРАЗН TAN = TAN TANH = TANH TRUNC = ОТБР ## ## Статистические функции (Statistical Functions) ## AVEDEV = СРОТКЛ AVERAGE = СРЗНАЧ AVERAGEA = СРЗНАЧА AVERAGEIF = СРЗНАЧЕСЛИ AVERAGEIFS = СРЗНАЧЕСЛИМН BETA.DIST = БЕТА.РАСП BETA.INV = БЕТА.ОБР BINOM.DIST = БИНОМ.РАСП BINOM.DIST.RANGE = БИНОМ.РАСП.ДИАП BINOM.INV = БИНОМ.ОБР CHISQ.DIST = ХИ2.РАСП CHISQ.DIST.RT = ХИ2.РАСП.ПХ CHISQ.INV = ХИ2.ОБР CHISQ.INV.RT = ХИ2.ОБР.ПХ CHISQ.TEST = ХИ2.ТЕСТ CONFIDENCE.NORM = ДОВЕРИТ.НОРМ CONFIDENCE.T = ДОВЕРИТ.СТЬЮДЕНТ CORREL = КОРРЕЛ COUNT = СЧЁТ COUNTA = СЧЁТЗ COUNTBLANK = СЧИТАТЬПУСТОТЫ COUNTIF = СЧЁТЕСЛИ COUNTIFS = СЧЁТЕСЛИМН COVARIANCE.P = КОВАРИАЦИЯ.Г COVARIANCE.S = КОВАРИАЦИЯ.В DEVSQ = КВАДРОТКЛ EXPON.DIST = ЭКСП.РАСП F.DIST = F.РАСП F.DIST.RT = F.РАСП.ПХ F.INV = F.ОБР F.INV.RT = F.ОБР.ПХ F.TEST = F.ТЕСТ FISHER = ФИШЕР FISHERINV = ФИШЕРОБР FORECAST.ETS = ПРЕДСКАЗ.ETS FORECAST.ETS.CONFINT = ПРЕДСКАЗ.ЕTS.ДОВИНТЕРВАЛ FORECAST.ETS.SEASONALITY = ПРЕДСКАЗ.ETS.СЕЗОННОСТЬ FORECAST.ETS.STAT = ПРЕДСКАЗ.ETS.СТАТ FORECAST.LINEAR = ПРЕДСКАЗ.ЛИНЕЙН FREQUENCY = ЧАСТОТА GAMMA = ГАММА GAMMA.DIST = ГАММА.РАСП GAMMA.INV = ГАММА.ОБР GAMMALN = ГАММАНЛОГ GAMMALN.PRECISE = ГАММАНЛОГ.ТОЧН GAUSS = ГАУСС GEOMEAN = СРГЕОМ GROWTH = РОСТ HARMEAN = СРГАРМ HYPGEOM.DIST = ГИПЕРГЕОМ.РАСП INTERCEPT = ОТРЕЗОК KURT = ЭКСЦЕСС LARGE = НАИБОЛЬШИЙ LINEST = ЛИНЕЙН LOGEST = ЛГРФПРИБЛ LOGNORM.DIST = ЛОГНОРМ.РАСП LOGNORM.INV = ЛОГНОРМ.ОБР MAX = МАКС MAXA = МАКСА MAXIFS = МАКСЕСЛИ MEDIAN = МЕДИАНА MIN = МИН MINA = МИНА MINIFS = МИНЕСЛИ MODE.MULT = МОДА.НСК MODE.SNGL = МОДА.ОДН NEGBINOM.DIST = ОТРБИНОМ.РАСП NORM.DIST = НОРМ.РАСП NORM.INV = НОРМ.ОБР NORM.S.DIST = НОРМ.СТ.РАСП NORM.S.INV = НОРМ.СТ.ОБР PEARSON = PEARSON PERCENTILE.EXC = ПРОЦЕНТИЛЬ.ИСКЛ PERCENTILE.INC = ПРОЦЕНТИЛЬ.ВКЛ PERCENTRANK.EXC = ПРОЦЕНТРАНГ.ИСКЛ PERCENTRANK.INC = ПРОЦЕНТРАНГ.ВКЛ PERMUT = ПЕРЕСТ PERMUTATIONA = ПЕРЕСТА PHI = ФИ POISSON.DIST = ПУАССОН.РАСП PROB = ВЕРОЯТНОСТЬ QUARTILE.EXC = КВАРТИЛЬ.ИСКЛ QUARTILE.INC = КВАРТИЛЬ.ВКЛ RANK.AVG = РАНГ.СР RANK.EQ = РАНГ.РВ RSQ = КВПИРСОН SKEW = СКОС SKEW.P = СКОС.Г SLOPE = НАКЛОН SMALL = НАИМЕНЬШИЙ STANDARDIZE = НОРМАЛИЗАЦИЯ STDEV.P = СТАНДОТКЛОН.Г STDEV.S = СТАНДОТКЛОН.В STDEVA = СТАНДОТКЛОНА STDEVPA = СТАНДОТКЛОНПА STEYX = СТОШYX T.DIST = СТЬЮДЕНТ.РАСП T.DIST.2T = СТЬЮДЕНТ.РАСП.2Х T.DIST.RT = СТЬЮДЕНТ.РАСП.ПХ T.INV = СТЬЮДЕНТ.ОБР T.INV.2T = СТЬЮДЕНТ.ОБР.2Х T.TEST = СТЬЮДЕНТ.ТЕСТ TREND = ТЕНДЕНЦИЯ TRIMMEAN = УРЕЗСРЕДНЕЕ VAR.P = ДИСП.Г VAR.S = ДИСП.В VARA = ДИСПА VARPA = ДИСПРА WEIBULL.DIST = ВЕЙБУЛЛ.РАСП Z.TEST = Z.ТЕСТ ## ## Текстовые функции (Text Functions) ## ARRAYTOTEXT = МАССИВВТЕКСТ BAHTTEXT = БАТТЕКСТ CHAR = СИМВОЛ CLEAN = ПЕЧСИМВ CODE = КОДСИМВ CONCAT = СЦЕП DBCS = БДЦС DOLLAR = РУБЛЬ EXACT = СОВПАД FIND = НАЙТИ FINDB = НАЙТИБ FIXED = ФИКСИРОВАННЫЙ ISTHAIDIGIT = ЕТАЙЦИФРЫ LEFT = ЛЕВСИМВ LEFTB = ЛЕВБ LEN = ДЛСТР LENB = ДЛИНБ LOWER = СТРОЧН MID = ПСТР MIDB = ПСТРБ NUMBERSTRING = СТРОКАЧИСЕЛ NUMBERVALUE = ЧЗНАЧ PROPER = ПРОПНАЧ REPLACE = ЗАМЕНИТЬ REPLACEB = ЗАМЕНИТЬБ REPT = ПОВТОР RIGHT = ПРАВСИМВ RIGHTB = ПРАВБ SEARCH = ПОИСК SEARCHB = ПОИСКБ SUBSTITUTE = ПОДСТАВИТЬ T = Т TEXT = ТЕКСТ TEXTJOIN = ОБЪЕДИНИТЬ THAIDIGIT = ТАЙЦИФРА THAINUMSOUND = ТАЙЧИСЛОВЗВУК THAINUMSTRING = ТАЙЧИСЛОВСТРОКУ THAISTRINGLENGTH = ТАЙДЛИНАСТРОКИ TRIM = СЖПРОБЕЛЫ UNICHAR = ЮНИСИМВ UNICODE = UNICODE UPPER = ПРОПИСН VALUE = ЗНАЧЕН VALUETOTEXT = ЗНАЧЕНИЕВТЕКСТ ## ## Веб-функции (Web Functions) ## ENCODEURL = КОДИР.URL FILTERXML = ФИЛЬТР.XML WEBSERVICE = ВЕБСЛУЖБА ## ## Функции совместимости (Compatibility Functions) ## BETADIST = БЕТАРАСП BETAINV = БЕТАОБР BINOMDIST = БИНОМРАСП CEILING = ОКРВВЕРХ CHIDIST = ХИ2РАСП CHIINV = ХИ2ОБР CHITEST = ХИ2ТЕСТ CONCATENATE = СЦЕПИТЬ CONFIDENCE = ДОВЕРИТ COVAR = КОВАР CRITBINOM = КРИТБИНОМ EXPONDIST = ЭКСПРАСП FDIST = FРАСП FINV = FРАСПОБР FLOOR = ОКРВНИЗ FORECAST = ПРЕДСКАЗ FTEST = ФТЕСТ GAMMADIST = ГАММАРАСП GAMMAINV = ГАММАОБР HYPGEOMDIST = ГИПЕРГЕОМЕТ LOGINV = ЛОГНОРМОБР LOGNORMDIST = ЛОГНОРМРАСП MODE = МОДА NEGBINOMDIST = ОТРБИНОМРАСП NORMDIST = НОРМРАСП NORMINV = НОРМОБР NORMSDIST = НОРМСТРАСП NORMSINV = НОРМСТОБР PERCENTILE = ПЕРСЕНТИЛЬ PERCENTRANK = ПРОЦЕНТРАНГ POISSON = ПУАССОН QUARTILE = КВАРТИЛЬ RANK = РАНГ STDEV = СТАНДОТКЛОН STDEVP = СТАНДОТКЛОНП TDIST = СТЬЮДРАСП TINV = СТЬЮДРАСПОБР TTEST = ТТЕСТ VAR = ДИСП VARP = ДИСПР WEIBULL = ВЕЙБУЛЛ ZTEST = ZТЕСТ ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/sv/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Svenska (Swedish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #SKÄRNING! DIV0 = #DIVISION/0! VALUE = #VÄRDEFEL! REF = #REFERENS! NAME = #NAMN? NUM = #OGILTIGT! NA = #SAKNAS! ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/sv/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Svenska (Swedish) ## ############################################################ ## ## Kubfunktioner (Cube Functions) ## CUBEKPIMEMBER = KUBKPIMEDLEM CUBEMEMBER = KUBMEDLEM CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM CUBESET = KUBUPPSÄTTNING CUBESETCOUNT = KUBUPPSÄTTNINGANTAL CUBEVALUE = KUBVÄRDE ## ## Databasfunktioner (Database Functions) ## DAVERAGE = DMEDEL DCOUNT = DANTAL DCOUNTA = DANTALV DGET = DHÄMTA DMAX = DMAX DMIN = DMIN DPRODUCT = DPRODUKT DSTDEV = DSTDAV DSTDEVP = DSTDAVP DSUM = DSUMMA DVAR = DVARIANS DVARP = DVARIANSP ## ## Tid- och datumfunktioner (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATUMVÄRDE DAY = DAG DAYS = DAGAR DAYS360 = DAGAR360 EDATE = EDATUM EOMONTH = SLUTMÅNAD HOUR = TIMME ISOWEEKNUM = ISOVECKONR MINUTE = MINUT MONTH = MÅNAD NETWORKDAYS = NETTOARBETSDAGAR NETWORKDAYS.INTL = NETTOARBETSDAGAR.INT NOW = NU SECOND = SEKUND THAIDAYOFWEEK = THAIVECKODAG THAIMONTHOFYEAR = THAIMÅNAD THAIYEAR = THAIÅR TIME = KLOCKSLAG TIMEVALUE = TIDVÄRDE TODAY = IDAG WEEKDAY = VECKODAG WEEKNUM = VECKONR WORKDAY = ARBETSDAGAR WORKDAY.INTL = ARBETSDAGAR.INT YEAR = ÅR YEARFRAC = ÅRDEL ## ## Tekniska funktioner (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.TILL.DEC BIN2HEX = BIN.TILL.HEX BIN2OCT = BIN.TILL.OKT BITAND = BITOCH BITLSHIFT = BITVSKIFT BITOR = BITELLER BITRSHIFT = BITHSKIFT BITXOR = BITXELLER COMPLEX = KOMPLEX CONVERT = KONVERTERA DEC2BIN = DEC.TILL.BIN DEC2HEX = DEC.TILL.HEX DEC2OCT = DEC.TILL.OKT DELTA = DELTA ERF = FELF ERF.PRECISE = FELF.EXAKT ERFC = FELFK ERFC.PRECISE = FELFK.EXAKT GESTEP = SLSTEG HEX2BIN = HEX.TILL.BIN HEX2DEC = HEX.TILL.DEC HEX2OCT = HEX.TILL.OKT IMABS = IMABS IMAGINARY = IMAGINÄR IMARGUMENT = IMARGUMENT IMCONJUGATE = IMKONJUGAT IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEUPPHÖJT IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMUPPHÖJT IMPRODUCT = IMPRODUKT IMREAL = IMREAL IMSEC = IMSEK IMSECH = IMSEKH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMROT IMSUB = IMDIFF IMSUM = IMSUM IMTAN = IMTAN OCT2BIN = OKT.TILL.BIN OCT2DEC = OKT.TILL.DEC OCT2HEX = OKT.TILL.HEX ## ## Finansiella funktioner (Financial Functions) ## ACCRINT = UPPLRÄNTA ACCRINTM = UPPLOBLRÄNTA AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KUPDAGBB COUPDAYS = KUPDAGB COUPDAYSNC = KUPDAGNK COUPNCD = KUPNKD COUPNUM = KUPANT COUPPCD = KUPFKD CUMIPMT = KUMRÄNTA CUMPRINC = KUMPRIS DB = DB DDB = DEGAVSKR DISC = DISK DOLLARDE = DECTAL DOLLARFR = BRÅK DURATION = LÖPTID EFFECT = EFFRÄNTA FV = SLUTVÄRDE FVSCHEDULE = FÖRRÄNTNING INTRATE = ÅRSRÄNTA IPMT = RBETALNING IRR = IR ISPMT = RALÅN MDURATION = MLÖPTID MIRR = MODIR NOMINAL = NOMRÄNTA NPER = PERIODER NPV = NETNUVÄRDE ODDFPRICE = UDDAFPRIS ODDFYIELD = UDDAFAVKASTNING ODDLPRICE = UDDASPRIS ODDLYIELD = UDDASAVKASTNING PDURATION = PLÖPTID PMT = BETALNING PPMT = AMORT PRICE = PRIS PRICEDISC = PRISDISK PRICEMAT = PRISFÖRF PV = NUVÄRDE RATE = RÄNTA RECEIVED = BELOPP RRI = AVKPÅINVEST SLN = LINAVSKR SYD = ÅRSAVSKR TBILLEQ = SSVXEKV TBILLPRICE = SSVXPRIS TBILLYIELD = SSVXRÄNTA VDB = VDEGRAVSKR XIRR = XIRR XNPV = XNUVÄRDE YIELD = NOMAVK YIELDDISC = NOMAVKDISK YIELDMAT = NOMAVKFÖRF ## ## Informationsfunktioner (Information Functions) ## CELL = CELL ERROR.TYPE = FEL.TYP INFO = INFO ISBLANK = ÄRTOM ISERR = ÄRF ISERROR = ÄRFEL ISEVEN = ÄRJÄMN ISFORMULA = ÄRFORMEL ISLOGICAL = ÄRLOGISK ISNA = ÄRSAKNAD ISNONTEXT = ÄREJTEXT ISNUMBER = ÄRTAL ISODD = ÄRUDDA ISREF = ÄRREF ISTEXT = ÄRTEXT N = N NA = SAKNAS SHEET = BLAD SHEETS = ANTALBLAD TYPE = VÄRDETYP ## ## Logiska funktioner (Logical Functions) ## AND = OCH FALSE = FALSKT IF = OM IFERROR = OMFEL IFNA = OMSAKNAS IFS = IFS NOT = ICKE OR = ELLER SWITCH = VÄXLA TRUE = SANT XOR = XELLER ## ## Sök- och referensfunktioner (Lookup & Reference Functions) ## ADDRESS = ADRESS AREAS = OMRÅDEN CHOOSE = VÄLJ COLUMN = KOLUMN COLUMNS = KOLUMNER FORMULATEXT = FORMELTEXT GETPIVOTDATA = HÄMTA.PIVOTDATA HLOOKUP = LETAKOLUMN HYPERLINK = HYPERLÄNK INDEX = INDEX INDIRECT = INDIREKT LOOKUP = LETAUPP MATCH = PASSA OFFSET = FÖRSKJUTNING ROW = RAD ROWS = RADER RTD = RTD TRANSPOSE = TRANSPONERA VLOOKUP = LETARAD *RC = RK ## ## Matematiska och trigonometriska funktioner (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = MÄNGD ARABIC = ARABISKA ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ARCTANH BASE = BAS CEILING.MATH = RUNDA.UPP.MATEMATISKT CEILING.PRECISE = RUNDA.UPP.EXAKT COMBIN = KOMBIN COMBINA = KOMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRADER ECMA.CEILING = ECMA.RUNDA.UPP EVEN = JÄMN EXP = EXP FACT = FAKULTET FACTDOUBLE = DUBBELFAKULTET FLOOR.MATH = RUNDA.NER.MATEMATISKT FLOOR.PRECISE = RUNDA.NER.EXAKT GCD = SGD INT = HELTAL ISO.CEILING = ISO.RUNDA.UPP LCM = MGM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERT MMULT = MMULT MOD = REST MROUND = MAVRUNDA MULTINOMIAL = MULTINOMIAL MUNIT = MENHET ODD = UDDA PI = PI POWER = UPPHÖJT.TILL PRODUCT = PRODUKT QUOTIENT = KVOT RADIANS = RADIANER RAND = SLUMP RANDBETWEEN = SLUMP.MELLAN ROMAN = ROMERSK ROUND = AVRUNDA ROUNDBAHTDOWN = AVRUNDABAHTNEDÅT ROUNDBAHTUP = AVRUNDABAHTUPPÅT ROUNDDOWN = AVRUNDA.NEDÅT ROUNDUP = AVRUNDA.UPPÅT SEC = SEK SECH = SEKH SERIESSUM = SERIESUMMA SIGN = TECKEN SIN = SIN SINH = SINH SQRT = ROT SQRTPI = ROTPI SUBTOTAL = DELSUMMA SUM = SUMMA SUMIF = SUMMA.OM SUMIFS = SUMMA.OMF SUMPRODUCT = PRODUKTSUMMA SUMSQ = KVADRATSUMMA SUMX2MY2 = SUMMAX2MY2 SUMX2PY2 = SUMMAX2PY2 SUMXMY2 = SUMMAXMY2 TAN = TAN TANH = TANH TRUNC = AVKORTA ## ## Statistiska funktioner (Statistical Functions) ## AVEDEV = MEDELAVV AVERAGE = MEDEL AVERAGEA = AVERAGEA AVERAGEIF = MEDEL.OM AVERAGEIFS = MEDEL.OMF BETA.DIST = BETA.FÖRD BETA.INV = BETA.INV BINOM.DIST = BINOM.FÖRD BINOM.DIST.RANGE = BINOM.FÖRD.INTERVALL BINOM.INV = BINOM.INV CHISQ.DIST = CHI2.FÖRD CHISQ.DIST.RT = CHI2.FÖRD.RT CHISQ.INV = CHI2.INV CHISQ.INV.RT = CHI2.INV.RT CHISQ.TEST = CHI2.TEST CONFIDENCE.NORM = KONFIDENS.NORM CONFIDENCE.T = KONFIDENS.T CORREL = KORREL COUNT = ANTAL COUNTA = ANTALV COUNTBLANK = ANTAL.TOMMA COUNTIF = ANTAL.OM COUNTIFS = ANTAL.OMF COVARIANCE.P = KOVARIANS.P COVARIANCE.S = KOVARIANS.S DEVSQ = KVADAVV EXPON.DIST = EXPON.FÖRD F.DIST = F.FÖRD F.DIST.RT = F.FÖRD.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PROGNOS.ETS FORECAST.ETS.CONFINT = PROGNOS.ETS.KONFINT FORECAST.ETS.SEASONALITY = PROGNOS.ETS.SÄSONGSBEROENDE FORECAST.ETS.STAT = PROGNOS.ETS.STAT FORECAST.LINEAR = PROGNOS.LINJÄR FREQUENCY = FREKVENS GAMMA = GAMMA GAMMA.DIST = GAMMA.FÖRD GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.EXAKT GAUSS = GAUSS GEOMEAN = GEOMEDEL GROWTH = EXPTREND HARMEAN = HARMMEDEL HYPGEOM.DIST = HYPGEOM.FÖRD INTERCEPT = SKÄRNINGSPUNKT KURT = TOPPIGHET LARGE = STÖRSTA LINEST = REGR LOGEST = EXPREGR LOGNORM.DIST = LOGNORM.FÖRD LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXIFS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINIFS MODE.MULT = TYPVÄRDE.FLERA MODE.SNGL = TYPVÄRDE.ETT NEGBINOM.DIST = NEGBINOM.FÖRD NORM.DIST = NORM.FÖRD NORM.INV = NORM.INV NORM.S.DIST = NORM.S.FÖRD NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXK PERCENTILE.INC = PERCENTIL.INK PERCENTRANK.EXC = PROCENTRANG.EXK PERCENTRANK.INC = PROCENTRANG.INK PERMUT = PERMUT PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.FÖRD PROB = SANNOLIKHET QUARTILE.EXC = KVARTIL.EXK QUARTILE.INC = KVARTIL.INK RANK.AVG = RANG.MED RANK.EQ = RANG.EKV RSQ = RKV SKEW = SNEDHET SKEW.P = SNEDHET.P SLOPE = LUTNING SMALL = MINSTA STANDARDIZE = STANDARDISERA STDEV.P = STDAV.P STDEV.S = STDAV.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STDFELYX T.DIST = T.FÖRD T.DIST.2T = T.FÖRD.2T T.DIST.RT = T.FÖRD.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = TREND TRIMMEAN = TRIMMEDEL VAR.P = VARIANS.P VAR.S = VARIANS.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.FÖRD Z.TEST = Z.TEST ## ## Textfunktioner (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = TECKENKOD CLEAN = STÄDA CODE = KOD CONCAT = SAMMAN DOLLAR = VALUTA EXACT = EXAKT FIND = HITTA FIXED = FASTTAL LEFT = VÄNSTER LEN = LÄNGD LOWER = GEMENER MID = EXTEXT NUMBERVALUE = TALVÄRDE PROPER = INITIAL REPLACE = ERSÄTT REPT = REP RIGHT = HÖGER SEARCH = SÖK SUBSTITUTE = BYT.UT T = T TEXT = TEXT TEXTJOIN = TEXTJOIN THAIDIGIT = THAISIFFRA THAINUMSOUND = THAITALLJUD THAINUMSTRING = THAITALSTRÄNG THAISTRINGLENGTH = THAISTRÄNGLÄNGD TRIM = RENSA UNICHAR = UNITECKENKOD UNICODE = UNICODE UPPER = VERSALER VALUE = TEXTNUM ## ## Webbfunktioner (Web Functions) ## ENCODEURL = KODAWEBBADRESS FILTERXML = FILTRERAXML WEBSERVICE = WEBBTJÄNST ## ## Kompatibilitetsfunktioner (Compatibility Functions) ## BETADIST = BETAFÖRD BETAINV = BETAINV BINOMDIST = BINOMFÖRD CEILING = RUNDA.UPP CHIDIST = CHI2FÖRD CHIINV = CHI2INV CHITEST = CHI2TEST CONCATENATE = SAMMANFOGA CONFIDENCE = KONFIDENS COVAR = KOVAR CRITBINOM = KRITBINOM EXPONDIST = EXPONFÖRD FDIST = FFÖRD FINV = FINV FLOOR = RUNDA.NER FORECAST = PREDIKTION FTEST = FTEST GAMMADIST = GAMMAFÖRD GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMFÖRD LOGINV = LOGINV LOGNORMDIST = LOGNORMFÖRD MODE = TYPVÄRDE NEGBINOMDIST = NEGBINOMFÖRD NORMDIST = NORMFÖRD NORMINV = NORMINV NORMSDIST = NORMSFÖRD NORMSINV = NORMSINV PERCENTILE = PERCENTIL PERCENTRANK = PROCENTRANG POISSON = POISSON QUARTILE = KVARTIL RANK = RANG STDEV = STDAV STDEVP = STDAVP TDIST = TFÖRD TINV = TINV TTEST = TTEST VAR = VARIANS VARP = VARIANSP WEIBULL = WEIBULL ZTEST = ZTEST ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/tr/config ================================================ ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Türkçe (Turkish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #BOŞ! DIV0 = #SAYI/0! VALUE = #DEĞER! REF = #BAŞV! NAME = #AD? NUM = #SAYI! NA = #YOK ================================================ FILE: src/PhpSpreadsheet/Calculation/locale/tr/functions ================================================ ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Türkçe (Turkish) ## ############################################################ ## ## Küp işlevleri (Cube Functions) ## CUBEKPIMEMBER = KÜPKPIÜYESİ CUBEMEMBER = KÜPÜYESİ CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ CUBERANKEDMEMBER = DERECELİKÜPÜYESİ CUBESET = KÜPKÜMESİ CUBESETCOUNT = KÜPKÜMESAYISI CUBEVALUE = KÜPDEĞERİ ## ## Veritabanı işlevleri (Database Functions) ## DAVERAGE = VSEÇORT DCOUNT = VSEÇSAY DCOUNTA = VSEÇSAYDOLU DGET = VAL DMAX = VSEÇMAK DMIN = VSEÇMİN DPRODUCT = VSEÇÇARP DSTDEV = VSEÇSTDSAPMA DSTDEVP = VSEÇSTDSAPMAS DSUM = VSEÇTOPLA DVAR = VSEÇVAR DVARP = VSEÇVARS ## ## Tarih ve saat işlevleri (Date & Time Functions) ## DATE = TARİH DATEDIF = ETARİHLİ DATESTRING = TARİHDİZİ DATEVALUE = TARİHSAYISI DAY = GÜN DAYS = GÜNSAY DAYS360 = GÜN360 EDATE = SERİTARİH EOMONTH = SERİAY HOUR = SAAT ISOWEEKNUM = ISOHAFTASAY MINUTE = DAKİKA MONTH = AY NETWORKDAYS = TAMİŞGÜNÜ NETWORKDAYS.INTL = TAMİŞGÜNÜ.ULUSL NOW = ŞİMDİ SECOND = SANİYE THAIDAYOFWEEK = TAYHAFTANINGÜNÜ THAIMONTHOFYEAR = TAYYILINAYI THAIYEAR = TAYYILI TIME = ZAMAN TIMEVALUE = ZAMANSAYISI TODAY = BUGÜN WEEKDAY = HAFTANINGÜNÜ WEEKNUM = HAFTASAY WORKDAY = İŞGÜNÜ WORKDAY.INTL = İŞGÜNÜ.ULUSL YEAR = YIL YEARFRAC = YILORAN ## ## Mühendislik işlevleri (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN2DEC BIN2HEX = BIN2HEX BIN2OCT = BIN2OCT BITAND = BİTVE BITLSHIFT = BİTSOLAKAYDIR BITOR = BİTVEYA BITRSHIFT = BİTSAĞAKAYDIR BITXOR = BİTÖZELVEYA COMPLEX = KARMAŞIK CONVERT = ÇEVİR DEC2BIN = DEC2BIN DEC2HEX = DEC2HEX DEC2OCT = DEC2OCT DELTA = DELTA ERF = HATAİŞLEV ERF.PRECISE = HATAİŞLEV.DUYARLI ERFC = TÜMHATAİŞLEV ERFC.PRECISE = TÜMHATAİŞLEV.DUYARLI GESTEP = BESINIR HEX2BIN = HEX2BIN HEX2DEC = HEX2DEC HEX2OCT = HEX2OCT IMABS = SANMUTLAK IMAGINARY = SANAL IMARGUMENT = SANBAĞ_DEĞİŞKEN IMCONJUGATE = SANEŞLENEK IMCOS = SANCOS IMCOSH = SANCOSH IMCOT = SANCOT IMCSC = SANCSC IMCSCH = SANCSCH IMDIV = SANBÖL IMEXP = SANÜS IMLN = SANLN IMLOG10 = SANLOG10 IMLOG2 = SANLOG2 IMPOWER = SANKUVVET IMPRODUCT = SANÇARP IMREAL = SANGERÇEK IMSEC = SANSEC IMSECH = SANSECH IMSIN = SANSIN IMSINH = SANSINH IMSQRT = SANKAREKÖK IMSUB = SANTOPLA IMSUM = SANÇIKAR IMTAN = SANTAN OCT2BIN = OCT2BIN OCT2DEC = OCT2DEC OCT2HEX = OCT2HEX ## ## Finansal işlevler (Financial Functions) ## ACCRINT = GERÇEKFAİZ ACCRINTM = GERÇEKFAİZV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KUPONGÜNBD COUPDAYS = KUPONGÜN COUPDAYSNC = KUPONGÜNDSK COUPNCD = KUPONGÜNSKT COUPNUM = KUPONSAYI COUPPCD = KUPONGÜNÖKT CUMIPMT = TOPÖDENENFAİZ CUMPRINC = TOPANAPARA DB = AZALANBAKİYE DDB = ÇİFTAZALANBAKİYE DISC = İNDİRİM DOLLARDE = LİRAON DOLLARFR = LİRAKES DURATION = SÜRE EFFECT = ETKİN FV = GD FVSCHEDULE = GDPROGRAM INTRATE = FAİZORANI IPMT = FAİZTUTARI IRR = İÇ_VERİM_ORANI ISPMT = ISPMT MDURATION = MSÜRE MIRR = D_İÇ_VERİM_ORANI NOMINAL = NOMİNAL NPER = TAKSİT_SAYISI NPV = NBD ODDFPRICE = TEKYDEĞER ODDFYIELD = TEKYÖDEME ODDLPRICE = TEKSDEĞER ODDLYIELD = TEKSÖDEME PDURATION = PSÜRE PMT = DEVRESEL_ÖDEME PPMT = ANA_PARA_ÖDEMESİ PRICE = DEĞER PRICEDISC = DEĞERİND PRICEMAT = DEĞERVADE PV = BD RATE = FAİZ_ORANI RECEIVED = GETİRİ RRI = GERÇEKLEŞENYATIRIMGETİRİSİ SLN = DA SYD = YAT TBILLEQ = HTAHEŞ TBILLPRICE = HTAHDEĞER TBILLYIELD = HTAHÖDEME VDB = DAB XIRR = AİÇVERİMORANI XNPV = ANBD YIELD = ÖDEME YIELDDISC = ÖDEMEİND YIELDMAT = ÖDEMEVADE ## ## Bilgi işlevleri (Information Functions) ## CELL = HÜCRE ERROR.TYPE = HATA.TİPİ INFO = BİLGİ ISBLANK = EBOŞSA ISERR = EHATA ISERROR = EHATALIYSA ISEVEN = ÇİFTMİ ISFORMULA = EFORMÜLSE ISLOGICAL = EMANTIKSALSA ISNA = EYOKSA ISNONTEXT = EMETİNDEĞİLSE ISNUMBER = ESAYIYSA ISODD = TEKMİ ISREF = EREFSE ISTEXT = EMETİNSE N = S NA = YOKSAY SHEET = SAYFA SHEETS = SAYFALAR TYPE = TÜR ## ## Mantıksal işlevler (Logical Functions) ## AND = VE FALSE = YANLIŞ IF = EĞER IFERROR = EĞERHATA IFNA = EĞERYOKSA IFS = ÇOKEĞER NOT = DEĞİL OR = YADA SWITCH = İLKEŞLEŞEN TRUE = DOĞRU XOR = ÖZELVEYA ## ## Arama ve başvuru işlevleri (Lookup & Reference Functions) ## ADDRESS = ADRES AREAS = ALANSAY CHOOSE = ELEMAN COLUMN = SÜTUN COLUMNS = SÜTUNSAY FORMULATEXT = FORMÜLMETNİ GETPIVOTDATA = ÖZETVERİAL HLOOKUP = YATAYARA HYPERLINK = KÖPRÜ INDEX = İNDİS INDIRECT = DOLAYLI LOOKUP = ARA MATCH = KAÇINCI OFFSET = KAYDIR ROW = SATIR ROWS = SATIRSAY RTD = GZV TRANSPOSE = DEVRİK_DÖNÜŞÜM VLOOKUP = DÜŞEYARA ## ## Matematik ve trigonometri işlevleri (Math & Trig Functions) ## ABS = MUTLAK ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = TOPLAMA ARABIC = ARAP ASIN = ASİN ASINH = ASİNH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = TABAN CEILING.MATH = TAVANAYUVARLA.MATEMATİK CEILING.PRECISE = TAVANAYUVARLA.DUYARLI COMBIN = KOMBİNASYON COMBINA = KOMBİNASYONA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = ONDALIK DEGREES = DERECE ECMA.CEILING = ECMA.TAVAN EVEN = ÇİFT EXP = ÜS FACT = ÇARPINIM FACTDOUBLE = ÇİFTFAKTÖR FLOOR.MATH = TABANAYUVARLA.MATEMATİK FLOOR.PRECISE = TABANAYUVARLA.DUYARLI GCD = OBEB INT = TAMSAYI ISO.CEILING = ISO.TAVAN LCM = OKEK LN = LN LOG = LOG LOG10 = LOG10 MDETERM = DETERMİNANT MINVERSE = DİZEY_TERS MMULT = DÇARP MOD = MOD MROUND = KYUVARLA MULTINOMIAL = ÇOKTERİMLİ MUNIT = BİRİMMATRİS ODD = TEK PI = Pİ POWER = KUVVET PRODUCT = ÇARPIM QUOTIENT = BÖLÜM RADIANS = RADYAN RAND = S_SAYI_ÜRET RANDBETWEEN = RASTGELEARADA ROMAN = ROMEN ROUND = YUVARLA ROUNDBAHTDOWN = BAHTAŞAĞIYUVARLA ROUNDBAHTUP = BAHTYUKARIYUVARLA ROUNDDOWN = AŞAĞIYUVARLA ROUNDUP = YUKARIYUVARLA SEC = SEC SECH = SECH SERIESSUM = SERİTOPLA SIGN = İŞARET SIN = SİN SINH = SİNH SQRT = KAREKÖK SQRTPI = KAREKÖKPİ SUBTOTAL = ALTTOPLAM SUM = TOPLA SUMIF = ETOPLA SUMIFS = ÇOKETOPLA SUMPRODUCT = TOPLA.ÇARPIM SUMSQ = TOPKARE SUMX2MY2 = TOPX2EY2 SUMX2PY2 = TOPX2AY2 SUMXMY2 = TOPXEY2 TAN = TAN TANH = TANH TRUNC = NSAT ## ## İstatistik işlevleri (Statistical Functions) ## AVEDEV = ORTSAP AVERAGE = ORTALAMA AVERAGEA = ORTALAMAA AVERAGEIF = EĞERORTALAMA AVERAGEIFS = ÇOKEĞERORTALAMA BETA.DIST = BETA.DAĞ BETA.INV = BETA.TERS BINOM.DIST = BİNOM.DAĞ BINOM.DIST.RANGE = BİNOM.DAĞ.ARALIK BINOM.INV = BİNOM.TERS CHISQ.DIST = KİKARE.DAĞ CHISQ.DIST.RT = KİKARE.DAĞ.SAĞK CHISQ.INV = KİKARE.TERS CHISQ.INV.RT = KİKARE.TERS.SAĞK CHISQ.TEST = KİKARE.TEST CONFIDENCE.NORM = GÜVENİLİRLİK.NORM CONFIDENCE.T = GÜVENİLİRLİK.T CORREL = KORELASYON COUNT = BAĞ_DEĞ_SAY COUNTA = BAĞ_DEĞ_DOLU_SAY COUNTBLANK = BOŞLUKSAY COUNTIF = EĞERSAY COUNTIFS = ÇOKEĞERSAY COVARIANCE.P = KOVARYANS.P COVARIANCE.S = KOVARYANS.S DEVSQ = SAPKARE EXPON.DIST = ÜSTEL.DAĞ F.DIST = F.DAĞ F.DIST.RT = F.DAĞ.SAĞK F.INV = F.TERS F.INV.RT = F.TERS.SAĞK F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERTERS FORECAST.ETS = TAHMİN.ETS FORECAST.ETS.CONFINT = TAHMİN.ETS.GVNARAL FORECAST.ETS.SEASONALITY = TAHMİN.ETS.MEVSİMSELLİK FORECAST.ETS.STAT = TAHMİN.ETS.İSTAT FORECAST.LINEAR = TAHMİN.DOĞRUSAL FREQUENCY = SIKLIK GAMMA = GAMA GAMMA.DIST = GAMA.DAĞ GAMMA.INV = GAMA.TERS GAMMALN = GAMALN GAMMALN.PRECISE = GAMALN.DUYARLI GAUSS = GAUSS GEOMEAN = GEOORT GROWTH = BÜYÜME HARMEAN = HARORT HYPGEOM.DIST = HİPERGEOM.DAĞ INTERCEPT = KESMENOKTASI KURT = BASIKLIK LARGE = BÜYÜK LINEST = DOT LOGEST = LOT LOGNORM.DIST = LOGNORM.DAĞ LOGNORM.INV = LOGNORM.TERS MAX = MAK MAXA = MAKA MAXIFS = ÇOKEĞERMAK MEDIAN = ORTANCA MIN = MİN MINA = MİNA MINIFS = ÇOKEĞERMİN MODE.MULT = ENÇOK_OLAN.ÇOK MODE.SNGL = ENÇOK_OLAN.TEK NEGBINOM.DIST = NEGBİNOM.DAĞ NORM.DIST = NORM.DAĞ NORM.INV = NORM.TERS NORM.S.DIST = NORM.S.DAĞ NORM.S.INV = NORM.S.TERS PEARSON = PEARSON PERCENTILE.EXC = YÜZDEBİRLİK.HRC PERCENTILE.INC = YÜZDEBİRLİK.DHL PERCENTRANK.EXC = YÜZDERANK.HRC PERCENTRANK.INC = YÜZDERANK.DHL PERMUT = PERMÜTASYON PERMUTATIONA = PERMÜTASYONA PHI = PHI POISSON.DIST = POISSON.DAĞ PROB = OLASILIK QUARTILE.EXC = DÖRTTEBİRLİK.HRC QUARTILE.INC = DÖRTTEBİRLİK.DHL RANK.AVG = RANK.ORT RANK.EQ = RANK.EŞİT RSQ = RKARE SKEW = ÇARPIKLIK SKEW.P = ÇARPIKLIK.P SLOPE = EĞİM SMALL = KÜÇÜK STANDARDIZE = STANDARTLAŞTIRMA STDEV.P = STDSAPMA.P STDEV.S = STDSAPMA.S STDEVA = STDSAPMAA STDEVPA = STDSAPMASA STEYX = STHYX T.DIST = T.DAĞ T.DIST.2T = T.DAĞ.2K T.DIST.RT = T.DAĞ.SAĞK T.INV = T.TERS T.INV.2T = T.TERS.2K T.TEST = T.TEST TREND = EĞİLİM TRIMMEAN = KIRPORTALAMA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARSA WEIBULL.DIST = WEIBULL.DAĞ Z.TEST = Z.TEST ## ## Metin işlevleri (Text Functions) ## BAHTTEXT = BAHTMETİN CHAR = DAMGA CLEAN = TEMİZ CODE = KOD CONCAT = ARALIKBİRLEŞTİR DOLLAR = LİRA EXACT = ÖZDEŞ FIND = BUL FIXED = SAYIDÜZENLE ISTHAIDIGIT = TAYRAKAMIYSA LEFT = SOLDAN LEN = UZUNLUK LOWER = KÜÇÜKHARF MID = PARÇAAL NUMBERSTRING = SAYIDİZİ NUMBERVALUE = SAYIDEĞERİ PHONETIC = SES PROPER = YAZIM.DÜZENİ REPLACE = DEĞİŞTİR REPT = YİNELE RIGHT = SAĞDAN SEARCH = MBUL SUBSTITUTE = YERİNEKOY T = M TEXT = METNEÇEVİR TEXTJOIN = METİNBİRLEŞTİR THAIDIGIT = TAYRAKAM THAINUMSOUND = TAYSAYISES THAINUMSTRING = TAYSAYIDİZE THAISTRINGLENGTH = TAYDİZEUZUNLUĞU TRIM = KIRP UNICHAR = UNICODEKARAKTERİ UNICODE = UNICODE UPPER = BÜYÜKHARF VALUE = SAYIYAÇEVİR ## ## Metin işlevleri (Web Functions) ## ENCODEURL = URLKODLA FILTERXML = XMLFİLTRELE WEBSERVICE = WEBHİZMETİ ## ## Uyumluluk işlevleri (Compatibility Functions) ## BETADIST = BETADAĞ BETAINV = BETATERS BINOMDIST = BİNOMDAĞ CEILING = TAVANAYUVARLA CHIDIST = KİKAREDAĞ CHIINV = KİKARETERS CHITEST = KİKARETEST CONCATENATE = BİRLEŞTİR CONFIDENCE = GÜVENİRLİK COVAR = KOVARYANS CRITBINOM = KRİTİKBİNOM EXPONDIST = ÜSTELDAĞ FDIST = FDAĞ FINV = FTERS FLOOR = TABANAYUVARLA FORECAST = TAHMİN FTEST = FTEST GAMMADIST = GAMADAĞ GAMMAINV = GAMATERS HYPGEOMDIST = HİPERGEOMDAĞ LOGINV = LOGTERS LOGNORMDIST = LOGNORMDAĞ MODE = ENÇOK_OLAN NEGBINOMDIST = NEGBİNOMDAĞ NORMDIST = NORMDAĞ NORMINV = NORMTERS NORMSDIST = NORMSDAĞ NORMSINV = NORMSTERS PERCENTILE = YÜZDEBİRLİK PERCENTRANK = YÜZDERANK POISSON = POISSON QUARTILE = DÖRTTEBİRLİK RANK = RANK STDEV = STDSAPMA STDEVP = STDSAPMAS TDIST = TDAĞ TINV = TTERS TTEST = TTEST VAR = VAR VARP = VARS WEIBULL = WEIBULL ZTEST = ZTEST ================================================ FILE: src/PhpSpreadsheet/Cell/AddressHelper.php ================================================ setValueExplicit(true, DataType::TYPE_BOOL); return true; } elseif (StringHelper::strToUpper($value) === Calculation::getFALSE()) { $cell->setValueExplicit(false, DataType::TYPE_BOOL); return true; } // Check for fractions if (preg_match('~^([+-]?)\s*(\d+)\s*/\s*(\d+)$~', $value, $matches)) { return $this->setProperFraction($matches, $cell); } elseif (preg_match('~^([+-]?)(\d+)\s+(\d+)\s*/\s*(\d+)$~', $value, $matches)) { return $this->setImproperFraction($matches, $cell); } $decimalSeparatorNoPreg = StringHelper::getDecimalSeparator(); $decimalSeparator = preg_quote($decimalSeparatorNoPreg, '/'); $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); // Check for percentage if (preg_match('/^\-?\d*' . $decimalSeparator . '?\d*\s?\%$/', (string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value))) { return $this->setPercentage((string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value), $cell); } // Check for currency if (preg_match(FormattedNumber::currencyMatcherRegexp(), (string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value), $matches, PREG_UNMATCHED_AS_NULL)) { // Convert value to number $sign = ($matches['PrefixedSign'] ?? $matches['PrefixedSign2'] ?? $matches['PostfixedSign']) ?? null; $currencyCode = $matches['PrefixedCurrency'] ?? $matches['PostfixedCurrency'] ?? ''; /** @var string */ $temp = str_replace([$decimalSeparatorNoPreg, $currencyCode, ' ', '-'], ['.', '', '', ''], (string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value)); $value = (float) ($sign . trim($temp)); return $this->setCurrency($value, $cell, $currencyCode); } // Check for time without seconds e.g. '9:45', '09:45' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) { return $this->setTimeHoursMinutes($value, $cell); } // Check for time with seconds '9:45:59', '09:45:59' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) { return $this->setTimeHoursMinutesSeconds($value, $cell); } // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' if (($d = Date::stringToExcel($value)) !== false) { // Convert value to number $cell->setValueExplicit($d, DataType::TYPE_NUMERIC); // Determine style. Either there is a time part or not. Look for ':' if (str_contains($value, ':')) { $formatCode = 'yyyy-mm-dd h:mm'; } else { $formatCode = 'yyyy-mm-dd'; } $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($formatCode); return true; } // Check for newline character "\n" if (str_contains($value, "\n")) { $cell->setValueExplicit($value, DataType::TYPE_STRING); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getAlignment()->setWrapText(true); return true; } } // Not bound yet? Use parent... return parent::bindValue($cell, $value); } /** @param array{0: string, 1: ?string, 2: numeric-string, 3: numeric-string, 4: numeric-string} $matches */ protected function setImproperFraction(array $matches, Cell $cell): bool { // Convert value to number $value = $matches[2] + ($matches[3] / $matches[4]); if ($matches[1] === '-') { $value = 0 - $value; } $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); // Build the number format mask based on the size of the matched values $dividend = str_repeat('?', strlen($matches[3])); $divisor = str_repeat('?', strlen($matches[4])); $fractionMask = "# {$dividend}/{$divisor}"; // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($fractionMask); return true; } /** @param array{0: string, 1: ?string, 2: numeric-string, 3: numeric-string} $matches */ protected function setProperFraction(array $matches, Cell $cell): bool { // Convert value to number $value = $matches[2] / $matches[3]; if ($matches[1] === '-') { $value = 0 - $value; } $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); // Build the number format mask based on the size of the matched values $dividend = str_repeat('?', strlen($matches[2])); $divisor = str_repeat('?', strlen($matches[3])); $fractionMask = "{$dividend}/{$divisor}"; // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($fractionMask); return true; } protected function setPercentage(string $value, Cell $cell): bool { // Convert value to number $value = ((float) str_replace('%', '', $value)) / 100; $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00); return true; } protected function setCurrency(float $value, Cell $cell, string $currencyCode): bool { $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode( str_replace('$', '[$' . $currencyCode . ']', NumberFormat::FORMAT_CURRENCY_USD) ); return true; } protected function setTimeHoursMinutes(string $value, Cell $cell): bool { // Convert value to number [$hours, $minutes] = explode(':', $value); $hours = (int) $hours; $minutes = (int) $minutes; $days = ($hours / 24) + ($minutes / 1440); $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3); return true; } protected function setTimeHoursMinutesSeconds(string $value, Cell $cell): bool { // Convert value to number [$hours, $minutes, $seconds] = explode(':', $value); $hours = (int) $hours; $minutes = (int) $minutes; $seconds = (int) $seconds; $days = ($hours / 24) + ($minutes / 1440) + ($seconds / 86400); $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); return true; } } ================================================ FILE: src/PhpSpreadsheet/Cell/Cell.php ================================================ */ private ?array $formulaAttributes = null; private IgnoredErrors $ignoredErrors; /** * Update the cell into the cell collection. * * @throws SpreadsheetException */ public function updateInCollection(): self { $parent = $this->parent; if ($parent === null) { throw new SpreadsheetException('Cannot update when cell is not bound to a worksheet'); } $parent->update($this); return $this; } public function detach(): void { $this->parent = null; } public function attach(Cells $parent): void { $this->parent = $parent; } /** * Create a new Cell. * * @throws SpreadsheetException */ public function __construct(mixed $value, ?string $dataType, Worksheet $worksheet) { // Initialise cell value $this->value = $value; // Set worksheet cache $this->parent = $worksheet->getCellCollection(); // Set datatype? if ($dataType !== null) { if ($dataType == DataType::TYPE_STRING2) { $dataType = DataType::TYPE_STRING; } $this->dataType = $dataType; } else { $valueBinder = $worksheet->getParent()?->getValueBinder() ?? self::getValueBinder(); if ($valueBinder->bindValue($this, $value) === false) { throw new SpreadsheetException('Value could not be bound to cell.'); } } $this->ignoredErrors = new IgnoredErrors(); } /** * Get cell coordinate column. * * @throws SpreadsheetException */ public function getColumn(): string { $parent = $this->parent; if ($parent === null) { throw new SpreadsheetException('Cannot get column when cell is not bound to a worksheet'); } return $parent->getCurrentColumn(); } /** * Get cell coordinate row. * * @throws SpreadsheetException */ public function getRow(): int { $parent = $this->parent; if ($parent === null) { throw new SpreadsheetException('Cannot get row when cell is not bound to a worksheet'); } return $parent->getCurrentRow(); } /** * Get cell coordinate. * * @throws SpreadsheetException */ public function getCoordinate(): string { $parent = $this->parent; if ($parent !== null) { $coordinate = $parent->getCurrentCoordinate(); } else { $coordinate = null; } if ($coordinate === null) { throw new SpreadsheetException('Coordinate no longer exists'); } return $coordinate; } /** * Get cell value. */ public function getValue(): mixed { return $this->value; } public function getValueString(): string { return StringHelper::convertToString($this->value, false); } /** * Get cell value with formatting. */ public function getFormattedValue(): string { $currentCalendar = SharedDate::getExcelCalendar(); SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar()); $formattedValue = (string) NumberFormat::toFormattedString( $this->getCalculatedValueString(), (string) $this->getStyle()->getNumberFormat()->getFormatCode(true) ); SharedDate::setExcelCalendar($currentCalendar); return $formattedValue; } protected static function updateIfCellIsTableHeader(?Worksheet $workSheet, self $cell, mixed $oldValue, mixed $newValue): void { $oldValue = StringHelper::convertToString($oldValue, false); $newValue = StringHelper::convertToString($newValue, false); if (StringHelper::strToLower($oldValue) === StringHelper::strToLower($newValue) || $workSheet === null) { return; } foreach ($workSheet->getTableCollection() as $table) { /** @var Table $table */ if ($cell->isInRange($table->getRange())) { $rangeRowsColumns = Coordinate::getRangeBoundaries($table->getRange()); if ($cell->getRow() === (int) $rangeRowsColumns[0][1]) { Table\Column::updateStructuredReferences($workSheet, $oldValue, $newValue); } return; } } } /** * Set cell value. * * Sets the value for a cell, automatically determining the datatype using the value binder * * @param mixed $value Value * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder * * @throws SpreadsheetException */ public function setValue(mixed $value, ?IValueBinder $binder = null): self { if ($this->hadHyperlink) { $this->clearHyperlink(); } // Cells?->Worksheet?->Spreadsheet $binder ??= $this->parent?->getParent()?->getParent()?->getValueBinder() ?? self::getValueBinder(); if (!$binder->bindValue($this, $value)) { throw new SpreadsheetException('Value could not be bound to cell.'); } return $this; } private bool $hadHyperlink = false; /** @internal */ public function setHadHyperlink(bool $hadHyperlink): void { $this->hadHyperlink = $hadHyperlink; } private function clearHyperlink(): void { $worksheet = $this->getWorksheetOrNull(); if ($worksheet !== null) { $coordinate = $this->getCoordinate(); $worksheet->setHyperlink($coordinate, null); } $this->hadHyperlink = false; } /** * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder). * * @param mixed $value Value * @param string $dataType Explicit data type, see DataType::TYPE_* * This parameter is currently optional (default = string). * Omitting it is ***DEPRECATED***, and the default will be removed in a future release. * Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this * method, then it is your responsibility as an end-user developer to validate that the value and * the datatype match. * If you do mismatch value and datatype, then the value you enter may be changed to match the datatype * that you specify. * * @throws SpreadsheetException */ public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE_STRING): self { if ($this->hadHyperlink) { $this->clearHyperlink(); } $oldValue = $this->value; $quotePrefix = false; // set the value according to data type switch ($dataType) { case DataType::TYPE_NULL: $this->value = null; break; case DataType::TYPE_STRING2: $dataType = DataType::TYPE_STRING; // no break case DataType::TYPE_STRING: // Synonym for string if (is_string($value) && strlen($value) > 1 && $value[0] === '=') { $quotePrefix = true; } // no break case DataType::TYPE_INLINE: // Rich text $value2 = StringHelper::convertToString($value, true); // Cells?->Worksheet?->Spreadsheet $binder = $this->parent?->getParent()?->getParent()?->getValueBinder(); $preserveCr = false; if ($binder !== null && method_exists($binder, 'getPreserveCr')) { /** @var bool */ $preserveCr = $binder->getPreserveCr(); } $this->value = DataType::checkString(($value instanceof RichText) ? $value : $value2, $preserveCr); break; case DataType::TYPE_NUMERIC: if ($value !== null && !is_bool($value) && !is_numeric($value)) { throw new SpreadsheetException('Invalid numeric value for datatype Numeric'); } $this->value = 0 + $value; break; case DataType::TYPE_FORMULA: $this->value = StringHelper::convertToString($value, true); break; case DataType::TYPE_BOOL: $this->value = (bool) $value; break; case DataType::TYPE_ISO_DATE: $this->value = SharedDate::convertIsoDate($value); $dataType = DataType::TYPE_NUMERIC; break; case DataType::TYPE_DRAWING_IN_CELL: if ($value instanceof BaseDrawing) { $this->value = $value; } else { throw new SpreadsheetException('Item is not a drawing'); } break; case DataType::TYPE_ERROR: $this->value = DataType::checkErrorCode($value); break; default: throw new SpreadsheetException('Invalid datatype: ' . $dataType); } // set the datatype $this->dataType = $dataType; $this->updateInCollection(); $cellCoordinate = $this->getCoordinate(); self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value); $worksheet = $this->getWorksheet(); $spreadsheet = $worksheet->getParent(); if (isset($spreadsheet) && $spreadsheet->getIndex($worksheet, true) >= 0) { $originalSelected = $worksheet->getSelectedCells(); $activeSheetIndex = $spreadsheet->getActiveSheetIndex(); $style = $this->getStyle(); $oldQuotePrefix = $style->getQuotePrefix(); if ($oldQuotePrefix !== $quotePrefix) { $style->setQuotePrefix($quotePrefix); } $worksheet->setSelectedCells($originalSelected); if ($activeSheetIndex >= 0) { $spreadsheet->setActiveSheetIndex($activeSheetIndex); } } return $this->getParent()?->get($cellCoordinate) ?? $this; } public const CALCULATE_DATE_TIME_ASIS = 0; public const CALCULATE_DATE_TIME_FLOAT = 1; public const CALCULATE_TIME_FLOAT = 2; private static int $calculateDateTimeType = self::CALCULATE_DATE_TIME_ASIS; public static function getCalculateDateTimeType(): int { return self::$calculateDateTimeType; } /** @throws CalculationException */ public static function setCalculateDateTimeType(int $calculateDateTimeType): void { self::$calculateDateTimeType = match ($calculateDateTimeType) { self::CALCULATE_DATE_TIME_ASIS, self::CALCULATE_DATE_TIME_FLOAT, self::CALCULATE_TIME_FLOAT => $calculateDateTimeType, default => throw new CalculationException("Invalid value $calculateDateTimeType for calculated date time type"), }; } /** * Convert date, time, or datetime from int to float if desired. */ private function convertDateTimeInt(mixed $result): mixed { if (is_int($result)) { if (self::$calculateDateTimeType === self::CALCULATE_TIME_FLOAT) { if (SharedDate::isDateTime($this, $result, false)) { $result = (float) $result; } } elseif (self::$calculateDateTimeType === self::CALCULATE_DATE_TIME_FLOAT) { if (SharedDate::isDateTime($this, $result, true)) { $result = (float) $result; } } } return $result; } /** * Get calculated cell value converted to string. */ public function getCalculatedValueString(): string { $value = $this->getCalculatedValue(); while (is_array($value)) { $value = array_shift($value); } return StringHelper::convertToString($value, false); } /** * Get calculated cell value. * * @param bool $resetLog Whether the calculation engine logger should be reset or not * * @throws CalculationException */ public function getCalculatedValue(bool $resetLog = true): mixed { $title = 'unknown'; $oldAttributes = $this->formulaAttributes; $oldAttributesT = $oldAttributes['t'] ?? ''; $coordinate = $this->getCoordinate(); $oldAttributesRef = $oldAttributes['ref'] ?? $coordinate; $originalValue = $this->value; $originalDataType = $this->dataType; $this->formulaAttributes = []; $spill = false; if ($this->dataType === DataType::TYPE_FORMULA) { try { $currentCalendar = SharedDate::getExcelCalendar(); SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar()); $thisworksheet = $this->getWorksheet(); $index = $thisworksheet->getParentOrThrow()->getActiveSheetIndex(); $selected = $thisworksheet->getSelectedCells(); $title = $thisworksheet->getTitle(); $calculation = Calculation::getInstance($thisworksheet->getParent()); $result = $calculation->calculateCellValue($this, $resetLog); $result = $this->convertDateTimeInt($result); $thisworksheet->setSelectedCells($selected); $thisworksheet->getParentOrThrow()->setActiveSheetIndex($index); if (is_array($result) && $calculation->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) { while (is_array($result)) { $result = array_shift($result); } } if ( !is_array($result) && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY && $oldAttributesT === 'array' && ($oldAttributesRef === $coordinate || $oldAttributesRef === "$coordinate:$coordinate") ) { $result = [$result]; } // if return_as_array for formula like '=sheet!cell' if (is_array($result) && count($result) === 1) { $resultKey = array_keys($result)[0]; $resultValue = $result[$resultKey]; if (is_int($resultKey) && is_array($resultValue) && count($resultValue) === 1) { $resultKey2 = array_keys($resultValue)[0]; $resultValue2 = $resultValue[$resultKey2]; if (is_string($resultKey2) && !is_array($resultValue2) && preg_match('/[a-zA-Z]{1,3}/', $resultKey2) === 1) { $result = $resultValue2; } } } $newColumn = $this->getColumn(); if (is_array($result)) { $result = self::convertSpecialArray($result); $this->formulaAttributes['t'] = 'array'; $this->formulaAttributes['ref'] = $maxCoordinate = $coordinate; $newRow = $row = $this->getRow(); $column = $this->getColumn(); foreach ($result as $resultRow) { if (is_array($resultRow)) { $newColumn = $column; foreach ($resultRow as $resultValue) { if ($row !== $newRow || $column !== $newColumn) { $maxCoordinate = $newColumn . $newRow; if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) { if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) { $spill = true; break; } } } /** @var string $newColumn */ StringHelper::stringIncrement($newColumn); } ++$newRow; } else { if ($row !== $newRow || $column !== $newColumn) { $maxCoordinate = $newColumn . $newRow; if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) { if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) { $spill = true; } } } StringHelper::stringIncrement($newColumn); } if ($spill) { break; } } if (!$spill) { $this->formulaAttributes['ref'] .= ":$maxCoordinate"; } $thisworksheet->getCell($column . $row); } if (is_array($result)) { if ($oldAttributes !== null && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) { if (($oldAttributesT) === 'array') { $thisworksheet = $this->getWorksheet(); $coordinate = $this->getCoordinate(); $ref = $oldAttributesRef; if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches) === 1) { if (isset($matches[3])) { $minCol = $matches[1]; $minRow = (int) $matches[2]; $maxCol = $matches[4]; StringHelper::stringIncrement($maxCol); $maxRow = (int) $matches[5]; for ($row = $minRow; $row <= $maxRow; ++$row) { for ($col = $minCol; $col !== $maxCol; StringHelper::stringIncrement($col)) { /** @var string $col */ if ("$col$row" !== $coordinate) { $thisworksheet->getCell("$col$row")->setValue(null); } } } } } $thisworksheet->getCell($coordinate); } } } if ($spill) { $result = ExcelError::SPILL(); } if (is_array($result)) { $newRow = $row = $this->getRow(); $newColumn = $column = $this->getColumn(); foreach ($result as $resultRow) { if (is_array($resultRow)) { $newColumn = $column; foreach ($resultRow as $resultValue) { if ($row !== $newRow || $column !== $newColumn) { $thisworksheet ->getCell($newColumn . $newRow) ->setValue($resultValue); } StringHelper::stringIncrement($newColumn); } ++$newRow; } else { if ($row !== $newRow || $column !== $newColumn) { $thisworksheet->getCell($newColumn . $newRow)->setValue($resultRow); } StringHelper::stringIncrement($newColumn); } } $thisworksheet->getCell($column . $row); $this->value = $originalValue; $this->dataType = $originalDataType; } } catch (SpreadsheetException $ex) { SharedDate::setExcelCalendar($currentCalendar); if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { return $this->calculatedValue; // Fallback for calculations referencing external files. } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) { return ExcelError::NAME(); } throw new CalculationException( $title . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage(), $ex->getCode(), $ex ); } SharedDate::setExcelCalendar($currentCalendar); if ($result === Functions::NOT_YET_IMPLEMENTED) { $this->formulaAttributes = $oldAttributes; return $this->calculatedValue; // Fallback if calculation engine does not support the formula. } return $result; } elseif ($this->value instanceof RichText) { return $this->value->getPlainText(); } return $this->convertDateTimeInt($this->value); } /** * Convert array like the following (preserve values, lose indexes): * [ * rowNumber1 => [colLetter1 => value, colLetter2 => value ...], * rowNumber2 => [colLetter1 => value, colLetter2 => value ...], * ... * ]. * * @param mixed[] $array * * @return mixed[] */ private static function convertSpecialArray(array $array): array { $newArray = []; foreach ($array as $rowIndex => $row) { if (!is_int($rowIndex) || $rowIndex <= 0 || !is_array($row)) { return $array; } $keys = array_keys($row); $key0 = $keys[0] ?? ''; if (!is_string($key0)) { return $array; } $newArray[] = array_values($row); } return $newArray; } /** * Set old calculated value (cached). * * @param mixed $originalValue Value */ public function setCalculatedValue(mixed $originalValue, bool $tryNumeric = true): self { if ($originalValue !== null) { $this->calculatedValue = ($tryNumeric && is_numeric($originalValue)) ? (0 + $originalValue) : $originalValue; } return $this->updateInCollection(); } /** * Get old calculated value (cached) * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to * create the original spreadsheet file. * Note that this value is not guaranteed to reflect the actual calculated value because it is * possible that auto-calculation was disabled in the original spreadsheet, and underlying data * values used by the formula have changed since it was last calculated. */ public function getOldCalculatedValue(): mixed { return $this->calculatedValue; } /** * Get cell data type. */ public function getDataType(): string { return $this->dataType; } /** * Set cell data type. * * @param string $dataType see DataType::TYPE_* */ public function setDataType(string $dataType): self { $this->setValueExplicit($this->value, $dataType); return $this; } /** * Identify if the cell contains a formula. */ public function isFormula(): bool { return $this->dataType === DataType::TYPE_FORMULA && $this->getStyle()->getQuotePrefix() === false; } /** * Does this cell contain Data validation rules? * * @throws SpreadsheetException */ public function hasDataValidation(): bool { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot check for data validation when cell is not bound to a worksheet'); } return $this->getWorksheet()->dataValidationExists($this->getCoordinate()); } /** * Get Data validation rules. * * @throws SpreadsheetException */ public function getDataValidation(): DataValidation { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot get data validation for cell that is not bound to a worksheet'); } return $this->getWorksheet()->getDataValidation($this->getCoordinate()); } /** * Set Data validation rules. * * @throws SpreadsheetException */ public function setDataValidation(?DataValidation $dataValidation = null): self { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot set data validation for cell that is not bound to a worksheet'); } $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation); return $this->updateInCollection(); } /** * Does this cell contain valid value? */ public function hasValidValue(): bool { $validator = new DataValidator(); return $validator->isValid($this); } /** * Does this cell contain a Hyperlink? * * @throws SpreadsheetException */ public function hasHyperlink(): bool { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot check for hyperlink when cell is not bound to a worksheet'); } return $this->getWorksheet()->hyperlinkExists($this->getCoordinate()); } /** * Get Hyperlink. * * @throws SpreadsheetException */ public function getHyperlink(): Hyperlink { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot get hyperlink for cell that is not bound to a worksheet'); } return $this->getWorksheet() ->getHyperlink($this->getCoordinate()); } /** * Set Hyperlink. * * @throws SpreadsheetException */ public function setHyperlink(?Hyperlink $hyperlink = null): self { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot set hyperlink for cell that is not bound to a worksheet'); } $this->getWorksheet() ->setHyperlink($this->getCoordinate(), $hyperlink); return $this->updateInCollection(); } /** * Get cell collection. */ public function getParent(): ?Cells { return $this->parent; } /** * Get parent worksheet. * * @throws SpreadsheetException */ public function getWorksheet(): Worksheet { $parent = $this->parent; if ($parent !== null) { $worksheet = $parent->getParent(); } else { $worksheet = null; } if ($worksheet === null) { throw new SpreadsheetException('Worksheet no longer exists'); } return $worksheet; } public function getWorksheetOrNull(): ?Worksheet { $parent = $this->parent; if ($parent !== null) { $worksheet = $parent->getParent(); } else { $worksheet = null; } return $worksheet; } /** * Is this cell in a merge range. */ public function isInMergeRange(): bool { return (bool) $this->getMergeRange(); } /** * Is this cell the master (top left cell) in a merge range (that holds the actual data value). */ public function isMergeRangeValueCell(): bool { if ($mergeRange = $this->getMergeRange()) { $mergeRange = Coordinate::splitRange($mergeRange); [$startCell] = $mergeRange[0]; return $this->getCoordinate() === $startCell; } return false; } /** * If this cell is in a merge range, then return the range. * * @return false|string */ public function getMergeRange() { foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) { if ($this->isInRange($mergeRange)) { return $mergeRange; } } return false; } /** * Get cell style. */ public function getStyle(): Style { return $this->getWorksheet()->getStyle($this->getCoordinate()); } /** * Get cell style. */ public function getAppliedStyle(): Style { if ($this->getWorksheet()->conditionalStylesExists($this->getCoordinate()) === false) { return $this->getStyle(); } $range = $this->getWorksheet()->getConditionalRange($this->getCoordinate()); if ($range === null) { return $this->getStyle(); } $matcher = new CellStyleAssessor($this, $range); return $matcher->matchConditions($this->getWorksheet()->getConditionalStyles($this->getCoordinate())); } /** * Re-bind parent. */ public function rebindParent(Worksheet $parent): self { $this->parent = $parent->getCellCollection(); return $this->updateInCollection(); } /** * Is cell in a specific range? * * @param string $range Cell range (e.g. A1:A1) */ public function isInRange(string $range): bool { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); // Translate properties $myColumn = Coordinate::columnIndexFromString($this->getColumn()); $myRow = $this->getRow(); // Verify if cell is in range return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow); } /** * Compare 2 cells. * * @param Cell $a Cell a * @param Cell $b Cell b * * @return int Result of comparison (always -1 or 1, never zero!) */ public static function compareCells(self $a, self $b): int { if ($a->getRow() < $b->getRow()) { return -1; } elseif ($a->getRow() > $b->getRow()) { return 1; } elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) { return -1; } return 1; } /** * Get value binder to use. */ public static function getValueBinder(): IValueBinder { if (self::$valueBinder === null) { self::$valueBinder = new DefaultValueBinder(); } return self::$valueBinder; } /** * Set value binder to use. */ public static function setValueBinder(IValueBinder $binder): void { self::$valueBinder = $binder; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $propertyName => $propertyValue) { if ((is_object($propertyValue)) && ($propertyName !== 'parent')) { $this->$propertyName = clone $propertyValue; } else { $this->$propertyName = $propertyValue; } } } /** * Get index to cellXf. */ public function getXfIndex(): int { return $this->xfIndex; } /** * Set index to cellXf. */ public function setXfIndex(int $indexValue): self { $this->xfIndex = $indexValue; return $this->updateInCollection(); } /** * Set the formula attributes. * * @param null|array $attributes */ public function setFormulaAttributes(?array $attributes): self { $this->formulaAttributes = $attributes; return $this; } /** * Get the formula attributes. * * @return null|array */ public function getFormulaAttributes(): mixed { return $this->formulaAttributes; } /** * Convert to string. */ public function __toString(): string { $retVal = $this->value; return StringHelper::convertToString($retVal, false); } public function getIgnoredErrors(): IgnoredErrors { return $this->ignoredErrors; } public function isLocked(): bool { $protected = $this->parent?->getParent()?->getProtection()?->getSheet(); if ($protected !== true) { return false; } $locked = $this->getStyle()->getProtection()->getLocked(); return $locked !== Protection::PROTECTION_UNPROTECTED; } public function isHiddenOnFormulaBar(): bool { if ($this->getDataType() !== DataType::TYPE_FORMULA) { return false; } $protected = $this->parent?->getParent()?->getProtection()?->getSheet(); if ($protected !== true) { return false; } $hidden = $this->getStyle()->getProtection()->getHidden(); return $hidden !== Protection::PROTECTION_UNPROTECTED; } } ================================================ FILE: src/PhpSpreadsheet/Cell/CellAddress.php ================================================ cellAddress = str_replace('$', '', $cellAddress); [$this->columnId, $this->rowId, $this->columnName] = Coordinate::indexesFromString($this->cellAddress); $this->worksheet = $worksheet; } public function __destruct() { unset($this->worksheet); } /** * @phpstan-assert int|numeric-string $columnId * @phpstan-assert int|numeric-string $rowId */ private static function validateColumnAndRow(int|string $columnId, int|string $rowId): void { if (!is_numeric($columnId) || $columnId <= 0 || !is_numeric($rowId) || $rowId <= 0) { throw new Exception('Row and Column Ids must be positive integer values'); } } public static function fromColumnAndRow(int|string $columnId, int|string $rowId, ?Worksheet $worksheet = null): self { self::validateColumnAndRow($columnId, $rowId); return new self(Coordinate::stringFromColumnIndex($columnId) . $rowId, $worksheet); } /** @param array $array */ public static function fromColumnRowArray(array $array, ?Worksheet $worksheet = null): self { [$columnId, $rowId] = $array; return self::fromColumnAndRow($columnId, $rowId, $worksheet); } public static function fromCellAddress(string $cellAddress, ?Worksheet $worksheet = null): self { return new self($cellAddress, $worksheet); } /** * The returned address string will contain the worksheet name as well, if available, * (ie. if a Worksheet was provided to the constructor). * e.g. "'Mark''s Worksheet'!C5". */ public function fullCellAddress(): string { if ($this->worksheet !== null) { $title = str_replace("'", "''", $this->worksheet->getTitle()); return "'{$title}'!{$this->cellAddress}"; } return $this->cellAddress; } public function worksheet(): ?Worksheet { return $this->worksheet; } /** * The returned address string will contain just the column/row address, * (even if a Worksheet was provided to the constructor). * e.g. "C5". */ public function cellAddress(): string { return $this->cellAddress; } public function rowId(): int { return $this->rowId; } public function columnId(): int { return $this->columnId; } public function columnName(): string { return $this->columnName; } public function nextRow(int $offset = 1): self { $newRowId = $this->rowId + $offset; if ($newRowId < 1) { $newRowId = 1; } return self::fromColumnAndRow($this->columnId, $newRowId); } public function previousRow(int $offset = 1): self { return $this->nextRow(0 - $offset); } public function nextColumn(int $offset = 1): self { $newColumnId = $this->columnId + $offset; if ($newColumnId < 1) { $newColumnId = 1; } return self::fromColumnAndRow($newColumnId, $this->rowId); } public function previousColumn(int $offset = 1): self { return $this->nextColumn(0 - $offset); } /** * The returned address string will contain the worksheet name as well, if available, * (ie. if a Worksheet was provided to the constructor). * e.g. "'Mark''s Worksheet'!C5". */ public function __toString(): string { return $this->fullCellAddress(); } } ================================================ FILE: src/PhpSpreadsheet/Cell/CellRange.php ================================================ */ class CellRange implements AddressRange, Stringable { protected CellAddress $from; protected CellAddress $to; public function __construct(CellAddress $from, CellAddress $to) { $this->validateFromTo($from, $to); } private function validateFromTo(CellAddress $from, CellAddress $to): void { // Identify actual top-left and bottom-right values (in case we've been given top-right and bottom-left) $firstColumn = min($from->columnId(), $to->columnId()); $firstRow = min($from->rowId(), $to->rowId()); $lastColumn = max($from->columnId(), $to->columnId()); $lastRow = max($from->rowId(), $to->rowId()); $fromWorksheet = $from->worksheet(); $toWorksheet = $to->worksheet(); $this->validateWorksheets($fromWorksheet, $toWorksheet); $this->from = $this->cellAddressWrapper($firstColumn, $firstRow, $fromWorksheet); $this->to = $this->cellAddressWrapper($lastColumn, $lastRow, $toWorksheet); } private function validateWorksheets(?Worksheet $fromWorksheet, ?Worksheet $toWorksheet): void { if ($fromWorksheet !== null && $toWorksheet !== null) { // We could simply compare worksheets rather than worksheet titles; but at some point we may introduce // support for 3d ranges; and at that point we drop this check and let the validation fall through // to the check for same workbook; but unless we check on titles, this test will also detect if the // worksheets are in different spreadsheets, and the next check will never execute or throw its // own exception. if ($fromWorksheet->getTitle() !== $toWorksheet->getTitle()) { throw new Exception('3d Cell Ranges are not supported'); } elseif ($fromWorksheet->getParent() !== $toWorksheet->getParent()) { throw new Exception('Worksheets must be in the same spreadsheet'); } } } private function cellAddressWrapper(int $column, int $row, ?Worksheet $worksheet = null): CellAddress { $cellAddress = Coordinate::stringFromColumnIndex($column) . (string) $row; return new class ($cellAddress, $worksheet) extends CellAddress { public function nextRow(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::nextRow($offset); $this->rowId = $result->rowId; $this->cellAddress = $result->cellAddress; return $this; } public function previousRow(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::previousRow($offset); $this->rowId = $result->rowId; $this->cellAddress = $result->cellAddress; return $this; } public function nextColumn(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::nextColumn($offset); $this->columnId = $result->columnId; $this->columnName = $result->columnName; $this->cellAddress = $result->cellAddress; return $this; } public function previousColumn(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::previousColumn($offset); $this->columnId = $result->columnId; $this->columnName = $result->columnName; $this->cellAddress = $result->cellAddress; return $this; } }; } public function from(): CellAddress { // Re-order from/to in case the cell addresses have been modified $this->validateFromTo($this->from, $this->to); return $this->from; } public function to(): CellAddress { // Re-order from/to in case the cell addresses have been modified $this->validateFromTo($this->from, $this->to); return $this->to; } public function __toString(): string { // Re-order from/to in case the cell addresses have been modified $this->validateFromTo($this->from, $this->to); if ($this->from->cellAddress() === $this->to->cellAddress()) { return "{$this->from->fullCellAddress()}"; } $fromAddress = $this->from->fullCellAddress(); $toAddress = $this->to->cellAddress(); return "{$fromAddress}:{$toAddress}"; } } ================================================ FILE: src/PhpSpreadsheet/Cell/ColumnRange.php ================================================ */ class ColumnRange implements AddressRange, Stringable { protected ?Worksheet $worksheet; protected int $from; protected int $to; public function __construct(string $from, ?string $to = null, ?Worksheet $worksheet = null) { $this->validateFromTo( Coordinate::columnIndexFromString($from), Coordinate::columnIndexFromString($to ?? $from) ); $this->worksheet = $worksheet; } public function __destruct() { $this->worksheet = null; } public static function fromColumnIndexes(int $from, int $to, ?Worksheet $worksheet = null): self { return new self(Coordinate::stringFromColumnIndex($from), Coordinate::stringFromColumnIndex($to), $worksheet); } /** * @param array $array */ public static function fromArray(array $array, ?Worksheet $worksheet = null): self { array_walk( $array, function (&$column): void { $column = is_numeric($column) ? Coordinate::stringFromColumnIndex((int) $column) : $column; } ); /** @var string $from */ /** @var string $to */ [$from, $to] = $array; return new self($from, $to, $worksheet); } private function validateFromTo(int $from, int $to): void { // Identify actual top and bottom values (in case we've been given bottom and top) $this->from = min($from, $to); $this->to = max($from, $to); } public function columnCount(): int { return $this->to - $this->from + 1; } public function shiftDown(int $offset = 1): self { $newFrom = $this->from + $offset; $newFrom = ($newFrom < 1) ? 1 : $newFrom; $newTo = $this->to + $offset; $newTo = ($newTo < 1) ? 1 : $newTo; return self::fromColumnIndexes($newFrom, $newTo, $this->worksheet); } public function shiftUp(int $offset = 1): self { return $this->shiftDown(0 - $offset); } public function from(): string { return Coordinate::stringFromColumnIndex($this->from); } public function to(): string { return Coordinate::stringFromColumnIndex($this->to); } public function fromIndex(): int { return $this->from; } public function toIndex(): int { return $this->to; } public function toCellRange(): CellRange { return new CellRange( CellAddress::fromColumnAndRow($this->from, 1, $this->worksheet), CellAddress::fromColumnAndRow($this->to, AddressRange::MAX_ROW) ); } public function __toString(): string { $from = $this->from(); $to = $this->to(); if ($this->worksheet !== null) { $title = str_replace("'", "''", $this->worksheet->getTitle()); return "'{$title}'!{$from}:{$to}"; } return "{$from}:{$to}"; } } ================================================ FILE: src/PhpSpreadsheet/Cell/Coordinate.php ================================================ \$?[A-Z]{1,3})(?\$?\d{1,7})$/i'; public const FULL_REFERENCE_REGEX = '/^(?:(?[^!]*)!)?(?(?[$]?[A-Z]{1,3}[$]?\d{1,7})(?:\:(?[$]?[A-Z]{1,3}[$]?\d{1,7}))?)$/i'; /** * Default range variable constant. * * @var string */ const DEFAULT_RANGE = 'A1:A1'; /** * Convert string coordinate to [0 => int column index, 1 => int row index]. * * @param string $cellAddress eg: 'A1' * * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1) */ public static function coordinateFromString(string $cellAddress): array { if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) { $row = (int) ltrim($matches['row'], '$'); // reluctantly allow row 0 due to regression problems if (/*$row > 0 &&*/ $row <= AddressRange::MAX_ROW) { return [$matches['col'], $matches['row']]; } } elseif (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string'); } throw new Exception('Invalid cell coordinate ' . $cellAddress); } /** * Convert string coordinate to [0 => int column index, 1 => int row index, 2 => string column string]. * * @param string $coordinates eg: 'A1', '$B$12' * * @return array{0: int, 1: int, 2: string} Array containing column and row index, and column string */ public static function indexesFromString(string $coordinates): array { [$column, $row] = self::coordinateFromString($coordinates); $column = ltrim($column, '$'); return [ self::columnIndexFromString($column), (int) ltrim($row, '$'), $column, ]; } /** * Checks if a Cell Address represents a range of cells. * * @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2' * * @return bool Whether the coordinate represents a range of cells */ public static function coordinateIsRange(string $cellAddress): bool { return str_contains($cellAddress, ':') || str_contains($cellAddress, ','); } /** * Make string row, column or cell coordinate absolute. * * @param int|string $cellAddress e.g. 'A' or '1' or 'A1' * Note that this value can be a row or column reference as well as a cell reference * * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' */ public static function absoluteReference(int|string $cellAddress): string { $cellAddress = (string) $cellAddress; if (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } // Split out any worksheet name from the reference [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate $cellAddress = "$cellAddress"; if (ctype_digit($cellAddress)) { return $worksheet . '$' . $cellAddress; } elseif (ctype_alpha($cellAddress)) { return $worksheet . '$' . strtoupper($cellAddress); } return $worksheet . self::absoluteCoordinate($cellAddress); } /** * Make string coordinate absolute. * * @param string $cellAddress e.g. 'A1' * * @return string Absolute coordinate e.g. '$A$1' */ public static function absoluteCoordinate(string $cellAddress): string { if (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } // Split out any worksheet name from the coordinate [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate [$column, $row] = self::coordinateFromString($cellAddress ?? 'A1'); $column = ltrim($column, '$'); $row = ltrim($row, '$'); return $worksheet . '$' . $column . '$' . $row; } /** * Split range into coordinate strings, using comma for union * and ignoring intersection (space). * * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' * * @return array> Array containing one or more arrays containing one or two coordinate strings * e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']] * or ['B4'] */ public static function splitRange(string $range): array { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } $exploded = explode(',', $range); $outArray = []; foreach ($exploded as $value) { $outArray[] = explode(':', $value); } return $outArray; } /** * Split range into coordinate strings, resolving unions and intersections. * * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' * @param bool $unionIsComma true=comma is union, space is intersection * false=space is union, comma is intersection * * @return array> Array containing one or more arrays containing one or two coordinate strings * e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']] * or ['B4'] */ public static function allRanges(string $range, bool $unionIsComma = true): array { if (!$unionIsComma) { $range = str_replace([',', ' ', "\0"], ["\0", ',', ' '], $range); } return self::splitRange( self::resolveUnionAndIntersection($range) ); } /** * Build range from coordinate strings. * * @param mixed[] $range Array containing one or more arrays containing one or two coordinate strings * * @return string String representation of $pRange */ public static function buildRange(array $range): string { // Verify range if (empty($range)) { throw new Exception('Range does not contain any information'); } // Build range $counter = count($range); for ($i = 0; $i < $counter; ++$i) { if (!is_array($range[$i])) { throw new Exception('Each array entry must be an array'); } $range[$i] = implode(':', $range[$i]); } return implode(',', $range); } /** * Calculate range boundaries. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array{array{int, int}, array{int, int}} Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays (Column Number, Row Number) */ public static function rangeBoundaries(string $range): array { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } // Uppercase coordinate $range = strtoupper($range); // Extract range if (!str_contains($range, ':')) { $rangeA = $rangeB = $range; } else { [$rangeA, $rangeB] = explode(':', $range); } if (is_numeric($rangeA) && is_numeric($rangeB)) { $rangeA = 'A' . $rangeA; $rangeB = AddressRange::MAX_COLUMN . $rangeB; } if (ctype_alpha($rangeA) && ctype_alpha($rangeB)) { $rangeA = $rangeA . '1'; $rangeB = $rangeB . AddressRange::MAX_ROW; } // Calculate range outer borders $rangeStart = self::coordinateFromString($rangeA); $rangeEnd = self::coordinateFromString($rangeB); // Translate column into index $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); $rangeStart[1] = (int) $rangeStart[1]; $rangeEnd[1] = (int) $rangeEnd[1]; return [$rangeStart, $rangeEnd]; } /** * Calculate range dimension. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array{int, int} Range dimension (width, height) */ public static function rangeDimension(string $range): array { // Calculate range outer borders [$rangeStart, $rangeEnd] = self::rangeBoundaries($range); return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)]; } /** * Calculate range boundaries. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array{array{string, int}, array{string, int}} Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays [Column ID, Row Number] */ public static function getRangeBoundaries(string $range): array { [$rangeA, $rangeB] = self::rangeBoundaries($range); return [ [self::stringFromColumnIndex($rangeA[0]), $rangeA[1]], [self::stringFromColumnIndex($rangeB[0]), $rangeB[1]], ]; } /** * Check if cell or range reference is valid and return an array with type of reference (cell or range), worksheet (if it was given) * and the coordinate or the first coordinate and second coordinate if it is a range. * * @param string $reference Coordinate or Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array{type: string, firstCoordinate?: string, secondCoordinate?: string, coordinate?: string, worksheet?: string, localReference?: string} reference data */ private static function validateReferenceAndGetData($reference): array { $data = []; if (1 !== preg_match(self::FULL_REFERENCE_REGEX, $reference, $matches)) { return ['type' => 'invalid']; } if (isset($matches['secondCoordinate'])) { $data['type'] = 'range'; $data['firstCoordinate'] = str_replace('$', '', $matches['firstCoordinate']); $data['secondCoordinate'] = str_replace('$', '', $matches['secondCoordinate']); } else { $data['type'] = 'coordinate'; $data['coordinate'] = str_replace('$', '', $matches['firstCoordinate']); } $worksheet = $matches['worksheet']; if ($worksheet !== '') { if (str_starts_with($worksheet, "'") && str_ends_with($worksheet, "'")) { $worksheet = substr($worksheet, 1, -1); } $data['worksheet'] = strtolower($worksheet); } $data['localReference'] = str_replace('$', '', $matches['localReference']); return $data; } /** * Check if coordinate is inside a range. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * @param string $coordinate Cell coordinate (e.g. A1) * * @return bool true if coordinate is inside range */ public static function coordinateIsInsideRange(string $range, string $coordinate): bool { $range = Validations::convertWholeRowColumn($range); $rangeData = self::validateReferenceAndGetData($range); if ($rangeData['type'] === 'invalid') { throw new Exception('First argument needs to be a range'); } $coordinateData = self::validateReferenceAndGetData($coordinate); if ($coordinateData['type'] === 'invalid') { throw new Exception('Second argument needs to be a single coordinate'); } if (isset($coordinateData['worksheet']) && !isset($rangeData['worksheet'])) { return false; } if (!isset($coordinateData['worksheet']) && isset($rangeData['worksheet'])) { return false; } if (isset($coordinateData['worksheet'], $rangeData['worksheet'])) { if ($coordinateData['worksheet'] !== $rangeData['worksheet']) { return false; } } if (!isset($rangeData['localReference'])) { return false; } $boundaries = self::rangeBoundaries($rangeData['localReference']); if (!isset($coordinateData['localReference'])) { return false; } $coordinates = self::indexesFromString($coordinateData['localReference']); $columnIsInside = $boundaries[0][0] <= $coordinates[0] && $coordinates[0] <= $boundaries[1][0]; if (!$columnIsInside) { return false; } $rowIsInside = $boundaries[0][1] <= $coordinates[1] && $coordinates[1] <= $boundaries[1][1]; if (!$rowIsInside) { return false; } return true; } /** * Column index from string. * * @param ?string $columnAddress eg 'A' * * @return int Column index (A = 1) */ public static function columnIndexFromString(?string $columnAddress): int { // Using a lookup cache adds a slight memory overhead, but boosts speed // caching using a static within the method is faster than a class static, // though it's additional memory overhead /** @var int[] */ static $indexCache = []; $columnAddress = $columnAddress ?? ''; if (isset($indexCache[$columnAddress])) { return $indexCache[$columnAddress]; } // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array // rather than use ord() and make it case-insensitive to get rid of the strtoupper() as well. // Because it's a static, there's no significant memory overhead either. /** @var array */ static $columnLookup = [ 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26, 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26, ]; // We also use the language construct isset() rather than the more costly strlen() function to match the // length of $columnAddress for improved performance if (isset($columnAddress[0])) { if (!isset($columnAddress[1])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress]; return $indexCache[$columnAddress]; } if (!isset($columnAddress[2])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]]; return $indexCache[$columnAddress]; } if (!isset($columnAddress[3])) { $temp = $columnLookup[$columnAddress[0]] * 676 + $columnLookup[$columnAddress[1]] * 26 + $columnLookup[$columnAddress[2]]; if ($temp <= AddressRange::MAX_COLUMN_INT) { $indexCache[$columnAddress] = $temp; return $temp; } } } throw new Exception( 'Column string index can not be ' . ((isset($columnAddress[0])) ? ('beyond ' . AddressRange::MAX_COLUMN) : 'empty') ); } private const LOOKUP_CACHE = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * String from column index. * * @param int|numeric-string $columnIndex Column index (A = 1) */ public static function stringFromColumnIndex(int|string $columnIndex, bool $tolerateZero = false): string { /** @var string[] */ static $indexCache = []; $columnIndex2 = (int) $columnIndex; if ($columnIndex2 === 0 && $tolerateZero) { return ''; } if ($columnIndex2 < 1 || $columnIndex2 > AddressRange::MAX_COLUMN_INT) { throw new Exception("Invalid column index $columnIndex"); } $columnIndex = $columnIndex2; if (!isset($indexCache[$columnIndex])) { $indexValue = $columnIndex; $base26 = ''; do { $characterValue = ($indexValue % 26) ?: 26; $indexValue = ($indexValue - $characterValue) / 26; $base26 = self::LOOKUP_CACHE[$characterValue] . $base26; } while ($indexValue > 0); $indexCache[$columnIndex] = $base26; } return $indexCache[$columnIndex]; } /** * Extract all cell references in range, which may be comprised of multiple cell ranges. * * @param string $cellRange Range: e.g. 'A1' or 'A1:C10' or 'A1:E10,A20:E25' or 'A1:E5 C3:G7' or 'A1:C1,A3:C3 B1:C3' * * @return string[] Array containing single cell references */ public static function extractAllCellReferencesInRange(string $cellRange): array { if (substr_count($cellRange, '!') > 1) { throw new Exception('3-D Range References are not supported'); } [$worksheet, $cellRange] = Worksheet::extractSheetTitle($cellRange, true); $quoted = ''; if ($worksheet) { $quoted = Worksheet::nameRequiresQuotes($worksheet) ? "'" : ''; if (str_starts_with($worksheet, "'") && str_ends_with($worksheet, "'")) { $worksheet = substr($worksheet, 1, -1); } $worksheet = str_replace("'", "''", $worksheet); } [$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange ?? 'A1'); $cells = []; foreach ($ranges as $range) { /** @var string $range */ $cells[] = self::getReferencesForCellBlock($range); } /** @var mixed[] */ $cells = self::processRangeSetOperators($operators, $cells); if (empty($cells)) { return []; } /** @var string[] */ $cellList = array_merge(...$cells); //* @phpstan-ignore-line // Unsure how to satisfy phpstan in line above $retVal = array_map( fn (string $cellAddress) => ($worksheet !== '') ? "{$quoted}{$worksheet}{$quoted}!{$cellAddress}" : $cellAddress, self::sortCellReferenceArray($cellList) ); return $retVal; } /** * @param mixed[] $operators * @param mixed[][] $cells * * @return mixed[] */ private static function processRangeSetOperators(array $operators, array $cells): array { $operatorCount = count($operators); for ($offset = 0; $offset < $operatorCount; ++$offset) { $operator = $operators[$offset]; if ($operator !== ' ') { continue; } $cells[$offset] = array_intersect($cells[$offset], $cells[$offset + 1]); unset($operators[$offset], $cells[$offset + 1]); $operators = array_values($operators); $cells = array_values($cells); --$offset; --$operatorCount; } return $cells; } /** * @param string[] $cellList * * @return string[] */ private static function sortCellReferenceArray(array $cellList): array { // Sort the result by column and row $sortKeys = []; foreach ($cellList as $coordinate) { $column = ''; $row = 0; sscanf($coordinate, '%[A-Z]%d', $column, $row); /** @var int $row */ $key = (--$row * AddressRange::MAX_COLUMN_INT) + self::columnIndexFromString((string) $column); $sortKeys[$key] = $coordinate; } ksort($sortKeys); return array_values($sortKeys); } /** * Get all cell references applying union and intersection. * * @param string $cellBlock A cell range e.g. A1:B5,D1:E5 B2:C4 * * @return string A string without intersection operator. * If there was no intersection to begin with, return original argument. * Otherwise, return cells and/or cell ranges in that range separated by comma. */ public static function resolveUnionAndIntersection(string $cellBlock, string $implodeCharacter = ','): string { $cellBlock = preg_replace('/ +/', ' ', trim($cellBlock)) ?? $cellBlock; $cellBlock = preg_replace('/ ,/', ',', $cellBlock) ?? $cellBlock; $cellBlock = preg_replace('/, /', ',', $cellBlock) ?? $cellBlock; $array1 = []; $blocks = explode(',', $cellBlock); foreach ($blocks as $block) { $block0 = explode(' ', $block); if (count($block0) === 1) { $array1 = array_merge($array1, $block0); } else { $blockIdx = -1; $array2 = []; foreach ($block0 as $block00) { ++$blockIdx; if ($blockIdx === 0) { $array2 = self::getReferencesForCellBlock($block00); } else { $array2 = array_intersect($array2, self::getReferencesForCellBlock($block00)); } } $array1 = array_merge($array1, $array2); } } return implode($implodeCharacter, $array1); } /** * Get all cell references for an individual cell block. * * @param string $cellBlock A cell range e.g. A4:B5 * * @return string[] All individual cells in that range */ private static function getReferencesForCellBlock(string $cellBlock): array { $returnValue = []; // Single cell? if (!self::coordinateIsRange($cellBlock)) { return (array) $cellBlock; } // Range... $ranges = self::splitRange($cellBlock); foreach ($ranges as $range) { // Single cell? if (!isset($range[1])) { $returnValue[] = $range[0]; continue; } // Range... [$rangeStart, $rangeEnd] = $range; [$startColumn, $startRow] = self::coordinateFromString($rangeStart); [$endColumn, $endRow] = self::coordinateFromString($rangeEnd); $startColumnIndex = self::columnIndexFromString($startColumn); $endColumnIndex = self::columnIndexFromString($endColumn); ++$endColumnIndex; // Current data $currentColumnIndex = $startColumnIndex; $currentRow = $startRow; self::validateRange($cellBlock, $startColumnIndex, $endColumnIndex, (int) $currentRow, (int) $endRow); // Loop cells while ($currentColumnIndex < $endColumnIndex) { /** @var int $currentRow */ /** @var int $endRow */ while ($currentRow <= $endRow) { $returnValue[] = self::stringFromColumnIndex($currentColumnIndex) . $currentRow; ++$currentRow; } ++$currentColumnIndex; $currentRow = $startRow; } } return $returnValue; } /** * Convert an associative array of single cell coordinates to values to an associative array * of cell ranges to values. Only adjacent cell coordinates with the same * value will be merged. If the value is an object, it must implement the method getHashCode(). * * For example, this function converts: * * [ 'A1' => 'x', 'A2' => 'x', 'A3' => 'x', 'A4' => 'y' ] * * to: * * [ 'A1:A3' => 'x', 'A4' => 'y' ] * * @param array $coordinateCollection associative array mapping coordinates to values * * @return array associative array mapping coordinate ranges to values */ public static function mergeRangesInCollection(array $coordinateCollection): array { $hashedValues = []; $mergedCoordCollection = []; foreach ($coordinateCollection as $coord => $value) { if (self::coordinateIsRange($coord)) { $mergedCoordCollection[$coord] = $value; continue; } [$column, $row] = self::coordinateFromString($coord); $row = (int) (ltrim($row, '$')); $hashCode = $column . '-' . StringHelper::convertToString((is_object($value) && method_exists($value, 'getHashCode')) ? $value->getHashCode() : $value); if (!isset($hashedValues[$hashCode])) { $hashedValues[$hashCode] = (object) [ 'value' => $value, 'col' => $column, 'rows' => [$row], ]; } else { $hashedValues[$hashCode]->rows[] = $row; } } ksort($hashedValues); foreach ($hashedValues as $hashedValue) { sort($hashedValue->rows); $rowStart = null; $rowEnd = null; $ranges = []; foreach ($hashedValue->rows as $row) { if ($rowStart === null) { $rowStart = $row; $rowEnd = $row; } elseif ($rowEnd === $row - 1) { $rowEnd = $row; } else { if ($rowStart == $rowEnd) { $ranges[] = $hashedValue->col . $rowStart; } else { $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd; } $rowStart = $row; $rowEnd = $row; } } if ($rowStart !== null) { // @phpstan-ignore-line if ($rowStart == $rowEnd) { $ranges[] = $hashedValue->col . $rowStart; } else { $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd; } } foreach ($ranges as $range) { $mergedCoordCollection[$range] = $hashedValue->value; } } return $mergedCoordCollection; } /** * Get the individual cell blocks from a range string, removing any $ characters. * then splitting by operators and returning an array with ranges and operators. * * @return mixed[][] */ private static function getCellBlocksFromRangeString(string $rangeString): array { $rangeString = str_replace('$', '', strtoupper($rangeString)); // split range sets on intersection (space) or union (,) operators $tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE) ?: []; $split = array_chunk($tokens, 2); $ranges = array_column($split, 0); $operators = array_column($split, 1); return [$ranges, $operators]; } /** * Check that the given range is valid, i.e. that the start column and row are not greater than the end column and * row. * * @param string $cellBlock The original range, for displaying a meaningful error message */ private static function validateRange(string $cellBlock, int $startColumnIndex, int $endColumnIndex, int $currentRow, int $endRow): void { if ($startColumnIndex >= $endColumnIndex || $currentRow > $endRow) { throw new Exception('Invalid range: "' . $cellBlock . '"'); } } } ================================================ FILE: src/PhpSpreadsheet/Cell/DataType.php ================================================ */ private static array $errorCodes = [ '#NULL!' => 0, '#DIV/0!' => 1, '#VALUE!' => 2, '#REF!' => 3, '#NAME?' => 4, '#NUM!' => 5, '#N/A' => 6, '#CALC!' => 7, ]; public const MAX_STRING_LENGTH = 32767; /** * Get list of error codes. * * @return array */ public static function getErrorCodes(): array { return self::$errorCodes; } /** * Check a string that it satisfies Excel requirements. * * @param null|RichText|string $textValue Value to sanitize to an Excel string * * @return RichText|string Sanitized value */ public static function checkString(null|RichText|string $textValue, bool $preserveCr = false): RichText|string { if ($textValue instanceof RichText) { // TODO: Sanitize Rich-Text string (max. character count is 32,767) return $textValue; } // string must never be longer than 32,767 characters, truncate if necessary $textValue = StringHelper::substring((string) $textValue, 0, self::MAX_STRING_LENGTH); // we require that newline is represented as "\n" in core, not as "\r\n" or "\r" if (!$preserveCr) { $textValue = str_replace(["\r\n", "\r"], "\n", $textValue); } return $textValue; } /** * Check a value that it is a valid error code. * * @param mixed $value Value to sanitize to an Excel error code * * @return string Sanitized value */ public static function checkErrorCode(mixed $value): string { $default = '#NULL!'; $value = ($value === null) ? $default : StringHelper::convertToString($value, false, $default); if (!isset(self::$errorCodes[$value])) { $value = $default; } return $value; } } ================================================ FILE: src/PhpSpreadsheet/Cell/DataValidation.php ================================================ formula1; } /** * Set Formula 1. * * @return $this */ public function setFormula1(string $formula): static { $this->formula1 = $formula; return $this; } /** * Get Formula 2. */ public function getFormula2(): string { return $this->formula2; } /** * Set Formula 2. * * @return $this */ public function setFormula2(string $formula): static { $this->formula2 = $formula; return $this; } /** * Get Type. */ public function getType(): string { return $this->type; } /** * Set Type. * * @return $this */ public function setType(string $type): static { $this->type = $type; return $this; } /** * Get Error style. */ public function getErrorStyle(): string { return $this->errorStyle; } /** * Set Error style. * * @param string $errorStyle see self::STYLE_* * * @return $this */ public function setErrorStyle(string $errorStyle): static { $this->errorStyle = $errorStyle; return $this; } /** * Get Operator. */ public function getOperator(): string { return $this->operator; } /** * Set Operator. * * @return $this */ public function setOperator(string $operator): static { $this->operator = ($operator === '') ? self::DEFAULT_OPERATOR : $operator; return $this; } /** * Get Allow Blank. */ public function getAllowBlank(): bool { return $this->allowBlank; } /** * Set Allow Blank. * * @return $this */ public function setAllowBlank(bool $allowBlank): static { $this->allowBlank = $allowBlank; return $this; } /** * Get Show DropDown. */ public function getShowDropDown(): bool { return $this->showDropDown; } /** * Set Show DropDown. * * @return $this */ public function setShowDropDown(bool $showDropDown): static { $this->showDropDown = $showDropDown; return $this; } /** * Get Show InputMessage. */ public function getShowInputMessage(): bool { return $this->showInputMessage; } /** * Set Show InputMessage. * * @return $this */ public function setShowInputMessage(bool $showInputMessage): static { $this->showInputMessage = $showInputMessage; return $this; } /** * Get Show ErrorMessage. */ public function getShowErrorMessage(): bool { return $this->showErrorMessage; } /** * Set Show ErrorMessage. * * @return $this */ public function setShowErrorMessage(bool $showErrorMessage): static { $this->showErrorMessage = $showErrorMessage; return $this; } /** * Get Error title. */ public function getErrorTitle(): string { return $this->errorTitle; } /** * Set Error title. * * @return $this */ public function setErrorTitle(string $errorTitle): static { $this->errorTitle = $errorTitle; return $this; } /** * Get Error. */ public function getError(): string { return $this->error; } /** * Set Error. * * @return $this */ public function setError(string $error): static { $this->error = $error; return $this; } /** * Get Prompt title. */ public function getPromptTitle(): string { return $this->promptTitle; } /** * Set Prompt title. * * @return $this */ public function setPromptTitle(string $promptTitle): static { $this->promptTitle = $promptTitle; return $this; } /** * Get Prompt. */ public function getPrompt(): string { return $this->prompt; } /** * Set Prompt. * * @return $this */ public function setPrompt(string $prompt): static { $this->prompt = $prompt; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->formula1 . $this->formula2 . $this->type . $this->errorStyle . $this->operator . ($this->allowBlank ? 't' : 'f') . ($this->showDropDown ? 't' : 'f') . ($this->showInputMessage ? 't' : 'f') . ($this->showErrorMessage ? 't' : 'f') . $this->errorTitle . $this->error . $this->promptTitle . $this->prompt . $this->sqref . __CLASS__ ); } private ?string $sqref = null; public function getSqref(): ?string { return $this->sqref; } public function setSqref(?string $str): self { $this->sqref = $str; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Cell/DataValidator.php ================================================ hasDataValidation() || $cell->getDataValidation()->getType() === DataValidation::TYPE_NONE) { return true; } $cellValue = $cell->getValue(); $dataValidation = $cell->getDataValidation(); if (!$dataValidation->getAllowBlank() && ($cellValue === null || $cellValue === '')) { return false; } $returnValue = false; $type = $dataValidation->getType(); if ($type === DataValidation::TYPE_LIST) { $returnValue = $this->isValueInList($cell); } elseif ($type === DataValidation::TYPE_WHOLE) { if (!is_numeric($cellValue) || fmod((float) $cellValue, 1) != 0) { $returnValue = false; } else { $returnValue = $this->numericOperator($dataValidation, (int) $cellValue, $cell); } } elseif ($type === DataValidation::TYPE_DECIMAL || $type === DataValidation::TYPE_DATE || $type === DataValidation::TYPE_TIME) { if (!is_numeric($cellValue)) { $returnValue = false; } else { $returnValue = $this->numericOperator($dataValidation, (float) $cellValue, $cell); } } elseif ($type === DataValidation::TYPE_TEXTLENGTH) { $returnValue = $this->numericOperator($dataValidation, mb_strlen($cell->getValueString()), $cell); } return $returnValue; } private const TWO_FORMULAS = [DataValidation::OPERATOR_BETWEEN, DataValidation::OPERATOR_NOTBETWEEN]; private static function evaluateNumericFormula(mixed $formula, Cell $cell): mixed { if (!is_numeric($formula)) { $calculation = Calculation::getInstance($cell->getWorksheet()->getParent()); try { $formula2 = StringHelper::convertToString($formula); $result = $calculation ->calculateFormula("=$formula2", $cell->getCoordinate(), $cell); while (is_array($result)) { $result = array_pop($result); } $formula = $result; } catch (Exception) { // do nothing } } return $formula; } private function numericOperator(DataValidation $dataValidation, int|float $cellValue, Cell $cell): bool { $operator = $dataValidation->getOperator(); $formula1 = self::evaluateNumericFormula( $dataValidation->getFormula1(), $cell ); $formula2 = 0; if (in_array($operator, self::TWO_FORMULAS, true)) { $formula2 = self::evaluateNumericFormula( $dataValidation->getFormula2(), $cell ); } return match ($operator) { DataValidation::OPERATOR_BETWEEN => $cellValue >= $formula1 && $cellValue <= $formula2, DataValidation::OPERATOR_NOTBETWEEN => $cellValue < $formula1 || $cellValue > $formula2, DataValidation::OPERATOR_EQUAL => $cellValue == $formula1, DataValidation::OPERATOR_NOTEQUAL => $cellValue != $formula1, DataValidation::OPERATOR_LESSTHAN => $cellValue < $formula1, DataValidation::OPERATOR_LESSTHANOREQUAL => $cellValue <= $formula1, DataValidation::OPERATOR_GREATERTHAN => $cellValue > $formula1, DataValidation::OPERATOR_GREATERTHANOREQUAL => $cellValue >= $formula1, default => false, }; } /** * Does this cell contain valid value, based on list? * * @param Cell $cell Cell to check the value */ private function isValueInList(Cell $cell): bool { $cellValueString = $cell->getValueString(); $dataValidation = $cell->getDataValidation(); $formula1 = $dataValidation->getFormula1(); if (!empty($formula1)) { // inline values list if ($formula1[0] === '"') { return in_array(strtolower($cellValueString), explode(',', strtolower(trim($formula1, '"'))), true); } $calculation = Calculation::getInstance($cell->getWorksheet()->getParent()); try { $result = $calculation->calculateFormula("=$formula1", $cell->getCoordinate(), $cell); $result = is_array($result) ? Functions::flattenArray($result) : [$result]; foreach ($result as $oneResult) { if (is_scalar($oneResult) && strcasecmp((string) $oneResult, $cellValueString) === 0) { return true; } } } catch (Exception) { // do nothing } return false; } return true; } } ================================================ FILE: src/PhpSpreadsheet/Cell/DefaultValueBinder.php ================================================ format('Y-m-d H:i:s'); } elseif ($value instanceof Stringable) { $value = (string) $value; } elseif ($value instanceof BaseDrawing) { $value->setCoordinates($cell->getCoordinate()); $value->setResizeProportional(false); $value->setInCell(true); $value->setWorksheet($cell->getWorksheet(), true); } else { throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value)); } // Set value explicit $cell->setValueExplicit($value, static::dataTypeForValue($value)); // Done! return true; } /** * DataType for value. */ public static function dataTypeForValue(mixed $value): string { // Match the value against a few data types if ($value === null) { return DataType::TYPE_NULL; } if (is_int($value) && abs($value) > self::FIFTEEN_NINES) { return DataType::TYPE_STRING; } if (is_float($value) || is_int($value)) { return DataType::TYPE_NUMERIC; } if (is_bool($value)) { return DataType::TYPE_BOOL; } if ($value === '') { return DataType::TYPE_STRING; } if ($value instanceof RichText) { return DataType::TYPE_INLINE; } if ($value instanceof BaseDrawing) { return DataType::TYPE_DRAWING_IN_CELL; } if ($value instanceof Stringable) { $value = (string) $value; } if (!is_string($value)) { $gettype = is_object($value) ? get_class($value) : gettype($value); throw new SpreadsheetException("unusable type $gettype"); } if (strlen($value) > 1 && $value[0] === '=') { $calculation = CalculationParserOnly::getParserInstance(); try { if (empty($calculation->parseFormula($value))) { return DataType::TYPE_STRING; } } catch (CalculationException $e) { $message = $e->getMessage(); if ( $message === 'Formula Error: An unexpected error occurred' || str_contains($message, 'has no operands') ) { return DataType::TYPE_STRING; } } return DataType::TYPE_FORMULA; } if (Preg::isMatch('/^[\+\-]?(\d+\.?\d*|\d*\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $value)) { $tValue = ltrim($value, '+-'); if (strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') { return DataType::TYPE_STRING; } if (!Preg::isMatch('/[eE.]/', $value)) { $aValue = abs((float) $value); if ($aValue > self::FIFTEEN_NINES) { return DataType::TYPE_STRING; } } if (!is_numeric($value) || !is_finite((float) $value)) { return DataType::TYPE_STRING; } return DataType::TYPE_NUMERIC; } $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$value])) { return DataType::TYPE_ERROR; } return DataType::TYPE_STRING; } protected bool $preserveCr = false; public function getPreserveCr(): bool { return $this->preserveCr; } public function setPreserveCr(bool $preserveCr): self { $this->preserveCr = $preserveCr; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Cell/Hyperlink.php ================================================ url = $url; $this->tooltip = $tooltip; } /** * Get URL. */ public function getUrl(): string { return $this->url; } /** * Set URL. * * @return $this */ public function setUrl(string $url): static { $this->url = $url; return $this; } /** * Get tooltip. */ public function getTooltip(): string { return $this->tooltip; } /** * Set tooltip. * * @return $this */ public function setTooltip(string $tooltip): static { $this->tooltip = $tooltip; return $this; } /** * Is this hyperlink internal? (to another worksheet or a cell in this worksheet). */ public function isInternal(): bool { return str_starts_with($this->url, 'sheet://') || str_starts_with($this->url, '#'); } public function getTypeHyperlink(): string { return $this->isInternal() ? '' : 'External'; } public function getDisplay(): string { return $this->display; } /** * This can be displayed in cell rather than actual cell contents. * It seems to be ignored by Excel. * It may be used by Google Sheets. */ public function setDisplay(string $display): self { $this->display = $display; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->url . ',' . $this->tooltip . ',' . $this->display . ',' . __CLASS__ ); } } ================================================ FILE: src/PhpSpreadsheet/Cell/IValueBinder.php ================================================ numberStoredAsText = $value; return $this; } public function getNumberStoredAsText(): bool { return $this->numberStoredAsText; } public function setFormula(bool $value): self { $this->formula = $value; return $this; } public function getFormula(): bool { return $this->formula; } public function setFormulaRange(bool $value): self { $this->formulaRange = $value; return $this; } public function getFormulaRange(): bool { return $this->formulaRange; } public function setTwoDigitTextYear(bool $value): self { $this->twoDigitTextYear = $value; return $this; } public function getTwoDigitTextYear(): bool { return $this->twoDigitTextYear; } public function setEvalError(bool $value): self { $this->evalError = $value; return $this; } public function getEvalError(): bool { return $this->evalError; } } ================================================ FILE: src/PhpSpreadsheet/Cell/RowRange.php ================================================ */ class RowRange implements AddressRange, Stringable { protected ?Worksheet $worksheet; protected int $from; protected int $to; public function __construct(int $from, ?int $to = null, ?Worksheet $worksheet = null) { $this->validateFromTo($from, $to ?? $from); $this->worksheet = $worksheet; } public function __destruct() { $this->worksheet = null; } /** @param array{int, int} $array */ public static function fromArray(array $array, ?Worksheet $worksheet = null): self { [$from, $to] = $array; return new self($from, $to, $worksheet); } private function validateFromTo(int $from, int $to): void { // Identify actual top and bottom values (in case we've been given bottom and top) $this->from = min($from, $to); $this->to = max($from, $to); } public function from(): int { return $this->from; } public function to(): int { return $this->to; } public function rowCount(): int { return $this->to - $this->from + 1; } public function shiftRight(int $offset = 1): self { $newFrom = $this->from + $offset; $newFrom = ($newFrom < 1) ? 1 : $newFrom; $newTo = $this->to + $offset; $newTo = ($newTo < 1) ? 1 : $newTo; return new self($newFrom, $newTo, $this->worksheet); } public function shiftLeft(int $offset = 1): self { return $this->shiftRight(0 - $offset); } public function toCellRange(): CellRange { return new CellRange( CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString('A'), $this->from, $this->worksheet), CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString(AddressRange::MAX_COLUMN), $this->to) ); } public function __toString(): string { if ($this->worksheet !== null) { $title = str_replace("'", "''", $this->worksheet->getTitle()); return "'{$title}'!{$this->from}:{$this->to}"; } return "{$this->from}:{$this->to}"; } } ================================================ FILE: src/PhpSpreadsheet/Cell/StringValueBinder.php ================================================ setIgnoredErrors = $setIgnoredErrors; return $this; } public function setNullConversion(bool $suppressConversion = false): self { $this->convertNull = $suppressConversion; return $this; } public function setBooleanConversion(bool $suppressConversion = false): self { $this->convertBoolean = $suppressConversion; return $this; } public function getBooleanConversion(): bool { return $this->convertBoolean; } public function setNumericConversion(bool $suppressConversion = false): self { $this->convertNumeric = $suppressConversion; return $this; } public function setFormulaConversion(bool $suppressConversion = false): self { $this->convertFormula = $suppressConversion; return $this; } public function setConversionForAllValueTypes(bool $suppressConversion = false): self { $this->convertNull = $suppressConversion; $this->convertBoolean = $suppressConversion; $this->convertNumeric = $suppressConversion; $this->convertFormula = $suppressConversion; return $this; } /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell */ public function bindValue(Cell $cell, mixed $value): bool { if (is_object($value)) { return $this->bindObjectValue($cell, $value); } if ($value !== null && !is_scalar($value)) { throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value)); } // sanitize UTF-8 strings if (is_string($value)) { $value = StringHelper::sanitizeUTF8($value); } $ignoredErrors = false; if ($value === null && $this->convertNull === false) { $cell->setValueExplicit($value, DataType::TYPE_NULL); } elseif (is_bool($value) && $this->convertBoolean === false) { $cell->setValueExplicit($value, DataType::TYPE_BOOL); } elseif ((is_int($value) || is_float($value)) && $this->convertNumeric === false) { $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=' && $this->convertFormula === false && parent::dataTypeForValue($value) === DataType::TYPE_FORMULA) { $cell->setValueExplicit($value, DataType::TYPE_FORMULA); } else { $ignoredErrors = is_numeric($value); $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); } if ($this->setIgnoredErrors) { $cell->getIgnoredErrors()->setNumberStoredAsText($ignoredErrors); } return true; } protected function bindObjectValue(Cell $cell, object $value): bool { // Handle any objects that might be injected $ignoredErrors = false; if ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d H:i:s'); $cell->setValueExplicit($value, DataType::TYPE_STRING); } elseif ($value instanceof RichText) { $cell->setValueExplicit($value, DataType::TYPE_INLINE); $ignoredErrors = is_numeric($value->getPlainText()); } elseif ($value instanceof Stringable) { $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); $ignoredErrors = is_numeric((string) $value); } else { throw new SpreadsheetException('Unable to bind unstringable object of type ' . get_class($value)); } if ($this->setIgnoredErrors) { $cell->getIgnoredErrors()->setNumberStoredAsText($ignoredErrors); } return true; } } ================================================ FILE: src/PhpSpreadsheet/CellReferenceHelper.php ================================================ beforeColumnAbsolute = $beforeCellAddress[0] === '$'; $this->beforeRowAbsolute = strpos($beforeCellAddress, '$', 1) !== false; $this->beforeCellAddress = str_replace('$', '', $beforeCellAddress); $this->numberOfColumns = $numberOfColumns; $this->numberOfRows = $numberOfRows; // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress); $this->beforeColumnString = $beforeColumn; $this->beforeColumn = (int) Coordinate::columnIndexFromString($beforeColumn); $this->beforeRow = (int) $beforeRow; } public function beforeCellAddress(): string { return $this->beforeCellAddress; } public function refreshRequired(string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): bool { return $this->beforeCellAddress !== $beforeCellAddress || $this->numberOfColumns !== $numberOfColumns || $this->numberOfRows !== $numberOfRows; } public function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false, ?bool $topLeft = null): string { if (Coordinate::coordinateIsRange($cellReference)) { throw new Exception('Only single cell references may be passed to this method.'); } // Get coordinate of $cellReference [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference); $newColumnIndex = Coordinate::columnIndexFromString(str_replace('$', '', $newColumn)); $newRowIndex = (int) str_replace('$', '', $newRow); $absoluteColumn = $newColumn[0] === '$' ? '$' : ''; $absoluteRow = $newRow[0] === '$' ? '$' : ''; // Verify which parts should be updated if ($onlyAbsoluteReferences === true) { $updateColumn = (($absoluteColumn === '$') && $newColumnIndex >= $this->beforeColumn); $updateRow = (($absoluteRow === '$') && $newRowIndex >= $this->beforeRow); } elseif ($includeAbsoluteReferences === false) { $updateColumn = (($absoluteColumn !== '$') && $newColumnIndex >= $this->beforeColumn); $updateRow = (($absoluteRow !== '$') && $newRowIndex >= $this->beforeRow); } else { $newColumnIndex = $this->computeNewColumnIndex($newColumnIndex, $topLeft); $newColumn = $absoluteColumn . Coordinate::stringFromColumnIndex($newColumnIndex); $updateColumn = false; $newRowIndex = $this->computeNewRowIndex($newRowIndex, $topLeft); $newRow = $absoluteRow . $newRowIndex; $updateRow = false; } // Create new column reference if ($updateColumn) { $newColumn = $this->updateColumnReference($newColumnIndex, $absoluteColumn); } // Create new row reference if ($updateRow) { $newRow = $this->updateRowReference($newRowIndex, $absoluteRow); } // Return new reference return "{$newColumn}{$newRow}"; } public function computeNewColumnIndex(int $newColumnIndex, ?bool $topLeft): int { // A special case is removing the left/top or bottom/right edge of a range // $topLeft is null if we aren't adjusting a range at all. if ( $topLeft !== null && $this->numberOfColumns < 0 && $newColumnIndex >= $this->beforeColumn + $this->numberOfColumns && $newColumnIndex <= $this->beforeColumn - 1 ) { if ($topLeft) { $newColumnIndex = $this->beforeColumn + $this->numberOfColumns; } else { $newColumnIndex = $this->beforeColumn + $this->numberOfColumns - 1; } } elseif ($newColumnIndex >= $this->beforeColumn) { // Create new column reference $newColumnIndex += $this->numberOfColumns; } return $newColumnIndex; } public function computeNewRowIndex(int $newRowIndex, ?bool $topLeft): int { // A special case is removing the left/top or bottom/right edge of a range // $topLeft is null if we aren't adjusting a range at all. if ( $topLeft !== null && $this->numberOfRows < 0 && $newRowIndex >= $this->beforeRow + $this->numberOfRows && $newRowIndex <= $this->beforeRow - 1 ) { if ($topLeft) { $newRowIndex = $this->beforeRow + $this->numberOfRows; } else { $newRowIndex = $this->beforeRow + $this->numberOfRows - 1; } } elseif ($newRowIndex >= $this->beforeRow) { $newRowIndex = $newRowIndex + $this->numberOfRows; } return $newRowIndex; } public function cellAddressInDeleteRange(string $cellAddress): bool { [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); // Is cell within the range of rows/columns if we're deleting if ( $this->numberOfRows < 0 && ($cellRow >= ($this->beforeRow + $this->numberOfRows)) && ($cellRow < $this->beforeRow) ) { return true; } elseif ( $this->numberOfColumns < 0 && ($cellColumnIndex >= ($this->beforeColumn + $this->numberOfColumns)) && ($cellColumnIndex < $this->beforeColumn) ) { return true; } return false; } protected function updateColumnReference(int $newColumnIndex, string $absoluteColumn): string { $newColumn = Coordinate::stringFromColumnIndex(min($newColumnIndex + $this->numberOfColumns, AddressRange::MAX_COLUMN_INT)); return "{$absoluteColumn}{$newColumn}"; } protected function updateRowReference(int $newRowIndex, string $absoluteRow): string { $newRow = $newRowIndex + $this->numberOfRows; $newRow = ($newRow > AddressRange::MAX_ROW) ? AddressRange::MAX_ROW : $newRow; return "{$absoluteRow}{$newRow}"; } } ================================================ FILE: src/PhpSpreadsheet/Chart/Axis.php ================================================ fillColor = new ChartColor(); } /** * Chart Major Gridlines as. */ private ?GridLines $majorGridlines = null; /** * Chart Minor Gridlines as. */ private ?GridLines $minorGridlines = null; /** * Axis Number. * * @var array{format: string, source_linked: int, numeric: ?bool} */ private array $axisNumber = [ 'format' => self::FORMAT_CODE_GENERAL, 'source_linked' => 1, 'numeric' => null, ]; private string $axisType = ''; private ?AxisText $axisText = null; private ?Title $dispUnitsTitle = null; /** * Axis Options. * * @var array */ private array $axisOptions = [ 'minimum' => null, 'maximum' => null, 'major_unit' => null, 'minor_unit' => null, 'orientation' => self::ORIENTATION_NORMAL, 'minor_tick_mark' => self::TICK_MARK_NONE, 'major_tick_mark' => self::TICK_MARK_NONE, 'axis_labels' => self::AXIS_LABELS_NEXT_TO, 'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO, 'horizontal_crosses_value' => null, 'textRotation' => null, 'hidden' => null, 'majorTimeUnit' => self::TIME_UNIT_YEARS, 'minorTimeUnit' => self::TIME_UNIT_MONTHS, 'baseTimeUnit' => self::TIME_UNIT_DAYS, 'logBase' => null, 'dispUnitsBuiltIn' => null, ]; public const DISP_UNITS_HUNDREDS = 'hundreds'; public const DISP_UNITS_THOUSANDS = 'thousands'; public const DISP_UNITS_TEN_THOUSANDS = 'tenThousands'; public const DISP_UNITS_HUNDRED_THOUSANDS = 'hundredThousands'; public const DISP_UNITS_MILLIONS = 'millions'; public const DISP_UNITS_TEN_MILLIONS = 'tenMillions'; public const DISP_UNITS_HUNDRED_MILLIONS = 'hundredMillions'; public const DISP_UNITS_BILLIONS = 'billions'; public const DISP_UNITS_TRILLIONS = 'trillions'; public const TRILLION_INDEX = (PHP_INT_SIZE > 4) ? 1000000000000 : '1000000000000'; public const DISP_UNITS_BUILTIN_INT = [ 100 => self::DISP_UNITS_HUNDREDS, 1000 => self::DISP_UNITS_THOUSANDS, 10000 => self::DISP_UNITS_TEN_THOUSANDS, 100000 => self::DISP_UNITS_HUNDRED_THOUSANDS, 1000000 => self::DISP_UNITS_MILLIONS, 10000000 => self::DISP_UNITS_TEN_MILLIONS, 100000000 => self::DISP_UNITS_HUNDRED_MILLIONS, 1000000000 => self::DISP_UNITS_BILLIONS, self::TRILLION_INDEX => self::DISP_UNITS_TRILLIONS, // overflow for 32-bit ]; /** * Fill Properties. */ private ChartColor $fillColor; private const NUMERIC_FORMAT = [ Properties::FORMAT_CODE_NUMBER, Properties::FORMAT_CODE_DATE, Properties::FORMAT_CODE_DATE_ISO8601, ]; private bool $noFill = false; /** * Get Series Data Type. */ public function setAxisNumberProperties(string $format_code, ?bool $numeric = null, int $sourceLinked = 0): void { $format = $format_code; $this->axisNumber['format'] = $format; $this->axisNumber['source_linked'] = $sourceLinked; if (is_bool($numeric)) { $this->axisNumber['numeric'] = $numeric; } elseif (in_array($format, self::NUMERIC_FORMAT, true)) { $this->axisNumber['numeric'] = true; } } /** * Get Axis Number Format Data Type. */ public function getAxisNumberFormat(): string { return $this->axisNumber['format']; } /** * Get Axis Number Source Linked. */ public function getAxisNumberSourceLinked(): string { return (string) $this->axisNumber['source_linked']; } public function getAxisIsNumericFormat(): bool { return $this->axisType === self::AXIS_TYPE_DATE || (bool) $this->axisNumber['numeric']; } public function setAxisOption(string $key, null|float|int|string $value): void { if ($value !== null && $value !== '') { $this->axisOptions[$key] = (string) $value; } } /** * Set Axis Options Properties. */ public function setAxisOptionsProperties( string $axisLabels, ?string $horizontalCrossesValue = null, ?string $horizontalCrosses = null, ?string $axisOrientation = null, ?string $majorTmt = null, ?string $minorTmt = null, null|float|int|string $minimum = null, null|float|int|string $maximum = null, null|float|int|string $majorUnit = null, null|float|int|string $minorUnit = null, null|float|int|string $textRotation = null, ?string $hidden = null, ?string $baseTimeUnit = null, ?string $majorTimeUnit = null, ?string $minorTimeUnit = null, null|float|int|string $logBase = null, ?string $dispUnitsBuiltIn = null ): void { $this->axisOptions['axis_labels'] = $axisLabels; $this->setAxisOption('horizontal_crosses_value', $horizontalCrossesValue); $this->setAxisOption('horizontal_crosses', $horizontalCrosses); $this->setAxisOption('orientation', $axisOrientation); $this->setAxisOption('major_tick_mark', $majorTmt); $this->setAxisOption('minor_tick_mark', $minorTmt); $this->setAxisOption('minimum', $minimum); $this->setAxisOption('maximum', $maximum); $this->setAxisOption('major_unit', $majorUnit); $this->setAxisOption('minor_unit', $minorUnit); $this->setAxisOption('textRotation', $textRotation); $this->setAxisOption('hidden', $hidden); $this->setAxisOption('baseTimeUnit', $baseTimeUnit); $this->setAxisOption('majorTimeUnit', $majorTimeUnit); $this->setAxisOption('minorTimeUnit', $minorTimeUnit); $this->setAxisOption('logBase', $logBase); $this->setAxisOption('dispUnitsBuiltIn', $dispUnitsBuiltIn); } /** * Get Axis Options Property. */ public function getAxisOptionsProperty(string $property): ?string { if ($property === 'textRotation') { if ($this->axisText !== null) { if ($this->axisText->getRotation() !== null) { return (string) $this->axisText->getRotation(); } } } return $this->axisOptions[$property]; } /** * Set Axis Orientation Property. */ public function setAxisOrientation(string $orientation): void { $this->axisOptions['orientation'] = (string) $orientation; } public function getAxisType(): string { return $this->axisType; } public function setAxisType(string $type): self { if ($type === self::AXIS_TYPE_CATEGORY || $type === self::AXIS_TYPE_VALUE || $type === self::AXIS_TYPE_DATE) { $this->axisType = $type; } else { $this->axisType = ''; } return $this; } /** * Set Fill Property. */ public function setFillParameters(?string $color, ?int $alpha = null, ?string $AlphaType = ChartColor::EXCEL_COLOR_TYPE_RGB): void { $this->fillColor->setColorProperties($color, $alpha, $AlphaType); } /** * Get Fill Property. */ public function getFillProperty(string $property): string { return (string) $this->fillColor->getColorProperty($property); } public function getFillColorObject(): ChartColor { return $this->fillColor; } private string $crossBetween = ''; // 'between' or 'midCat' might be better public function setCrossBetween(string $crossBetween): self { $this->crossBetween = $crossBetween; return $this; } public function getCrossBetween(): string { return $this->crossBetween; } public function getMajorGridlines(): ?GridLines { return $this->majorGridlines; } public function getMinorGridlines(): ?GridLines { return $this->minorGridlines; } public function setMajorGridlines(?GridLines $gridlines): self { $this->majorGridlines = $gridlines; return $this; } public function setMinorGridlines(?GridLines $gridlines): self { $this->minorGridlines = $gridlines; return $this; } public function getAxisText(): ?AxisText { return $this->axisText; } public function setAxisText(?AxisText $axisText): self { $this->axisText = $axisText; return $this; } public function setNoFill(bool $noFill): self { $this->noFill = $noFill; return $this; } public function getNoFill(): bool { return $this->noFill; } public function setDispUnitsTitle(?Title $dispUnitsTitle): self { $this->dispUnitsTitle = $dispUnitsTitle; return $this; } public function getDispUnitsTitle(): ?Title { return $this->dispUnitsTitle; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { parent::__clone(); $this->majorGridlines = ($this->majorGridlines === null) ? null : clone $this->majorGridlines; $this->majorGridlines = ($this->minorGridlines === null) ? null : clone $this->minorGridlines; $this->axisText = ($this->axisText === null) ? null : clone $this->axisText; $this->dispUnitsTitle = ($this->dispUnitsTitle === null) ? null : clone $this->dispUnitsTitle; $this->fillColor = clone $this->fillColor; } } ================================================ FILE: src/PhpSpreadsheet/Chart/AxisText.php ================================================ font = new Font(); $this->font->setSize(null, true); } public function setRotation(?int $rotation): self { $this->rotation = $rotation; return $this; } public function getRotation(): ?int { return $this->rotation; } public function getFillColorObject(): ChartColor { $fillColor = $this->font->getChartColor(); if ($fillColor === null) { $fillColor = new ChartColor(); $this->font->setChartColorFromObject($fillColor); } return $fillColor; } public function getFont(): Font { return $this->font; } public function setFont(Font $font): self { $this->font = $font; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { parent::__clone(); $this->font = clone $this->font; } } ================================================ FILE: src/PhpSpreadsheet/Chart/Chart.php ================================================ name = $name; $this->title = $title; $this->legend = $legend; $this->xAxisLabel = $xAxisLabel; $this->yAxisLabel = $yAxisLabel; $this->plotArea = $plotArea; $this->plotVisibleOnly = $plotVisibleOnly; $this->setDisplayBlanksAs($displayBlanksAs); $this->xAxis = $xAxis ?? new Axis(); $this->yAxis = $yAxis ?? new Axis(); if ($majorGridlines !== null) { $this->yAxis->setMajorGridlines($majorGridlines); } if ($minorGridlines !== null) { $this->yAxis->setMinorGridlines($minorGridlines); } $this->fillColor = new ChartColor(); $this->borderLines = new GridLines(); } public function __destruct() { $this->worksheet = null; } /** * Get Name. */ public function getName(): string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } /** * Get Worksheet. */ public function getWorksheet(): ?Worksheet { return $this->worksheet; } /** * Set Worksheet. * * @return $this */ public function setWorksheet(?Worksheet $worksheet = null): static { $this->worksheet = $worksheet; return $this; } public function getTitle(): ?Title { return $this->title; } /** * Set Title. * * @return $this */ public function setTitle(Title $title): static { $this->title = $title; return $this; } public function getLegend(): ?Legend { return $this->legend; } /** * Set Legend. * * @return $this */ public function setLegend(Legend $legend): static { $this->legend = $legend; return $this; } public function getXAxisLabel(): ?Title { return $this->xAxisLabel; } /** * Set X-Axis Label. * * @return $this */ public function setXAxisLabel(Title $label): static { $this->xAxisLabel = $label; return $this; } public function getYAxisLabel(): ?Title { return $this->yAxisLabel; } /** * Set Y-Axis Label. * * @return $this */ public function setYAxisLabel(Title $label): static { $this->yAxisLabel = $label; return $this; } public function getPlotArea(): ?PlotArea { return $this->plotArea; } public function getPlotAreaOrThrow(): PlotArea { $plotArea = $this->getPlotArea(); if ($plotArea !== null) { return $plotArea; } throw new Exception('Chart has no PlotArea'); } /** * Set Plot Area. */ public function setPlotArea(PlotArea $plotArea): self { $this->plotArea = $plotArea; return $this; } /** * Get Plot Visible Only. */ public function getPlotVisibleOnly(): bool { return $this->plotVisibleOnly; } /** * Set Plot Visible Only. * * @return $this */ public function setPlotVisibleOnly(bool $plotVisibleOnly): static { $this->plotVisibleOnly = $plotVisibleOnly; return $this; } /** * Get Display Blanks as. */ public function getDisplayBlanksAs(): string { return $this->displayBlanksAs; } /** * Set Display Blanks as. * * @return $this */ public function setDisplayBlanksAs(string $displayBlanksAs): static { $displayBlanksAs = strtolower($displayBlanksAs); $this->displayBlanksAs = in_array($displayBlanksAs, DataSeries::VALID_EMPTY_AS, true) ? $displayBlanksAs : DataSeries::DEFAULT_EMPTY_AS; return $this; } public function getChartAxisY(): Axis { return $this->yAxis; } /** * Set yAxis. */ public function setChartAxisY(?Axis $axis): self { $this->yAxis = $axis ?? new Axis(); return $this; } public function getChartAxisX(): Axis { return $this->xAxis; } /** * Set xAxis. */ public function setChartAxisX(?Axis $axis): self { $this->xAxis = $axis ?? new Axis(); return $this; } /** * Set the Top Left position for the chart. * * @return $this */ public function setTopLeftPosition(string $cellAddress, ?int $xOffset = null, ?int $yOffset = null): static { $this->topLeftCellRef = $cellAddress; if ($xOffset !== null) { $this->setTopLeftXOffset($xOffset); } if ($yOffset !== null) { $this->setTopLeftYOffset($yOffset); } return $this; } /** * Get the top left position of the chart. * * Returns ['cell' => string cell address, 'xOffset' => int, 'yOffset' => int]. * * @return array{cell: string, xOffset: int, yOffset: int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell */ public function getTopLeftPosition(): array { return [ 'cell' => $this->topLeftCellRef, 'xOffset' => $this->topLeftXOffset, 'yOffset' => $this->topLeftYOffset, ]; } /** * Get the cell address where the top left of the chart is fixed. */ public function getTopLeftCell(): string { return $this->topLeftCellRef; } /** * Set the Top Left cell position for the chart. * * @return $this */ public function setTopLeftCell(string $cellAddress): static { $this->topLeftCellRef = $cellAddress; return $this; } /** * Set the offset position within the Top Left cell for the chart. * * @return $this */ public function setTopLeftOffset(?int $xOffset, ?int $yOffset): static { if ($xOffset !== null) { $this->setTopLeftXOffset($xOffset); } if ($yOffset !== null) { $this->setTopLeftYOffset($yOffset); } return $this; } /** * Get the offset position within the Top Left cell for the chart. * * @return int[] */ public function getTopLeftOffset(): array { return [ 'X' => $this->topLeftXOffset, 'Y' => $this->topLeftYOffset, ]; } /** * @return $this */ public function setTopLeftXOffset(int $xOffset): static { $this->topLeftXOffset = $xOffset; return $this; } public function getTopLeftXOffset(): int { return $this->topLeftXOffset; } /** * @return $this */ public function setTopLeftYOffset(int $yOffset): static { $this->topLeftYOffset = $yOffset; return $this; } public function getTopLeftYOffset(): int { return $this->topLeftYOffset; } /** * Set the Bottom Right position of the chart. * * @return $this */ public function setBottomRightPosition(string $cellAddress = '', ?int $xOffset = null, ?int $yOffset = null): static { $this->bottomRightCellRef = $cellAddress; if ($xOffset !== null) { $this->setBottomRightXOffset($xOffset); } if ($yOffset !== null) { $this->setBottomRightYOffset($yOffset); } return $this; } /** * Get the bottom right position of the chart. * * @return array{cell: string, xOffset: int, yOffset:int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell */ public function getBottomRightPosition(): array { return [ 'cell' => $this->bottomRightCellRef, 'xOffset' => $this->bottomRightXOffset, 'yOffset' => $this->bottomRightYOffset, ]; } /** * Set the Bottom Right cell for the chart. * * @return $this */ public function setBottomRightCell(string $cellAddress = ''): static { $this->bottomRightCellRef = $cellAddress; return $this; } /** * Get the cell address where the bottom right of the chart is fixed. */ public function getBottomRightCell(): string { return $this->bottomRightCellRef; } /** * Set the offset position within the Bottom Right cell for the chart. * * @return $this */ public function setBottomRightOffset(?int $xOffset, ?int $yOffset): static { if ($xOffset !== null) { $this->setBottomRightXOffset($xOffset); } if ($yOffset !== null) { $this->setBottomRightYOffset($yOffset); } return $this; } /** * Get the offset position within the Bottom Right cell for the chart. * * @return int[] */ public function getBottomRightOffset(): array { return [ 'X' => $this->bottomRightXOffset, 'Y' => $this->bottomRightYOffset, ]; } /** * @return $this */ public function setBottomRightXOffset(int $xOffset): static { $this->bottomRightXOffset = $xOffset; return $this; } public function getBottomRightXOffset(): int { return $this->bottomRightXOffset; } /** * @return $this */ public function setBottomRightYOffset(int $yOffset): static { $this->bottomRightYOffset = $yOffset; return $this; } public function getBottomRightYOffset(): int { return $this->bottomRightYOffset; } public function refresh(): void { if ($this->worksheet !== null && $this->plotArea !== null) { $this->plotArea->refresh($this->worksheet); } } /** * Render the chart to given file (or stream). * * @param ?string $outputDestination Name of the file render to * * @return bool true on success */ public function render(?string $outputDestination = null): bool { if ($outputDestination == 'php://output') { $outputDestination = null; } $libraryName = Settings::getChartRenderer(); if ($libraryName === null) { return false; } // Ensure that data series values are up-to-date before we render $this->refresh(); $renderer = new $libraryName($this); return $renderer->render($outputDestination); } public function getRotX(): ?int { return $this->rotX; } public function setRotX(?int $rotX): self { $this->rotX = $rotX; return $this; } public function getRotY(): ?int { return $this->rotY; } public function setRotY(?int $rotY): self { $this->rotY = $rotY; return $this; } public function getRAngAx(): ?int { return $this->rAngAx; } public function setRAngAx(?int $rAngAx): self { $this->rAngAx = $rAngAx; return $this; } public function getPerspective(): ?int { return $this->perspective; } public function setPerspective(?int $perspective): self { $this->perspective = $perspective; return $this; } public function getOneCellAnchor(): bool { return $this->oneCellAnchor; } public function setOneCellAnchor(bool $oneCellAnchor): self { $this->oneCellAnchor = $oneCellAnchor; return $this; } public function getAutoTitleDeleted(): bool { return $this->autoTitleDeleted; } public function setAutoTitleDeleted(bool $autoTitleDeleted): self { $this->autoTitleDeleted = $autoTitleDeleted; return $this; } public function getNoFill(): bool { return $this->noFill; } public function setNoFill(bool $noFill): self { $this->noFill = $noFill; return $this; } public function getNoBorder(): bool { return $this->noBorder; } public function setNoBorder(bool $noBorder): self { $this->noBorder = $noBorder; return $this; } public function getRoundedCorners(): bool { return $this->roundedCorners; } public function setRoundedCorners(?bool $roundedCorners): self { if ($roundedCorners !== null) { $this->roundedCorners = $roundedCorners; } return $this; } public function getBorderLines(): GridLines { return $this->borderLines; } public function setBorderLines(GridLines $borderLines): self { $this->borderLines = $borderLines; return $this; } public function getFillColor(): ChartColor { return $this->fillColor; } public function setRenderedWidth(?float $width): self { $this->renderedWidth = $width; return $this; } public function getRenderedWidth(): ?float { return $this->renderedWidth; } public function setRenderedHeight(?float $height): self { $this->renderedHeight = $height; return $this; } public function getRenderedHeight(): ?float { return $this->renderedHeight; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->worksheet = null; $this->title = ($this->title === null) ? null : clone $this->title; $this->legend = ($this->legend === null) ? null : clone $this->legend; $this->xAxisLabel = ($this->xAxisLabel === null) ? null : clone $this->xAxisLabel; $this->yAxisLabel = ($this->yAxisLabel === null) ? null : clone $this->yAxisLabel; $this->plotArea = ($this->plotArea === null) ? null : clone $this->plotArea; $this->xAxis = clone $this->xAxis; $this->yAxis = clone $this->yAxis; $this->borderLines = clone $this->borderLines; $this->fillColor = clone $this->fillColor; } } ================================================ FILE: src/PhpSpreadsheet/Chart/ChartColor.php ================================================ setColorPropertiesArray($value); } else { $this->setColorProperties($value, $alpha, $type, $brightness); } } public function getValue(): string { return $this->value; } public function setValue(string $value): self { $this->value = $value; return $this; } public function getType(): string { return $this->type; } public function setType(string $type): self { $this->type = $type; return $this; } public function getAlpha(): ?int { return $this->alpha; } public function setAlpha(?int $alpha): self { $this->alpha = $alpha; return $this; } public function getBrightness(): ?int { return $this->brightness; } public function setBrightness(?int $brightness): self { $this->brightness = $brightness; return $this; } public function setColorProperties(?string $color, null|float|int|string $alpha = null, ?string $type = null, null|float|int|string $brightness = null): self { if (empty($type) && !empty($color)) { if (str_starts_with($color, '*')) { $type = 'schemeClr'; $color = substr($color, 1); } elseif (str_starts_with($color, '/')) { $type = 'prstClr'; $color = substr($color, 1); } elseif (preg_match('/^[0-9A-Fa-f]{6}$/', $color) === 1) { $type = 'srgbClr'; } } if ($color !== null) { $this->setValue("$color"); } if ($type !== null) { $this->setType($type); } if ($alpha === null) { $this->setAlpha(null); } elseif (is_numeric($alpha)) { $this->setAlpha((int) $alpha); } if ($brightness === null) { $this->setBrightness(null); } elseif (is_numeric($brightness)) { $this->setBrightness((int) $brightness); } return $this; } /** @param array{value: ?string, alpha: null|int|string, brightness?: null|int|string, type: ?string} $color */ public function setColorPropertiesArray(array $color): self { return $this->setColorProperties( $color['value'] ?? '', $color['alpha'] ?? null, $color['type'] ?? null, $color['brightness'] ?? null ); } public function isUsable(): bool { return $this->type !== '' && $this->value !== ''; } /** * Get Color Property. */ public function getColorProperty(string $propertyName): null|int|string { $retVal = null; if ($propertyName === 'value') { $retVal = $this->value; } elseif ($propertyName === 'type') { $retVal = $this->type; } elseif ($propertyName === 'alpha') { $retVal = $this->alpha; } elseif ($propertyName === 'brightness') { $retVal = $this->brightness; } return $retVal; } public static function alphaToXml(int $alpha): string { return (string) (100 - $alpha) . '000'; } public static function alphaFromXml(float|int|string $alpha): int { return 100 - ((int) $alpha / 1000); } } ================================================ FILE: src/PhpSpreadsheet/Chart/DataSeries.php ================================================ plotType = $plotType; $this->plotGrouping = $plotGrouping; $this->plotOrder = $plotOrder; $keys = array_keys($plotValues); $this->plotValues = $plotValues; if (!isset($plotLabel[$keys[0]])) { $plotLabel[$keys[0]] = new DataSeriesValues(); } $this->plotLabel = $plotLabel; if (!isset($plotCategory[$keys[0]])) { $plotCategory[$keys[0]] = new DataSeriesValues(); } $this->plotCategory = $plotCategory; $this->smoothLine = (bool) $smoothLine; $this->plotStyle = $plotStyle; if ($plotDirection === null) { $plotDirection = self::DIRECTION_COL; } $this->plotDirection = $plotDirection; } /** * Get Plot Type. */ public function getPlotType(): ?string { return $this->plotType; } /** * Set Plot Type. * * @return $this */ public function setPlotType(string $plotType): static { $this->plotType = $plotType; return $this; } /** * Get Plot Grouping Type. */ public function getPlotGrouping(): ?string { return $this->plotGrouping; } /** * Set Plot Grouping Type. * * @return $this */ public function setPlotGrouping(string $groupingType): static { $this->plotGrouping = $groupingType; return $this; } /** * Get Plot Direction. */ public function getPlotDirection(): string { return $this->plotDirection; } /** * Set Plot Direction. * * @return $this */ public function setPlotDirection(string $plotDirection): static { $this->plotDirection = $plotDirection; return $this; } /** * Get Plot Order. * * @return int[] */ public function getPlotOrder(): array { return $this->plotOrder; } /** * Get Plot Labels. * * @return DataSeriesValues[] */ public function getPlotLabels(): array { return $this->plotLabel; } /** * Get Plot Label by Index. * * @return DataSeriesValues|false */ public function getPlotLabelByIndex(int $index): bool|DataSeriesValues { $keys = array_keys($this->plotLabel); if (in_array($index, $keys)) { return $this->plotLabel[$index]; } return false; } /** * Get Plot Categories. * * @return DataSeriesValues[] */ public function getPlotCategories(): array { return $this->plotCategory; } /** * Get Plot Category by Index. * * @return DataSeriesValues|false */ public function getPlotCategoryByIndex(int $index): bool|DataSeriesValues { $keys = array_keys($this->plotCategory); if (in_array($index, $keys)) { return $this->plotCategory[$index]; } elseif (isset($keys[$index])) { return $this->plotCategory[$keys[$index]]; } return false; } /** * Get Plot Style. */ public function getPlotStyle(): ?string { return $this->plotStyle; } /** * Set Plot Style. * * @return $this */ public function setPlotStyle(?string $plotStyle): static { $this->plotStyle = $plotStyle; return $this; } /** * Get Plot Values. * * @return DataSeriesValues[] */ public function getPlotValues(): array { return $this->plotValues; } /** * Get Plot Values by Index. * * @return DataSeriesValues|false */ public function getPlotValuesByIndex(int $index): bool|DataSeriesValues { $keys = array_keys($this->plotValues); if (in_array($index, $keys)) { return $this->plotValues[$index]; } return false; } /** * Get Plot Bubble Sizes. * * @return DataSeriesValues[] */ public function getPlotBubbleSizes(): array { return $this->plotBubbleSizes; } /** * Set Plot Bubble Sizes. * * @param DataSeriesValues[] $plotBubbleSizes */ public function setPlotBubbleSizes(array $plotBubbleSizes): self { $this->plotBubbleSizes = $plotBubbleSizes; return $this; } /** * Get Number of Plot Series. */ public function getPlotSeriesCount(): int { return count($this->plotValues); } /** * Get Smooth Line. */ public function getSmoothLine(): bool { return $this->smoothLine; } /** * Set Smooth Line. * * @return $this */ public function setSmoothLine(bool $smoothLine): static { $this->smoothLine = $smoothLine; return $this; } public function refresh(Worksheet $worksheet): void { foreach ($this->plotValues as $plotValues) { $plotValues->refresh($worksheet, true); } foreach ($this->plotLabel as $plotValues) { $plotValues->refresh($worksheet, true); } foreach ($this->plotCategory as $plotValues) { $plotValues->refresh($worksheet, false); } } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $plotLabels = $this->plotLabel; $this->plotLabel = []; foreach ($plotLabels as $plotLabel) { $this->plotLabel[] = $plotLabel; } $plotCategories = $this->plotCategory; $this->plotCategory = []; foreach ($plotCategories as $plotCategory) { $this->plotCategory[] = clone $plotCategory; } $plotValues = $this->plotValues; $this->plotValues = []; foreach ($plotValues as $plotValue) { $this->plotValues[] = clone $plotValue; } $plotBubbleSizes = $this->plotBubbleSizes; $this->plotBubbleSizes = []; foreach ($plotBubbleSizes as $plotBubbleSize) { $this->plotBubbleSizes[] = clone $plotBubbleSize; } } } ================================================ FILE: src/PhpSpreadsheet/Chart/DataSeriesValues.php ================================================ markerFillColor = new ChartColor(); $this->markerBorderColor = new ChartColor(); $this->setDataType($dataType); $this->dataSource = $dataSource; $this->formatCode = $formatCode; $this->pointCount = $pointCount; $this->dataValues = $dataValues; $this->pointMarker = $marker; if ($fillColor !== null) { $this->setFillColor($fillColor); } if (is_numeric($pointSize)) { $this->pointSize = (int) $pointSize; } } /** * Get Series Data Type. */ public function getDataType(): string { return $this->dataType; } /** * Set Series Data Type. * * @param string $dataType Datatype of this data series * Typical values are: * DataSeriesValues::DATASERIES_TYPE_STRING * Normally used for axis point values * DataSeriesValues::DATASERIES_TYPE_NUMBER * Normally used for chart data values * * @return $this */ public function setDataType(string $dataType): static { if (!in_array($dataType, self::DATA_TYPE_VALUES)) { throw new Exception('Invalid datatype for chart data series values'); } $this->dataType = $dataType; return $this; } /** * Get Series Data Source (formula). */ public function getDataSource(): ?string { return $this->dataSource; } /** * Set Series Data Source (formula). * * @return $this */ public function setDataSource(?string $dataSource): static { $this->dataSource = $dataSource; return $this; } /** * Get Point Marker. */ public function getPointMarker(): ?string { return $this->pointMarker; } /** * Set Point Marker. * * @return $this */ public function setPointMarker(string $marker): static { $this->pointMarker = $marker; return $this; } public function getMarkerFillColor(): ChartColor { return $this->markerFillColor; } public function getMarkerBorderColor(): ChartColor { return $this->markerBorderColor; } /** * Get Point Size. */ public function getPointSize(): int { return $this->pointSize; } /** * Set Point Size. * * @return $this */ public function setPointSize(int $size = 3): static { $this->pointSize = $size; return $this; } /** * Get Series Format Code. */ public function getFormatCode(): ?string { return $this->formatCode; } /** * Set Series Format Code. * * @return $this */ public function setFormatCode(string $formatCode): static { $this->formatCode = $formatCode; return $this; } /** * Get Series Point Count. */ public function getPointCount(): int { return $this->pointCount; } /** * Get fill color object. * * @return null|ChartColor|ChartColor[] */ public function getFillColorObject() { return $this->fillColor; } private function stringToChartColor(string $fillString): ChartColor { $value = $type = ''; if (str_starts_with($fillString, '*')) { $type = 'schemeClr'; $value = substr($fillString, 1); } elseif (str_starts_with($fillString, '/')) { $type = 'prstClr'; $value = substr($fillString, 1); } elseif ($fillString !== '') { $type = 'srgbClr'; $value = $fillString; $this->validateColor($value); } return new ChartColor($value, null, $type); } private function chartColorToString(ChartColor $chartColor): string { $type = (string) $chartColor->getColorProperty('type'); $value = (string) $chartColor->getColorProperty('value'); if ($type === '' || $value === '') { return ''; } if ($type === 'schemeClr') { return "*$value"; } if ($type === 'prstClr') { return "/$value"; } return $value; } /** * Get fill color. * * @return string|string[] HEX color or array with HEX colors */ public function getFillColor(): string|array { if ($this->fillColor === null) { return ''; } if (is_array($this->fillColor)) { $array = []; foreach ($this->fillColor as $chartColor) { $array[] = $this->chartColorToString($chartColor); } return $array; } return $this->chartColorToString($this->fillColor); } /** * Set fill color for series. * * @param ChartColor|ChartColor[]|string|string[] $color HEX color or array with HEX colors * * @return $this */ public function setFillColor($color): static { if (is_array($color)) { $this->fillColor = []; foreach ($color as $fillString) { if ($fillString instanceof ChartColor) { $this->fillColor[] = $fillString; } else { $this->fillColor[] = $this->stringToChartColor($fillString); } } } elseif ($color instanceof ChartColor) { $this->fillColor = $color; } else { $this->fillColor = $this->stringToChartColor($color); } return $this; } /** * Method for validating hex color. * * @param string $color value for color */ private function validateColor(string $color): void { if (!preg_match('/^[a-f0-9]{6}$/i', $color)) { throw new Exception(sprintf('Invalid hex color for chart series (color: "%s")', $color)); } } /** * Get line width for series. */ public function getLineWidth(): null|float|int { /** @var null|float|int */ $temp = $this->lineStyleProperties['width']; return $temp; } /** * Set line width for the series. * * @return $this */ public function setLineWidth(null|float|int $width): static { $this->lineStyleProperties['width'] = $width; return $this; } /** * Identify if the Data Series is a multi-level or a simple series. */ public function isMultiLevelSeries(): ?bool { if (!empty($this->dataValues)) { return is_array(array_values($this->dataValues)[0]); } return null; } /** * Return the level count of a multi-level Data Series. */ public function multiLevelCount(): int { $levelCount = 0; foreach (($this->dataValues ?? []) as $dataValueSet) { /** @var mixed[] $dataValueSet */ $levelCount = max($levelCount, count($dataValueSet)); } return $levelCount; } /** * Get Series Data Values. * * @return null|mixed[] */ public function getDataValues(): ?array { return $this->dataValues; } /** * Get the first Series Data value. */ public function getDataValue(): mixed { if ($this->dataValues === null) { return null; } $count = count($this->dataValues); if ($count == 0) { return null; } elseif ($count == 1) { return $this->dataValues[0]; } return $this->dataValues; } /** * Set Series Data Values. * * @param mixed[] $dataValues * * @return $this */ public function setDataValues(array $dataValues): static { $this->dataValues = Functions::flattenArray($dataValues); $this->pointCount = count($dataValues); return $this; } public function refresh(Worksheet $worksheet, bool $flatten = true): void { if ($this->dataSource !== null) { $calcEngine = Calculation::getInstance($worksheet->getParent()); $newDataValues = Calculation::unwrapResult( $calcEngine->_calculateFormulaValue( '=' . $this->dataSource, null, $worksheet->getCell('A1') ) ); if ($flatten) { $this->dataValues = Functions::flattenArray($newDataValues); foreach ($this->dataValues as &$dataValue) { if (is_string($dataValue) && !empty($dataValue) && $dataValue[0] == '#') { $dataValue = 0.0; } } unset($dataValue); } else { [, $cellRange] = Worksheet::extractSheetTitle($this->dataSource, true); $dimensions = Coordinate::rangeDimension(str_replace('$', '', $cellRange ?? '')); if (($dimensions[0] == 1) || ($dimensions[1] == 1)) { $this->dataValues = Functions::flattenArray($newDataValues); } else { /** @var array */ $newDataValuesx = $newDataValues; /** @var mixed[][] $newArray */ $newArray = array_values(array_shift($newDataValuesx) ?? []); foreach ($newArray as $i => $newDataSet) { $newArray[$i] = [$newDataSet]; } foreach ($newDataValuesx as $newDataSet) { $i = 0; foreach ($newDataSet as $newDataVal) { array_unshift($newArray[$i++], $newDataVal); } } $this->dataValues = $newArray; } } $this->pointCount = count($this->dataValues ?? []); } } public function getScatterLines(): bool { return $this->scatterLines; } public function setScatterLines(bool $scatterLines): self { $this->scatterLines = $scatterLines; return $this; } public function getBubble3D(): bool { return $this->bubble3D; } public function setBubble3D(bool $bubble3D): self { $this->bubble3D = $bubble3D; return $this; } /** * Smooth Line. Must be specified for both DataSeries and DataSeriesValues. */ private bool $smoothLine = false; /** * Get Smooth Line. */ public function getSmoothLine(): bool { return $this->smoothLine; } /** * Set Smooth Line. * * @return $this */ public function setSmoothLine(bool $smoothLine): static { $this->smoothLine = $smoothLine; return $this; } public function getLabelLayout(): ?Layout { return $this->labelLayout; } public function setLabelLayout(?Layout $labelLayout): self { $this->labelLayout = $labelLayout; return $this; } /** @param TrendLine[] $trendLines */ public function setTrendLines(array $trendLines): self { $this->trendLines = $trendLines; return $this; } /** @return TrendLine[] */ public function getTrendLines(): array { return $this->trendLines; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { parent::__clone(); $this->markerFillColor = clone $this->markerFillColor; $this->markerBorderColor = clone $this->markerBorderColor; if (is_array($this->fillColor)) { $fillColor = $this->fillColor; $this->fillColor = []; foreach ($fillColor as $color) { $this->fillColor[] = clone $color; } } elseif ($this->fillColor instanceof ChartColor) { $this->fillColor = clone $this->fillColor; } $this->labelLayout = ($this->labelLayout === null) ? null : clone $this->labelLayout; $trendLines = $this->trendLines; $this->trendLines = []; foreach ($trendLines as $trendLine) { $this->trendLines[] = clone $trendLine; } } } ================================================ FILE: src/PhpSpreadsheet/Chart/Exception.php ================================================ $layout */ public function __construct(array $layout = []) { /** @var array{layoutTarget?: string, xMode?: string, yMode?: string, x?: float, y?: float, w?:float, h?:float, dLblPos?: string, labelFont?: ?mixed, labelFontColor?: ?mixed, labelEffects?: ?mixed, numFmtCode?: string} $layout */ if (isset($layout['layoutTarget'])) { $this->layoutTarget = $layout['layoutTarget']; } if (isset($layout['xMode'])) { $this->xMode = $layout['xMode']; } if (isset($layout['yMode'])) { $this->yMode = $layout['yMode']; } if (isset($layout['x'])) { $this->xPos = (float) $layout['x']; } if (isset($layout['y'])) { $this->yPos = (float) $layout['y']; } if (isset($layout['w'])) { $this->width = (float) $layout['w']; } if (isset($layout['h'])) { $this->height = (float) $layout['h']; } if (isset($layout['dLblPos'])) { $this->dLblPos = (string) $layout['dLblPos']; } if (isset($layout['numFmtCode'])) { $this->numFmtCode = (string) $layout['numFmtCode']; } $this->initBoolean($layout, 'showLegendKey'); $this->initBoolean($layout, 'showVal'); $this->initBoolean($layout, 'showCatName'); $this->initBoolean($layout, 'showSerName'); $this->initBoolean($layout, 'showPercent'); $this->initBoolean($layout, 'showBubbleSize'); $this->initBoolean($layout, 'showLeaderLines'); $this->initBoolean($layout, 'numFmtLinked'); $this->initColor($layout, 'labelFillColor'); $this->initColor($layout, 'labelBorderColor'); $labelFont = $layout['labelFont'] ?? null; if ($labelFont instanceof Font) { $this->labelFont = $labelFont; } $labelFontColor = $layout['labelFontColor'] ?? null; if ($labelFontColor instanceof ChartColor) { $this->setLabelFontColor($labelFontColor); } $labelEffects = $layout['labelEffects'] ?? null; if ($labelEffects instanceof Properties) { $this->labelEffects = $labelEffects; } } /** @param mixed[] $layout */ private function initBoolean(array $layout, string $name): void { if (isset($layout[$name])) { $this->$name = (bool) $layout[$name]; } } /** @param mixed[] $layout */ private function initColor(array $layout, string $name): void { if (isset($layout[$name]) && $layout[$name] instanceof ChartColor) { $this->$name = $layout[$name]; } } /** * Get Layout Target. */ public function getLayoutTarget(): ?string { return $this->layoutTarget; } /** * Set Layout Target. * * @return $this */ public function setLayoutTarget(?string $target): static { $this->layoutTarget = $target; return $this; } /** * Get X-Mode. */ public function getXMode(): ?string { return $this->xMode; } /** * Set X-Mode. * * @return $this */ public function setXMode(?string $mode): static { $this->xMode = (string) $mode; return $this; } /** * Get Y-Mode. */ public function getYMode(): ?string { return $this->yMode; } /** * Set Y-Mode. * * @return $this */ public function setYMode(?string $mode): static { $this->yMode = (string) $mode; return $this; } /** * Get X-Position. */ public function getXPosition(): null|float|int { return $this->xPos; } /** * Set X-Position. * * @return $this */ public function setXPosition(float $position): static { $this->xPos = $position; return $this; } /** * Get Y-Position. */ public function getYPosition(): ?float { return $this->yPos; } /** * Set Y-Position. * * @return $this */ public function setYPosition(float $position): static { $this->yPos = $position; return $this; } /** * Get Width. */ public function getWidth(): ?float { return $this->width; } /** * Set Width. * * @return $this */ public function setWidth(?float $width): static { $this->width = $width; return $this; } /** * Get Height. */ public function getHeight(): ?float { return $this->height; } /** * Set Height. * * @return $this */ public function setHeight(?float $height): static { $this->height = $height; return $this; } public function getShowLegendKey(): ?bool { return $this->showLegendKey; } /** * Set show legend key * Specifies that legend keys should be shown in data labels. */ public function setShowLegendKey(?bool $showLegendKey): self { $this->showLegendKey = $showLegendKey; return $this; } public function getShowVal(): ?bool { return $this->showVal; } /** * Set show val * Specifies that the value should be shown in data labels. */ public function setShowVal(?bool $showDataLabelValues): self { $this->showVal = $showDataLabelValues; return $this; } public function getShowCatName(): ?bool { return $this->showCatName; } /** * Set show cat name * Specifies that the category name should be shown in data labels. */ public function setShowCatName(?bool $showCategoryName): self { $this->showCatName = $showCategoryName; return $this; } public function getShowSerName(): ?bool { return $this->showSerName; } /** * Set show data series name. * Specifies that the series name should be shown in data labels. */ public function setShowSerName(?bool $showSeriesName): self { $this->showSerName = $showSeriesName; return $this; } public function getShowPercent(): ?bool { return $this->showPercent; } /** * Set show percentage. * Specifies that the percentage should be shown in data labels. */ public function setShowPercent(?bool $showPercentage): self { $this->showPercent = $showPercentage; return $this; } public function getShowBubbleSize(): ?bool { return $this->showBubbleSize; } /** * Set show bubble size. * Specifies that the bubble size should be shown in data labels. */ public function setShowBubbleSize(?bool $showBubbleSize): self { $this->showBubbleSize = $showBubbleSize; return $this; } public function getShowLeaderLines(): ?bool { return $this->showLeaderLines; } /** * Set show leader lines. * Specifies that leader lines should be shown in data labels. */ public function setShowLeaderLines(?bool $showLeaderLines): self { $this->showLeaderLines = $showLeaderLines; return $this; } public function getLabelFillColor(): ?ChartColor { return $this->labelFillColor; } public function setLabelFillColor(?ChartColor $chartColor): self { $this->labelFillColor = $chartColor; return $this; } public function getLabelBorderColor(): ?ChartColor { return $this->labelBorderColor; } public function setLabelBorderColor(?ChartColor $chartColor): self { $this->labelBorderColor = $chartColor; return $this; } public function getLabelFont(): ?Font { return $this->labelFont; } public function setLabelFont(?Font $labelFont): self { $this->labelFont = $labelFont; return $this; } public function getLabelEffects(): ?Properties { return $this->labelEffects; } public function getLabelFontColor(): ?ChartColor { if ($this->labelFont === null) { return null; } return $this->labelFont->getChartColor(); } public function setLabelFontColor(?ChartColor $chartColor): self { if ($this->labelFont === null) { $this->labelFont = new Font(); $this->labelFont->setSize(null, true); } $this->labelFont->setChartColorFromObject($chartColor); return $this; } public function getDLblPos(): string { return $this->dLblPos; } public function setDLblPos(string $dLblPos): self { $this->dLblPos = $dLblPos; return $this; } public function getNumFmtCode(): string { return $this->numFmtCode; } public function setNumFmtCode(string $numFmtCode): self { $this->numFmtCode = $numFmtCode; return $this; } public function getNumFmtLinked(): bool { return $this->numFmtLinked; } public function setNumFmtLinked(bool $numFmtLinked): self { $this->numFmtLinked = $numFmtLinked; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->labelFillColor = ($this->labelFillColor === null) ? null : clone $this->labelFillColor; $this->labelBorderColor = ($this->labelBorderColor === null) ? null : clone $this->labelBorderColor; $this->labelFont = ($this->labelFont === null) ? null : clone $this->labelFont; $this->labelEffects = ($this->labelEffects === null) ? null : clone $this->labelEffects; } } ================================================ FILE: src/PhpSpreadsheet/Chart/Legend.php ================================================ self::POSITION_BOTTOM, self::XL_LEGEND_POSITION_CORNER => self::POSITION_TOPRIGHT, self::XL_LEGEND_POSITION_CUSTOM => '??', self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT, self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT, self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP, ]; /** * Legend position. */ private string $position = self::POSITION_RIGHT; /** * Allow overlay of other elements? */ private bool $overlay = true; /** * Legend Layout. */ private ?Layout $layout; private GridLines $borderLines; private ChartColor $fillColor; private ?AxisText $legendText = null; /** * Create a new Legend. */ public function __construct(string $position = self::POSITION_RIGHT, ?Layout $layout = null, bool $overlay = false) { $this->setPosition($position); $this->layout = $layout; $this->setOverlay($overlay); $this->borderLines = new GridLines(); $this->fillColor = new ChartColor(); } public function getFillColor(): ChartColor { return $this->fillColor; } /** * Get legend position as an Excel string value. */ public function getPosition(): string { return $this->position; } /** * Get legend position using an Excel string value. * * @param string $position see self::POSITION_* */ public function setPosition(string $position): bool { if (!in_array($position, self::POSITION_XLREF)) { return false; } $this->position = $position; return true; } /** * Get legend position as an Excel internal numeric value. */ public function getPositionXL(): false|int { return array_search($this->position, self::POSITION_XLREF); } /** * Set legend position using an Excel internal numeric value. * * @param int $positionXL see self::XL_LEGEND_POSITION_* */ public function setPositionXL(int $positionXL): bool { if (!isset(self::POSITION_XLREF[$positionXL])) { return false; } $this->position = self::POSITION_XLREF[$positionXL]; return true; } /** * Get allow overlay of other elements? */ public function getOverlay(): bool { return $this->overlay; } /** * Set allow overlay of other elements? */ public function setOverlay(bool $overlay): void { $this->overlay = $overlay; } /** * Get Layout. */ public function getLayout(): ?Layout { return $this->layout; } public function getLegendText(): ?AxisText { return $this->legendText; } public function setLegendText(?AxisText $legendText): self { $this->legendText = $legendText; return $this; } public function getBorderLines(): GridLines { return $this->borderLines; } public function setBorderLines(GridLines $borderLines): self { $this->borderLines = $borderLines; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->layout = ($this->layout === null) ? null : clone $this->layout; $this->legendText = ($this->legendText === null) ? null : clone $this->legendText; $this->borderLines = clone $this->borderLines; $this->fillColor = clone $this->fillColor; } } ================================================ FILE: src/PhpSpreadsheet/Chart/PlotArea.php ================================================ */ private array $gradientFillStops = []; /** * PlotArea Gradient Angle. */ private ?float $gradientFillAngle = null; /** * PlotArea Layout. */ private ?Layout $layout; /** * Plot Series. * * @var DataSeries[] */ private array $plotSeries; /** * Create a new PlotArea. * * @param DataSeries[] $plotSeries */ public function __construct(?Layout $layout = null, array $plotSeries = []) { $this->layout = $layout; $this->plotSeries = $plotSeries; } public function getLayout(): ?Layout { return $this->layout; } /** * Get Number of Plot Groups. */ public function getPlotGroupCount(): int { return count($this->plotSeries); } /** * Get Number of Plot Series. */ public function getPlotSeriesCount(): int|float { $seriesCount = 0; foreach ($this->plotSeries as $plot) { $seriesCount += $plot->getPlotSeriesCount(); } return $seriesCount; } /** * Get Plot Series. * * @return DataSeries[] */ public function getPlotGroup(): array { return $this->plotSeries; } /** * Get Plot Series by Index. */ public function getPlotGroupByIndex(int $index): DataSeries { return $this->plotSeries[$index]; } /** * Set Plot Series. * * @param DataSeries[] $plotSeries * * @return $this */ public function setPlotSeries(array $plotSeries): static { $this->plotSeries = $plotSeries; return $this; } public function refresh(Worksheet $worksheet): void { foreach ($this->plotSeries as $plotSeries) { $plotSeries->refresh($worksheet); } } public function setNoFill(bool $noFill): self { $this->noFill = $noFill; return $this; } public function getNoFill(): bool { return $this->noFill; } /** @param array $gradientFillStops */ public function setGradientFillProperties(array $gradientFillStops, ?float $gradientFillAngle): self { $this->gradientFillStops = $gradientFillStops; $this->gradientFillAngle = $gradientFillAngle; return $this; } /** * Get gradientFillAngle. */ public function getGradientFillAngle(): ?float { return $this->gradientFillAngle; } /** * Get gradientFillStops. * * @return array */ public function getGradientFillStops(): array { return $this->gradientFillStops; } private ?int $gapWidth = null; private bool $useUpBars = false; private bool $useDownBars = false; public function getGapWidth(): ?int { return $this->gapWidth; } public function setGapWidth(?int $gapWidth): self { $this->gapWidth = $gapWidth; return $this; } public function getUseUpBars(): bool { return $this->useUpBars; } public function setUseUpBars(bool $useUpBars): self { $this->useUpBars = $useUpBars; return $this; } public function getUseDownBars(): bool { return $this->useDownBars; } public function setUseDownBars(bool $useDownBars): self { $this->useDownBars = $useDownBars; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->layout = ($this->layout === null) ? null : clone $this->layout; $plotSeries = $this->plotSeries; $this->plotSeries = []; foreach ($plotSeries as $series) { $this->plotSeries[] = clone $series; } } } ================================================ FILE: src/PhpSpreadsheet/Chart/Properties.php ================================================ null, ]; /** @var mixed[] */ protected array $shadowProperties = self::PRESETS_OPTIONS[0]; protected ChartColor $shadowColor; public function __construct() { $this->lineColor = new ChartColor(); $this->glowColor = new ChartColor(); $this->shadowColor = new ChartColor(); $this->shadowColor->setType(ChartColor::EXCEL_COLOR_TYPE_STANDARD); $this->shadowColor->setValue('black'); $this->shadowColor->setAlpha(40); } /** * Get Object State. */ public function getObjectState(): bool { return $this->objectState; } /** * Change Object State to True. * * @return $this */ public function activateObject() { $this->objectState = true; return $this; } public static function pointsToXml(float $width): string { return (string) (int) ($width * self::POINTS_WIDTH_MULTIPLIER); } public static function xmlToPoints(string $width): float { return ((float) $width) / self::POINTS_WIDTH_MULTIPLIER; } public static function angleToXml(float $angle): string { return (string) (int) ($angle * self::ANGLE_MULTIPLIER); } public static function xmlToAngle(string $angle): float { return ((float) $angle) / self::ANGLE_MULTIPLIER; } public static function tenthOfPercentToXml(float $value): string { return (string) (int) ($value * self::PERCENTAGE_MULTIPLIER); } public static function xmlToTenthOfPercent(string $value): float { return ((float) $value) / self::PERCENTAGE_MULTIPLIER; } /** @return array{type: ?string, value: ?string, alpha: ?int} */ protected function setColorProperties(?string $color, null|float|int|string $alpha, ?string $colorType): array { return [ 'type' => $colorType, 'value' => $color, 'alpha' => ($alpha === null) ? null : (int) $alpha, ]; } protected const PRESETS_OPTIONS = [ //NONE 0 => [ 'presets' => self::SHADOW_PRESETS_NOSHADOW, 'effect' => null, //'color' => [ // 'type' => ChartColor::EXCEL_COLOR_TYPE_STANDARD, // 'value' => 'black', // 'alpha' => 40, //], 'size' => [ 'sx' => null, 'sy' => null, 'kx' => null, 'ky' => null, ], 'blur' => null, 'direction' => null, 'distance' => null, 'algn' => null, 'rotWithShape' => null, ], //OUTER 1 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 2700000 / self::ANGLE_MULTIPLIER, 'algn' => 'tl', 'rotWithShape' => '0', ], 2 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 5400000 / self::ANGLE_MULTIPLIER, 'algn' => 't', 'rotWithShape' => '0', ], 3 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 8100000 / self::ANGLE_MULTIPLIER, 'algn' => 'tr', 'rotWithShape' => '0', ], 4 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'algn' => 'l', 'rotWithShape' => '0', ], 5 => [ 'effect' => 'outerShdw', 'size' => [ 'sx' => 102000 / self::PERCENTAGE_MULTIPLIER, 'sy' => 102000 / self::PERCENTAGE_MULTIPLIER, ], 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'algn' => 'ctr', 'rotWithShape' => '0', ], 6 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 10800000 / self::ANGLE_MULTIPLIER, 'algn' => 'r', 'rotWithShape' => '0', ], 7 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 18900000 / self::ANGLE_MULTIPLIER, 'algn' => 'bl', 'rotWithShape' => '0', ], 8 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 16200000 / self::ANGLE_MULTIPLIER, 'rotWithShape' => '0', ], 9 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 13500000 / self::ANGLE_MULTIPLIER, 'algn' => 'br', 'rotWithShape' => '0', ], //INNER 10 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 2700000 / self::ANGLE_MULTIPLIER, ], 11 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 5400000 / self::ANGLE_MULTIPLIER, ], 12 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 8100000 / self::ANGLE_MULTIPLIER, ], 13 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, ], 14 => [ 'effect' => 'innerShdw', 'blur' => 114300 / self::POINTS_WIDTH_MULTIPLIER, ], 15 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 10800000 / self::ANGLE_MULTIPLIER, ], 16 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 18900000 / self::ANGLE_MULTIPLIER, ], 17 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 16200000 / self::ANGLE_MULTIPLIER, ], 18 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 13500000 / self::ANGLE_MULTIPLIER, ], //perspective 19 => [ 'effect' => 'outerShdw', 'blur' => 152400 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 317500 / self::POINTS_WIDTH_MULTIPLIER, 'size' => [ 'sx' => 90000 / self::PERCENTAGE_MULTIPLIER, 'sy' => -19000 / self::PERCENTAGE_MULTIPLIER, ], 'direction' => 5400000 / self::ANGLE_MULTIPLIER, 'rotWithShape' => '0', ], 20 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 18900000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => 23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => -1200000 / self::ANGLE_MULTIPLIER, ], 'algn' => 'bl', 'rotWithShape' => '0', ], 21 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 13500000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => 23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => 1200000 / self::ANGLE_MULTIPLIER, ], 'algn' => 'br', 'rotWithShape' => '0', ], 22 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 12700 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 2700000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => -23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => -800400 / self::ANGLE_MULTIPLIER, ], 'algn' => 'bl', 'rotWithShape' => '0', ], 23 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 12700 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 8100000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => -23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => 800400 / self::ANGLE_MULTIPLIER, ], 'algn' => 'br', 'rotWithShape' => '0', ], ]; /** @return mixed[] */ protected function getShadowPresetsMap(int $presetsOption): array { return self::PRESETS_OPTIONS[$presetsOption] ?? self::PRESETS_OPTIONS[0]; } /** * Get value of array element. * * @param mixed[] $properties * @param array|int|string $elements */ protected function getArrayElementsValue(array $properties, array|int|string $elements): mixed { $reference = &$properties; if (!is_array($elements)) { return $reference[$elements]; } foreach ($elements as $keys) { $reference = &$reference[$keys]; //* @phpstan-ignore-line } return $reference; } /** * Set Glow Properties. */ public function setGlowProperties(float $size, ?string $colorValue = null, ?int $colorAlpha = null, ?string $colorType = null): void { $this ->activateObject() ->setGlowSize($size); $this->glowColor->setColorPropertiesArray( [ 'value' => $colorValue, 'type' => $colorType, 'alpha' => $colorAlpha, ] ); } /** * Get Glow Property. * * @param mixed[]|string $property * * @return null|array|float|int|string */ public function getGlowProperty(array|string $property): null|array|float|int|string { $retVal = null; if ($property === 'size') { $retVal = $this->glowSize; } elseif ($property === 'color') { $retVal = [ 'value' => $this->glowColor->getColorProperty('value'), 'type' => $this->glowColor->getColorProperty('type'), 'alpha' => $this->glowColor->getColorProperty('alpha'), ]; } elseif (is_array($property) && count($property) >= 2 && $property[0] === 'color') { /** @var string */ $temp = $property[1]; $retVal = $this->glowColor->getColorProperty($temp); } return $retVal; } /** * Get Glow Color Property. */ public function getGlowColor(string $propertyName): null|int|string { return $this->glowColor->getColorProperty($propertyName); } public function getGlowColorObject(): ChartColor { return $this->glowColor; } /** * Get Glow Size. */ public function getGlowSize(): ?float { return $this->glowSize; } /** * Set Glow Size. * * @return $this */ protected function setGlowSize(?float $size) { $this->glowSize = $size; return $this; } /** * Set Soft Edges Size. */ public function setSoftEdges(?float $size): void { if ($size !== null) { $this->activateObject(); $this->softEdges['size'] = $size; } } /** * Get Soft Edges Size. */ public function getSoftEdgesSize(): ?float { return $this->softEdges['size']; } /** @param null|array{value?: ?string, alpha?: null|int|string, brightness?: null|int|string, type?: ?string}|float|string $value */ public function setShadowProperty(string $propertyName, mixed $value): self { $this->activateObject(); if ($propertyName === 'color' && is_array($value)) { /** @var array{value: ?string, alpha: null|int|string, brightness?: null|int|string, type: ?string} */ $valuex = $value; $this->shadowColor->setColorPropertiesArray($valuex); } else { $this->shadowProperties[$propertyName] = $value; } return $this; } /** * Set Shadow Properties. */ public function setShadowProperties(int $presets, ?string $colorValue = null, ?string $colorType = null, null|float|int|string $colorAlpha = null, ?float $blur = null, ?int $angle = null, ?float $distance = null): void { $this->activateObject()->setShadowPresetsProperties((int) $presets); if ($presets === 0) { $this->shadowColor->setType(ChartColor::EXCEL_COLOR_TYPE_STANDARD); $this->shadowColor->setValue('black'); $this->shadowColor->setAlpha(40); } if ($colorValue !== null) { $this->shadowColor->setValue($colorValue); } if ($colorType !== null) { $this->shadowColor->setType($colorType); } if (is_numeric($colorAlpha)) { $this->shadowColor->setAlpha((int) $colorAlpha); } $this ->setShadowBlur($blur) ->setShadowAngle($angle) ->setShadowDistance($distance); } /** * Set Shadow Presets Properties. * * @return $this */ protected function setShadowPresetsProperties(int $presets) { $this->shadowProperties['presets'] = $presets; $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets)); return $this; } protected const SHADOW_ARRAY_KEYS = ['size', 'color']; /** * Set Shadow Properties Values. * * @param mixed[] $propertiesMap * @param null|mixed[] $reference * * @return $this */ protected function setShadowPropertiesMapValues(array $propertiesMap, ?array &$reference = null) { $base_reference = $reference; foreach ($propertiesMap as $property_key => $property_val) { if (is_array($property_val)) { if (in_array($property_key, self::SHADOW_ARRAY_KEYS, true)) { /** @var null|array */ $temp = &$this->shadowProperties[$property_key]; $reference = &$temp; $this->setShadowPropertiesMapValues( $property_val, $reference ); } } else { if ($base_reference === null) { $this->shadowProperties[$property_key] = $property_val; } else { $reference[$property_key] = $property_val; } } } return $this; } /** * Set Shadow Blur. * * @return $this */ protected function setShadowBlur(?float $blur) { if ($blur !== null) { $this->shadowProperties['blur'] = $blur; } return $this; } /** * Set Shadow Angle. * * @return $this */ protected function setShadowAngle(null|float|int|string $angle) { if (is_numeric($angle)) { $this->shadowProperties['direction'] = $angle; } return $this; } /** * Set Shadow Distance. * * @return $this */ protected function setShadowDistance(?float $distance) { if ($distance !== null) { $this->shadowProperties['distance'] = $distance; } return $this; } public function getShadowColorObject(): ChartColor { return $this->shadowColor; } /** * Get Shadow Property. * * @param string|string[] $elements * * @return null|mixed[]|string */ public function getShadowProperty($elements): array|string|null { if ($elements === 'color') { return [ 'value' => $this->shadowColor->getValue(), 'type' => $this->shadowColor->getType(), 'alpha' => $this->shadowColor->getAlpha(), ]; } $retVal = $this->getArrayElementsValue($this->shadowProperties, $elements); if (is_scalar($retVal)) { $retVal = (string) $retVal; } elseif ($retVal !== null && !is_array($retVal)) { // @codeCoverageIgnoreStart throw new Exception('Unexpected value for shadowProperty'); // @codeCoverageIgnoreEnd } return $retVal; } /** @return mixed[] */ public function getShadowArray(): array { $array = $this->shadowProperties; if ($this->getShadowColorObject()->isUsable()) { $array['color'] = $this->getShadowProperty('color'); } return $array; } protected ChartColor $lineColor; /** @var array{width: null|float|int|string, compound: ?string, dash: ?string, cap: ?string, join: ?string, arrow: array{head: array{type: ?string, size: null|int|string, w: ?string, len: ?string}, end: array{type: ?string, size: null|int|string, w: ?string, len: ?string}}} */ protected array $lineStyleProperties = [ 'width' => null, //'9525', 'compound' => '', //self::LINE_STYLE_COMPOUND_SIMPLE, 'dash' => '', //self::LINE_STYLE_DASH_SOLID, 'cap' => '', //self::LINE_STYLE_CAP_FLAT, 'join' => '', //self::LINE_STYLE_JOIN_BEVEL, 'arrow' => [ 'head' => [ 'type' => '', //self::LINE_STYLE_ARROW_TYPE_NOARROW, 'size' => '', //self::LINE_STYLE_ARROW_SIZE_5, 'w' => '', 'len' => '', ], 'end' => [ 'type' => '', //self::LINE_STYLE_ARROW_TYPE_NOARROW, 'size' => '', //self::LINE_STYLE_ARROW_SIZE_8, 'w' => '', 'len' => '', ], ], ]; public function copyLineStyles(self $otherProperties): void { $this->lineStyleProperties = $otherProperties->lineStyleProperties; $this->lineColor = $otherProperties->lineColor; $this->glowSize = $otherProperties->glowSize; $this->glowColor = $otherProperties->glowColor; $this->softEdges = $otherProperties->softEdges; $this->shadowProperties = $otherProperties->shadowProperties; } public function getLineColor(): ChartColor { return $this->lineColor; } /** * Set Line Color Properties. */ public function setLineColorProperties(?string $value, ?int $alpha = null, ?string $colorType = null): void { $this->activateObject(); $this->lineColor->setColorPropertiesArray( $this->setColorProperties( $value, $alpha, $colorType ) ); } /** * Get Line Color Property. */ public function getLineColorProperty(string $propertyName): null|int|string { return $this->lineColor->getColorProperty($propertyName); } /** * Set Line Style Properties. */ public function setLineStyleProperties( null|float|int|string $lineWidth = null, ?string $compoundType = '', ?string $dashType = '', ?string $capType = '', ?string $joinType = '', ?string $headArrowType = '', int $headArrowSize = 0, ?string $endArrowType = '', int $endArrowSize = 0, ?string $headArrowWidth = '', ?string $headArrowLength = '', ?string $endArrowWidth = '', ?string $endArrowLength = '' ): void { $this->activateObject(); if (is_numeric($lineWidth)) { $this->lineStyleProperties['width'] = $lineWidth; } if ($compoundType !== '') { $this->lineStyleProperties['compound'] = $compoundType; } if ($dashType !== '') { $this->lineStyleProperties['dash'] = $dashType; } if ($capType !== '') { $this->lineStyleProperties['cap'] = $capType; } if ($joinType !== '') { $this->lineStyleProperties['join'] = $joinType; } if ($headArrowType !== '') { $this->lineStyleProperties['arrow']['head']['type'] = $headArrowType; } if (isset(self::ARROW_SIZES[$headArrowSize])) { $this->lineStyleProperties['arrow']['head']['size'] = $headArrowSize; $this->lineStyleProperties['arrow']['head']['w'] = self::ARROW_SIZES[$headArrowSize]['w']; $this->lineStyleProperties['arrow']['head']['len'] = self::ARROW_SIZES[$headArrowSize]['len']; } if ($endArrowType !== '') { $this->lineStyleProperties['arrow']['end']['type'] = $endArrowType; } if (isset(self::ARROW_SIZES[$endArrowSize])) { $this->lineStyleProperties['arrow']['end']['size'] = $endArrowSize; $this->lineStyleProperties['arrow']['end']['w'] = self::ARROW_SIZES[$endArrowSize]['w']; $this->lineStyleProperties['arrow']['end']['len'] = self::ARROW_SIZES[$endArrowSize]['len']; } if ($headArrowWidth !== '') { $this->lineStyleProperties['arrow']['head']['w'] = $headArrowWidth; } if ($headArrowLength !== '') { $this->lineStyleProperties['arrow']['head']['len'] = $headArrowLength; } if ($endArrowWidth !== '') { $this->lineStyleProperties['arrow']['end']['w'] = $endArrowWidth; } if ($endArrowLength !== '') { $this->lineStyleProperties['arrow']['end']['len'] = $endArrowLength; } } /** @return mixed[] */ public function getLineStyleArray(): array { return $this->lineStyleProperties; } /** @param mixed[] $lineStyleProperties */ public function setLineStyleArray(array $lineStyleProperties = []): self { /** @var array{width?: ?string, compound?: string, dash?: string, cap?: string, join?: string, arrow?: array{head?: array{type?: string, size?: int, w?: string, len?: string}, end?: array{type?: string, size?: int, w?: string, len?: string}}} $lineStyleProperties */ $this->activateObject(); $this->lineStyleProperties['width'] = $lineStyleProperties['width'] ?? null; $this->lineStyleProperties['compound'] = $lineStyleProperties['compound'] ?? ''; $this->lineStyleProperties['dash'] = $lineStyleProperties['dash'] ?? ''; $this->lineStyleProperties['cap'] = $lineStyleProperties['cap'] ?? ''; $this->lineStyleProperties['join'] = $lineStyleProperties['join'] ?? ''; $this->lineStyleProperties['arrow']['head']['type'] = $lineStyleProperties['arrow']['head']['type'] ?? ''; $this->lineStyleProperties['arrow']['head']['size'] = $lineStyleProperties['arrow']['head']['size'] ?? ''; $this->lineStyleProperties['arrow']['head']['w'] = $lineStyleProperties['arrow']['head']['w'] ?? ''; $this->lineStyleProperties['arrow']['head']['len'] = $lineStyleProperties['arrow']['head']['len'] ?? ''; $this->lineStyleProperties['arrow']['end']['type'] = $lineStyleProperties['arrow']['end']['type'] ?? ''; $this->lineStyleProperties['arrow']['end']['size'] = $lineStyleProperties['arrow']['end']['size'] ?? ''; $this->lineStyleProperties['arrow']['end']['w'] = $lineStyleProperties['arrow']['end']['w'] ?? ''; $this->lineStyleProperties['arrow']['end']['len'] = $lineStyleProperties['arrow']['end']['len'] ?? ''; return $this; } public function setLineStyleProperty(string $propertyName, mixed $value): self { $this->activateObject(); $this->lineStyleProperties[$propertyName] = $value; //* @phpstan-ignore-line return $this; } /** * Get Line Style Property. * * @param array|string $elements */ public function getLineStyleProperty(array|string $elements): ?string { $retVal = $this->getArrayElementsValue($this->lineStyleProperties, $elements); if (is_scalar($retVal)) { $retVal = (string) $retVal; } elseif ($retVal !== null) { // @codeCoverageIgnoreStart throw new Exception('Unexpected value for lineStyleProperty'); // @codeCoverageIgnoreEnd } return $retVal; } protected const ARROW_SIZES = [ 1 => ['w' => 'sm', 'len' => 'sm'], 2 => ['w' => 'sm', 'len' => 'med'], 3 => ['w' => 'sm', 'len' => 'lg'], 4 => ['w' => 'med', 'len' => 'sm'], 5 => ['w' => 'med', 'len' => 'med'], 6 => ['w' => 'med', 'len' => 'lg'], 7 => ['w' => 'lg', 'len' => 'sm'], 8 => ['w' => 'lg', 'len' => 'med'], 9 => ['w' => 'lg', 'len' => 'lg'], ]; /** * Get Line Style Arrow Size. */ protected function getLineStyleArrowSize(int $arraySelector, string $arrayKaySelector): string { return self::ARROW_SIZES[$arraySelector][$arrayKaySelector] ?? ''; } /** * Get Line Style Arrow Parameters. */ public function getLineStyleArrowParameters(string $arrowSelector, string $propertySelector): string { return $this->getLineStyleArrowSize((int) $this->lineStyleProperties['arrow'][$arrowSelector]['size'], $propertySelector); } /** * Get Line Style Arrow Width. */ public function getLineStyleArrowWidth(string $arrow): ?string { return $this->getLineStyleProperty(['arrow', $arrow, 'w']); } /** * Get Line Style Arrow Excel Length. */ public function getLineStyleArrowLength(string $arrow): ?string { return $this->getLineStyleProperty(['arrow', $arrow, 'len']); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->lineColor = clone $this->lineColor; $this->glowColor = clone $this->glowColor; $this->shadowColor = clone $this->shadowColor; } } ================================================ FILE: src/PhpSpreadsheet/Chart/Renderer/IRenderer.php ================================================ graph = null; $this->chart = $chart; self::$markSet = [ 'diamond' => MARK_DIAMOND, 'square' => MARK_SQUARE, 'triangle' => MARK_UTRIANGLE, 'x' => MARK_X, 'star' => MARK_STAR, 'dot' => MARK_FILLEDCIRCLE, 'dash' => MARK_DTRIANGLE, 'circle' => MARK_CIRCLE, 'plus' => MARK_CROSS, ]; } private function getGraphWidth(): float { return $this->chart->getRenderedWidth() ?? self::DEFAULT_WIDTH; } private function getGraphHeight(): float { return $this->chart->getRenderedHeight() ?? self::DEFAULT_HEIGHT; } /** * This method should be overridden in descendants to do real JpGraph library initialization. */ abstract protected static function init(): void; private function formatPointMarker($seriesPlot, $markerID) { $plotMarkKeys = array_keys(self::$markSet); if ($markerID === null) { // Use default plot marker (next marker in the series) self::$plotMark %= count(self::$markSet); $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); } elseif ($markerID !== 'none') { // Use specified plot marker (if it exists) if (isset(self::$markSet[$markerID])) { $seriesPlot->mark->SetType(self::$markSet[$markerID]); } else { // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) self::$plotMark %= count(self::$markSet); $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); } } else { // Hide plot marker $seriesPlot->mark->Hide(); } $seriesPlot->mark->SetColor(self::$colourSet[self::$plotColour]); $seriesPlot->mark->SetFillColor(self::$colourSet[self::$plotColour]); $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); return $seriesPlot; } private function formatDataSetLabels(int $groupID, array $datasetLabels, $rotation = '') { $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode() ?? ''; // Retrieve any label formatting code $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); $testCurrentIndex = 0; foreach ($datasetLabels as $i => $datasetLabel) { if (is_array($datasetLabel)) { if ($rotation == 'bar') { $datasetLabels[$i] = implode(' ', $datasetLabel); } else { $datasetLabel = array_reverse($datasetLabel); $datasetLabels[$i] = implode("\n", $datasetLabel); } } else { // Format labels according to any formatting code if ($datasetLabelFormatCode !== null) { $datasetLabels[$i] = NumberFormat::toFormattedString($datasetLabel, $datasetLabelFormatCode); } } ++$testCurrentIndex; } return $datasetLabels; } private function percentageSumCalculation(int $groupID, $seriesCount) { $sumValues = []; // Adjust our values to a percentage value across all series in the group for ($i = 0; $i < $seriesCount; ++$i) { if ($i == 0) { $sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); } else { $nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); foreach ($nextValues as $k => $value) { if (isset($sumValues[$k])) { $sumValues[$k] += $value; } else { $sumValues[$k] = $value; } } } } return $sumValues; } private function percentageAdjustValues(array $dataValues, array $sumValues) { foreach ($dataValues as $k => $dataValue) { $dataValues[$k] = $dataValue / $sumValues[$k] * 100; } return $dataValues; } private function getCaption($captionElement) { // Read any caption $caption = ($captionElement !== null) ? $captionElement->getCaption() : null; // Test if we have a title caption to display if ($caption !== null) { // If we do, it could be a plain string or an array if (is_array($caption)) { // Implode an array to a plain string $caption = implode('', $caption); } } return $caption; } private function renderTitle(): void { $title = $this->getCaption($this->chart->getTitle()); if ($title !== null) { $this->graph->title->Set($title); } } private function renderLegend(): void { $legend = $this->chart->getLegend(); if ($legend !== null) { $legendPosition = $legend->getPosition(); switch ($legendPosition) { case 'r': $this->graph->legend->SetPos(0.01, 0.5, 'right', 'center'); // right $this->graph->legend->SetColumns(1); break; case 'l': $this->graph->legend->SetPos(0.01, 0.5, 'left', 'center'); // left $this->graph->legend->SetColumns(1); break; case 't': $this->graph->legend->SetPos(0.5, 0.01, 'center', 'top'); // top break; case 'b': $this->graph->legend->SetPos(0.5, 0.99, 'center', 'bottom'); // bottom break; default: $this->graph->legend->SetPos(0.01, 0.01, 'right', 'top'); // top-right $this->graph->legend->SetColumns(1); break; } } else { $this->graph->legend->Hide(); } } private function renderCartesianPlotArea(string $type = 'textlin'): void { $this->graph = new Graph($this->getGraphWidth(), $this->getGraphHeight()); $this->graph->SetScale($type); $this->renderTitle(); // Rotate for bar rather than column chart $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); $reverse = $rotation == 'bar'; $xAxisLabel = $this->chart->getXAxisLabel(); if ($xAxisLabel !== null) { $title = $this->getCaption($xAxisLabel); if ($title !== null) { $this->graph->xaxis->SetTitle($title, 'center'); $this->graph->xaxis->title->SetMargin(35); if ($reverse) { $this->graph->xaxis->title->SetAngle(90); $this->graph->xaxis->title->SetMargin(90); } } } $yAxisLabel = $this->chart->getYAxisLabel(); if ($yAxisLabel !== null) { $title = $this->getCaption($yAxisLabel); if ($title !== null) { $this->graph->yaxis->SetTitle($title, 'center'); if ($reverse) { $this->graph->yaxis->title->SetAngle(0); $this->graph->yaxis->title->SetMargin(-55); } } } } private function renderPiePlotArea(): void { $this->graph = new PieGraph($this->getGraphWidth(), $this->getGraphHeight()); $this->renderTitle(); } private function renderRadarPlotArea(): void { $this->graph = new RadarGraph($this->getGraphWidth(), $this->getGraphHeight()); $this->graph->SetScale('lin'); $this->renderTitle(); } private function getDataLabel(int $groupId, int $index): mixed { $plotLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupId)->getPlotLabelByIndex($index); if (!$plotLabel) { return ''; } return $plotLabel->getDataValue(); } private function renderPlotLine(int $groupID, bool $filled = false, bool $combination = false): void { $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[0]; $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels); $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); } else { $sumValues = []; } // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[$i]; $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getDataValues(); $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointMarker(); if ($grouping == 'percentStacked') { $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); } // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; foreach ($dataValues as $k => $dataValue) { while ($k != $testCurrentIndex) { $dataValues[$testCurrentIndex] = null; ++$testCurrentIndex; } ++$testCurrentIndex; } $seriesPlot = new LinePlot($dataValues); if ($combination) { $seriesPlot->SetBarCenter(); } if ($filled) { $seriesPlot->SetFilled(true); $seriesPlot->SetColor('black'); $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); } else { // Set the appropriate plot marker $this->formatPointMarker($seriesPlot, $marker); } $seriesPlot->SetLegend($this->getDataLabel($groupID, $index)); $seriesPlots[] = $seriesPlot; } if ($grouping == 'standard') { $groupPlot = $seriesPlots; } else { $groupPlot = new AccLinePlot($seriesPlots); } $this->graph->Add($groupPlot); } private function renderPlotBar(int $groupID, ?string $dimensions = '2d'): void { $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); // Rotate for bar rather than column chart if (($groupID == 0) && ($rotation == 'bar')) { $this->graph->Set90AndMargin(); } $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[0]; $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $rotation); // Rotate for bar rather than column chart if ($rotation == 'bar') { $datasetLabels = array_reverse($datasetLabels); $this->graph->yaxis->SetPos('max'); $this->graph->yaxis->SetLabelAlign('center', 'top'); $this->graph->yaxis->SetLabelSide(SIDE_RIGHT); } $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); } else { $sumValues = []; } // Loop through each data series in turn for ($j = 0; $j < $seriesCount; ++$j) { $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[$j]; $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getDataValues(); if ($grouping == 'percentStacked') { $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); } // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; foreach ($dataValues as $k => $dataValue) { while ($k != $testCurrentIndex) { $dataValues[$testCurrentIndex] = null; ++$testCurrentIndex; } ++$testCurrentIndex; } // Reverse the $dataValues order for bar rather than column chart if ($rotation == 'bar') { $dataValues = array_reverse($dataValues); } $seriesPlot = new BarPlot($dataValues); $seriesPlot->SetColor('black'); $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); if ($dimensions == '3d') { $seriesPlot->SetShadow(); } $seriesPlot->SetLegend($this->getDataLabel($groupID, $j)); $seriesPlots[] = $seriesPlot; } // Reverse the plot order for bar rather than column chart if (($rotation == 'bar') && ($grouping != 'percentStacked')) { $seriesPlots = array_reverse($seriesPlots); } if ($grouping == 'clustered') { $groupPlot = new GroupBarPlot($seriesPlots); } elseif ($grouping == 'standard') { $groupPlot = new GroupBarPlot($seriesPlots); } else { $groupPlot = new AccBarPlot($seriesPlots); if ($dimensions == '3d') { $groupPlot->SetShadow(); } } $this->graph->Add($groupPlot); } private function renderPlotScatter(int $groupID, bool $bubble): void { $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $plotCategoryByIndex = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i); if ($plotCategoryByIndex === false) { $plotCategoryByIndex = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0); } $dataValuesY = $plotCategoryByIndex->getDataValues(); $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $redoDataValuesY = true; if ($bubble) { if (!$bubbleSize) { $bubbleSize = '10'; } $redoDataValuesY = false; foreach ($dataValuesY as $dataValueY) { if (!is_int($dataValueY) && !is_float($dataValueY)) { $redoDataValuesY = true; break; } } } if ($redoDataValuesY) { foreach ($dataValuesY as $k => $dataValueY) { $dataValuesY[$k] = $k; } } $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); if ($scatterStyle == 'lineMarker') { $seriesPlot->SetLinkPoints(); $seriesPlot->link->SetColor(self::$colourSet[self::$plotColour]); } elseif ($scatterStyle == 'smoothMarker') { $spline = new Spline($dataValuesY, $dataValuesX); [$splineDataY, $splineDataX] = $spline->Get(count($dataValuesX) * $this->getGraphWidth() / 20); $lplot = new LinePlot($splineDataX, $splineDataY); $lplot->SetColor(self::$colourSet[self::$plotColour]); $this->graph->Add($lplot); } if ($bubble) { $this->formatPointMarker($seriesPlot, 'dot'); $seriesPlot->mark->SetColor('black'); $seriesPlot->mark->SetSize($bubbleSize); } else { $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); $this->formatPointMarker($seriesPlot, $marker); } $seriesPlot->SetLegend($this->getDataLabel($groupID, $i)); $this->graph->Add($seriesPlot); } } private function renderPlotRadar(int $groupID): void { $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); $dataValues = []; foreach ($dataValuesY as $k => $dataValueY) { $dataValues[$k] = is_array($dataValueY) ? implode(' ', array_reverse($dataValueY)) : $dataValueY; } $tmp = array_shift($dataValues); $dataValues[] = $tmp; $tmp = array_shift($dataValuesX); $dataValuesX[] = $tmp; $this->graph->SetTitles(array_reverse($dataValues)); $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); if ($radarStyle == 'filled') { $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour]); } $this->formatPointMarker($seriesPlot, $marker); $seriesPlot->SetLegend($this->getDataLabel($groupID, $i)); $this->graph->Add($seriesPlot); } } private function renderPlotContour(int $groupID): void { $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $dataValues = []; // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $dataValues[$i] = $dataValuesX; } $seriesPlot = new ContourPlot($dataValues); $this->graph->Add($seriesPlot); } private function renderPlotStock(int $groupID): void { $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); $dataValues = []; // Loop through each data series in turn and build the plot arrays foreach ($plotOrder as $i => $v) { $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v); if ($dataValuesX === false) { continue; } $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); foreach ($dataValuesX as $j => $dataValueX) { $dataValues[$plotOrder[$i]][$j] = $dataValueX; } } if (empty($dataValues)) { return; } $dataValuesPlot = []; // Flatten the plot arrays to a single dimensional array to work with jpgraph $jMax = count($dataValues[0]); for ($j = 0; $j < $jMax; ++$j) { for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesPlot[] = $dataValues[$i][$j] ?? null; } } // Set the x-axis labels $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels); $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesPlot = new StockPlot($dataValuesPlot); $seriesPlot->SetWidth(20); $this->graph->Add($seriesPlot); } private function renderAreaChart($groupCount): void { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotLine($i, true, false); } } private function renderLineChart($groupCount): void { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotLine($i, false, false); } } private function renderBarChart($groupCount, ?string $dimensions = '2d'): void { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotBar($i, $dimensions); } } private function renderScatterChart($groupCount): void { $this->renderCartesianPlotArea('linlin'); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotScatter($i, false); } } private function renderBubbleChart($groupCount): void { $this->renderCartesianPlotArea('linlin'); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotScatter($i, true); } } private function renderPieChart($groupCount, ?string $dimensions = '2d', bool $doughnut = false, bool $multiplePlots = false): void { $this->renderPiePlotArea(); $iLimit = ($multiplePlots) ? $groupCount : 1; for ($groupID = 0; $groupID < $iLimit; ++$groupID) { $exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $datasetLabels = []; if ($groupID == 0) { $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels); } } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); // For pie charts, we only display the first series: doughnut charts generally display all series $jLimit = ($multiplePlots) ? $seriesCount : 1; // Loop through each data series in turn for ($j = 0; $j < $jLimit; ++$j) { $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; foreach ($dataValues as $k => $dataValue) { while ($k != $testCurrentIndex) { $dataValues[$testCurrentIndex] = null; ++$testCurrentIndex; } ++$testCurrentIndex; } if ($dimensions == '3d') { $seriesPlot = new PiePlot3D($dataValues); } else { if ($doughnut) { $seriesPlot = new PiePlotC($dataValues); } else { $seriesPlot = new PiePlot($dataValues); } } if ($multiplePlots) { $seriesPlot->SetSize(($jLimit - $j) / ($jLimit * 4)); } if ($doughnut && method_exists($seriesPlot, 'SetMidColor')) { $seriesPlot->SetMidColor('white'); } $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); if (count($datasetLabels) > 0) { $seriesPlot->SetLabels(array_fill(0, count($datasetLabels), '')); } if ($dimensions != '3d') { $seriesPlot->SetGuideLines(false); } if ($j == 0) { if ($exploded) { $seriesPlot->ExplodeAll(); } $seriesPlot->SetLegends($datasetLabels); } $this->graph->Add($seriesPlot); } } } private function renderRadarChart($groupCount): void { $this->renderRadarPlotArea(); for ($groupID = 0; $groupID < $groupCount; ++$groupID) { $this->renderPlotRadar($groupID); } } private function renderStockChart($groupCount): void { $this->renderCartesianPlotArea('intint'); for ($groupID = 0; $groupID < $groupCount; ++$groupID) { $this->renderPlotStock($groupID); } } private function renderContourChart($groupCount): void { $this->renderCartesianPlotArea('intint'); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotContour($i); } } private function renderCombinationChart($groupCount, $outputDestination): bool { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $dimensions = null; $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); switch ($chartType) { case 'area3DChart': case 'areaChart': $this->renderPlotLine($i, true, true); break; case 'bar3DChart': $dimensions = '3d'; // no break case 'barChart': $this->renderPlotBar($i, $dimensions); break; case 'line3DChart': case 'lineChart': $this->renderPlotLine($i, false, true); break; case 'scatterChart': $this->renderPlotScatter($i, false); break; case 'bubbleChart': $this->renderPlotScatter($i, true); break; default: $this->graph = null; return false; } } $this->renderLegend(); $this->graph->Stroke($outputDestination); return true; } public function render(?string $outputDestination): bool { self::$plotColour = 0; $groupCount = $this->chart->getPlotArea()->getPlotGroupCount(); $dimensions = null; if ($groupCount == 1) { $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { $chartType = array_pop($chartTypes); } elseif (count($chartTypes) == 0) { echo 'Chart is not yet implemented
'; return false; } else { return $this->renderCombinationChart($groupCount, $outputDestination); } } switch ($chartType) { case 'area3DChart': $dimensions = '3d'; // no break case 'areaChart': $this->renderAreaChart($groupCount); break; case 'bar3DChart': $dimensions = '3d'; // no break case 'barChart': $this->renderBarChart($groupCount, $dimensions); break; case 'line3DChart': $dimensions = '3d'; // no break case 'lineChart': $this->renderLineChart($groupCount); break; case 'pie3DChart': $dimensions = '3d'; // no break case 'pieChart': $this->renderPieChart($groupCount, $dimensions, false, false); break; case 'doughnut3DChart': $dimensions = '3d'; // no break case 'doughnutChart': $this->renderPieChart($groupCount, $dimensions, true, true); break; case 'scatterChart': $this->renderScatterChart($groupCount); break; case 'bubbleChart': $this->renderBubbleChart($groupCount); break; case 'radarChart': $this->renderRadarChart($groupCount); break; case 'surface3DChart': case 'surfaceChart': $this->renderContourChart($groupCount); break; case 'stockChart': $this->renderStockChart($groupCount); break; default: echo $chartType . ' is not yet implemented
'; return false; } $this->renderLegend(); $this->graph->Stroke($outputDestination); return true; } } ================================================ FILE: src/PhpSpreadsheet/Chart/Renderer/MtJpGraphRenderer.php ================================================ |RichText|string */ private array|RichText|string $caption; /** * Allow overlay of other elements? */ private bool $overlay = true; /** * Title Layout. */ private ?Layout $layout; private string $cellReference = ''; private ?Font $font = null; /** * Create a new Title. * * @param array|RichText|string $caption */ public function __construct(array|RichText|string $caption = '', ?Layout $layout = null, bool $overlay = false) { $this->caption = $caption; $this->layout = $layout; $this->setOverlay($overlay); } /** * Get caption. * * @return array|RichText|string */ public function getCaption(): array|RichText|string { return $this->caption; } public function getCaptionText(?Spreadsheet $spreadsheet = null): string { if ($spreadsheet !== null) { $caption = $this->getCalculatedTitle($spreadsheet); if ($caption !== null) { return $caption; } } $caption = $this->caption; if (is_string($caption)) { return $caption; } if ($caption instanceof RichText) { return $caption->getPlainText(); } $retVal = ''; foreach ($caption as $textx) { /** @var RichText|string $text */ $text = $textx; if ($text instanceof RichText) { $retVal .= $text->getPlainText(); } else { $retVal .= $text; } } return $retVal; } /** * Set caption. * * @param array|RichText|string $caption * * @return $this */ public function setCaption(array|RichText|string $caption): static { $this->caption = $caption; return $this; } /** * Get allow overlay of other elements? */ public function getOverlay(): bool { return $this->overlay; } /** * Set allow overlay of other elements? */ public function setOverlay(bool $overlay): self { $this->overlay = $overlay; return $this; } public function getLayout(): ?Layout { return $this->layout; } public function setCellReference(string $cellReference): self { $this->cellReference = $cellReference; return $this; } public function getCellReference(): string { return $this->cellReference; } public function getCalculatedTitle(?Spreadsheet $spreadsheet): ?string { preg_match(self::TITLE_CELL_REFERENCE, $this->cellReference, $matches); if (count($matches) === 0 || $spreadsheet === null) { return null; } $sheetName = preg_replace("/^'(.*)'$/", '$1', $matches[1]) ?? ''; return $spreadsheet->getSheetByName($sheetName)?->getCell($matches[2] . $matches[3])?->getFormattedValue(); } public function getFont(): ?Font { return $this->font; } public function setFont(?Font $font): self { $this->font = $font; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->layout = ($this->layout === null) ? null : clone $this->layout; $this->font = ($this->font === null) ? null : clone $this->font; if (is_array($this->caption)) { $captions = []; foreach ($this->caption as $caption) { $captions[] = is_object($caption) ? (clone $caption) : $caption; } $this->caption = $captions; } else { $this->caption = is_object($this->caption) ? (clone $this->caption) : $this->caption; } } } ================================================ FILE: src/PhpSpreadsheet/Chart/TrendLine.php ================================================ setTrendLineProperties( $trendLineType, $order, $period, $dispRSqr, $dispEq, $backward, $forward, $intercept, $name ); } public function getTrendLineType(): string { return $this->trendLineType; } public function setTrendLineType(string $trendLineType): self { $this->trendLineType = $trendLineType; return $this; } public function getOrder(): int { return $this->order; } public function setOrder(int $order): self { $this->order = $order; return $this; } public function getPeriod(): int { return $this->period; } public function setPeriod(int $period): self { $this->period = $period; return $this; } public function getDispRSqr(): bool { return $this->dispRSqr; } public function setDispRSqr(bool $dispRSqr): self { $this->dispRSqr = $dispRSqr; return $this; } public function getDispEq(): bool { return $this->dispEq; } public function setDispEq(bool $dispEq): self { $this->dispEq = $dispEq; return $this; } public function getName(): string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getBackward(): float { return $this->backward; } public function setBackward(float $backward): self { $this->backward = $backward; return $this; } public function getForward(): float { return $this->forward; } public function setForward(float $forward): self { $this->forward = $forward; return $this; } public function getIntercept(): float { return $this->intercept; } public function setIntercept(float $intercept): self { $this->intercept = $intercept; return $this; } public function setTrendLineProperties( ?string $trendLineType = null, ?int $order = 0, ?int $period = 0, ?bool $dispRSqr = false, ?bool $dispEq = false, ?float $backward = null, ?float $forward = null, ?float $intercept = null, ?string $name = null ): self { if (!empty($trendLineType)) { $this->setTrendLineType($trendLineType); } if ($order !== null) { $this->setOrder($order); } if ($period !== null) { $this->setPeriod($period); } if ($dispRSqr !== null) { $this->setDispRSqr($dispRSqr); } if ($dispEq !== null) { $this->setDispEq($dispEq); } if ($backward !== null) { $this->setBackward($backward); } if ($forward !== null) { $this->setForward($forward); } if ($intercept !== null) { $this->setIntercept($intercept); } if ($name !== null) { $this->setName($name); } return $this; } } ================================================ FILE: src/PhpSpreadsheet/Collection/Cells.php ================================================ parent = $parent; $this->cache = $cache; $this->cachePrefix = $this->getUniqueID(); } /** * Return the parent worksheet for this cell collection. */ public function getParent(): ?Worksheet { return $this->parent; } /** * Whether the collection holds a cell for the given coordinate. * * @param string $cellCoordinate Coordinate of the cell to check */ public function has(string $cellCoordinate): bool { return ($cellCoordinate === $this->currentCoordinate) || isset($this->index[$cellCoordinate]); } public function has2(string $cellCoordinate): bool { return isset($this->index[$cellCoordinate]); } /** * Add or update a cell in the collection. * * @param Cell $cell Cell to update */ public function update(Cell $cell): Cell { return $this->add($cell->getCoordinate(), $cell); } /** * Delete a cell in cache identified by coordinate. * * @param string $cellCoordinate Coordinate of the cell to delete */ public function delete(string $cellCoordinate): void { if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) { $this->currentCell->detach(); $this->currentCoordinate = null; $this->currentCell = null; $this->currentCellIsDirty = false; } unset($this->index[$cellCoordinate]); // Clear index caches $this->indexKeysCache = null; $this->indexValuesCache = null; // Delete the entry from cache $this->cache->delete($this->cachePrefix . $cellCoordinate); } /** * Get a list of all cell coordinates currently held in the collection. * * @return string[] */ public function getCoordinates(): array { // Build or rebuild index keys cache if ($this->indexKeysCache === null) { $this->indexKeysCache = array_keys($this->index); } return $this->indexKeysCache; } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @return string[] */ public function getSortedCoordinates(): array { // Sort only when required if (!$this->indexSorted) { asort($this->index); $this->indexSorted = true; // Clear unsorted cache $this->indexKeysCache = null; $this->indexValuesCache = null; } // Build or rebuild index keys cache if ($this->indexKeysCache === null) { $this->indexKeysCache = array_keys($this->index); } return $this->indexKeysCache; } /** * Get a sorted list of all cell coordinates currently held in the collection by index (16384*row+column). * * @return int[] */ public function getSortedCoordinatesInt(): array { if (!$this->indexSorted) { asort($this->index); $this->indexSorted = true; // Clear unsorted cache $this->indexKeysCache = null; $this->indexValuesCache = null; } if ($this->indexValuesCache === null) { $this->indexValuesCache = array_values($this->index); } return $this->indexValuesCache; } /** * Return the cell coordinate of the currently active cell object. */ public function getCurrentCoordinate(): ?string { return $this->currentCoordinate; } /** * Return the column coordinate of the currently active cell object. */ public function getCurrentColumn(): string { $column = 0; $row = ''; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (string) $column; } /** * Return the row coordinate of the currently active cell object. */ public function getCurrentRow(): int { $column = 0; $row = ''; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (int) $row; } /** * Get highest worksheet column and highest row that have cell records. * * @return array{row: int, column: string} Highest column name and highest row number */ public function getHighestRowAndColumn(): array { // Lookup highest column and highest row $maxRow = $maxColumn = 1; foreach ($this->index as $coordinate) { $row = (int) floor(($coordinate - 1) / AddressRange::MAX_COLUMN_INT) + 1; $maxRow = ($maxRow > $row) ? $maxRow : $row; $column = ($coordinate % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT; $maxColumn = ($maxColumn > $column) ? $maxColumn : $column; } return [ 'row' => $maxRow, 'column' => Coordinate::stringFromColumnIndex($maxColumn), ]; } /** * Get highest worksheet column. * * @param null|int|string $row Return the highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null): string { if ($row === null) { return $this->getHighestRowAndColumn()['column']; } $row = (int) $row; if ($row <= 0) { throw new PhpSpreadsheetException('Row number must be a positive integer'); } $maxColumn = 1; $toRow = $row * AddressRange::MAX_COLUMN_INT; $fromRow = --$row * AddressRange::MAX_COLUMN_INT; foreach ($this->index as $coordinate) { if ($coordinate < $fromRow || $coordinate >= $toRow) { continue; } $column = ($coordinate % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT; $maxColumn = max($column, $maxColumn); } return Coordinate::stringFromColumnIndex($maxColumn); } /** * Get highest worksheet row. * * @param null|string $column Return the highest row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow(?string $column = null): int { if ($column === null) { return $this->getHighestRowAndColumn()['row']; } $maxRow = 1; $columnIndex = Coordinate::columnIndexFromString($column); foreach ($this->index as $coordinate) { if ($coordinate % AddressRange::MAX_COLUMN_INT !== $columnIndex) { continue; } $row = (int) floor($coordinate / AddressRange::MAX_COLUMN_INT) + 1; $maxRow = ($maxRow > $row) ? $maxRow : $row; } return $maxRow; } /** * Generate a unique ID for cache referencing. * * @return string Unique Reference */ private function getUniqueID(): string { $cacheType = Settings::getCache(); return ($cacheType instanceof Memory\SimpleCache1 || $cacheType instanceof Memory\SimpleCache3) ? random_bytes(7) . ':' : uniqid('phpspreadsheet.', true) . '.'; } /** * Clone the cell collection. */ public function cloneCellCollection(Worksheet $worksheet): static { $this->storeCurrentCell(); $newCollection = clone $this; $newCollection->parent = $worksheet; $newCollection->cachePrefix = $newCollection->getUniqueID(); foreach ($this->index as $key => $value) { $newCollection->index[$key] = $value; $stored = $newCollection->cache->set( $newCollection->cachePrefix . $key, clone $this->getCache($key) ); if ($stored === false) { $this->destructIfNeeded($newCollection, 'Failed to copy cells in cache'); } } // Clear index sorted flag and index caches $newCollection->indexSorted = false; $newCollection->indexKeysCache = null; $newCollection->indexValuesCache = null; return $newCollection; } /** * Remove a row, deleting all cells in that row. * * @param int|string $row Row number to remove */ public function removeRow($row): void { $this->storeCurrentCell(); $row = (int) $row; if ($row <= 0) { throw new PhpSpreadsheetException('Row number must be a positive integer'); } $toRow = $row * AddressRange::MAX_COLUMN_INT; $fromRow = --$row * AddressRange::MAX_COLUMN_INT; foreach ($this->index as $coordinate) { if ($coordinate >= $fromRow && $coordinate < $toRow) { $row = (int) floor($coordinate / AddressRange::MAX_COLUMN_INT) + 1; $column = Coordinate::stringFromColumnIndex($coordinate % AddressRange::MAX_COLUMN_INT); $this->delete("{$column}{$row}"); } } } /** * Remove a column, deleting all cells in that column. * * @param string $column Column ID to remove */ public function removeColumn(string $column): void { $this->storeCurrentCell(); $columnIndex = Coordinate::columnIndexFromString($column); foreach ($this->index as $coordinate) { if ($coordinate % AddressRange::MAX_COLUMN_INT === $columnIndex) { $row = (int) floor($coordinate / AddressRange::MAX_COLUMN_INT) + 1; $column = Coordinate::stringFromColumnIndex($coordinate % AddressRange::MAX_COLUMN_INT); $this->delete("{$column}{$row}"); } } } /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object. */ private function storeCurrentCell(): void { if ($this->currentCellIsDirty && isset($this->currentCoordinate, $this->currentCell)) { $this->currentCell->detach(); $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell); if ($stored === false) { $this->destructIfNeeded($this, "Failed to store cell {$this->currentCoordinate} in cache"); } $this->currentCellIsDirty = false; } $this->currentCoordinate = null; $this->currentCell = null; } private function destructIfNeeded(self $cells, string $message): void { $cells->__destruct(); throw new PhpSpreadsheetException($message); } /** * Add or update a cell identified by its coordinate into the collection. * * @param string $cellCoordinate Coordinate of the cell to update * @param Cell $cell Cell to update */ public function add(string $cellCoordinate, Cell $cell): Cell { if ($cellCoordinate !== $this->currentCoordinate) { $this->storeCurrentCell(); } $column = 0; $row = ''; sscanf($cellCoordinate, '%[A-Z]%d', $column, $row); /** @var int $row */ $this->index[$cellCoordinate] = (--$row * AddressRange::MAX_COLUMN_INT) + Coordinate::columnIndexFromString((string) $column); // Clear index sorted flag and index caches $this->indexSorted = false; $this->indexKeysCache = null; $this->indexValuesCache = null; $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; $this->currentCellIsDirty = true; return $cell; } /** * Get cell at a specific coordinate. * * @param string $cellCoordinate Coordinate of the cell * * @return null|Cell Cell that was found, or null if not found */ public function get(string $cellCoordinate): ?Cell { if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell; } $this->storeCurrentCell(); // Return null if requested entry doesn't exist in collection if ($this->has($cellCoordinate) === false) { return null; } $cell = $this->getcache($cellCoordinate); // Set current entry to the requested entry $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; // Re-attach this as the cell's parent $this->currentCell->attach($this); // Return requested entry return $this->currentCell; } /** * Clear the cell collection and disconnect from our parent. */ public function unsetWorksheetCells(): void { if ($this->currentCell !== null) { $this->currentCell->detach(); $this->currentCell = null; $this->currentCoordinate = null; } // Flush the cache $this->__destruct(); $this->index = []; // Clear index sorted flag and index caches $this->indexSorted = false; $this->indexKeysCache = null; $this->indexValuesCache = null; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; } /** * Destroy this cell collection. */ public function __destruct() { $this->cache->deleteMultiple($this->getAllCacheKeys()); $this->parent = null; } /** * Returns all known cache keys. * * @return iterable */ private function getAllCacheKeys(): iterable { foreach ($this->index as $coordinate => $value) { yield $this->cachePrefix . $coordinate; } } private function getCache(string $cellCoordinate): Cell { $cell = $this->cache->get($this->cachePrefix . $cellCoordinate); if (!($cell instanceof Cell)) { throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else."); } return $cell; } } ================================================ FILE: src/PhpSpreadsheet/Collection/CellsFactory.php ================================================ cache = []; return true; } public function delete($key): bool { unset($this->cache[$key]); return true; } public function deleteMultiple($keys): bool { foreach ($keys as $key) { $this->delete($key); } return true; } public function get($key, $default = null): mixed { if ($this->has($key)) { return $this->cache[$key]; } return $default; } public function getMultiple($keys, $default = null): iterable { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } public function has($key): bool { return array_key_exists($key, $this->cache); } public function set($key, $value, $ttl = null): bool { $this->cache[$key] = $value; return true; } public function setMultiple($values, $ttl = null): bool { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } } ================================================ FILE: src/PhpSpreadsheet/Collection/Memory/SimpleCache3.php ================================================ cache = []; return true; } public function delete(string $key): bool { unset($this->cache[$key]); return true; } public function deleteMultiple(iterable $keys): bool { foreach ($keys as $key) { $this->delete($key); } return true; } public function get(string $key, mixed $default = null): mixed { if ($this->has($key)) { return $this->cache[$key]; } return $default; } public function getMultiple(iterable $keys, mixed $default = null): iterable { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } public function has(string $key): bool { return array_key_exists($key, $this->cache); } public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool { $this->cache[$key] = $value; return true; } public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } } ================================================ FILE: src/PhpSpreadsheet/Comment.php ================================================ author = 'Author'; $this->text = new RichText(); $this->fillColor = new Color('FFFFFFE1'); $this->alignment = Alignment::HORIZONTAL_GENERAL; $this->backgroundImage = new Drawing(); } /** * Get Author. */ public function getAuthor(): string { return $this->author; } /** * Set Author. */ public function setAuthor(string $author): self { $this->author = $author; return $this; } /** * Get Rich text comment. */ public function getText(): RichText { return $this->text; } /** * Set Rich text comment. */ public function setText(RichText $text): self { $this->text = $text; return $this; } /** * Get comment width (CSS style, i.e. XXpx or YYpt). */ public function getWidth(): string { return $this->width; } /** * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setWidth(string $width): self { $width = new Size($width); if ($width->valid()) { $this->width = (string) $width; } return $this; } /** * Get comment height (CSS style, i.e. XXpx or YYpt). */ public function getHeight(): string { return $this->height; } /** * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setHeight(string $height): self { $height = new Size($height); if ($height->valid()) { $this->height = (string) $height; } return $this; } /** * Get left margin (CSS style, i.e. XXpx or YYpt). */ public function getMarginLeft(): string { return $this->marginLeft; } /** * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setMarginLeft(string $margin): self { $margin = new Size($margin); if ($margin->valid()) { $this->marginLeft = (string) $margin; } return $this; } /** * Get top margin (CSS style, i.e. XXpx or YYpt). */ public function getMarginTop(): string { return $this->marginTop; } /** * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setMarginTop(string $margin): self { $margin = new Size($margin); if ($margin->valid()) { $this->marginTop = (string) $margin; } return $this; } /** * Is the comment visible by default? */ public function getVisible(): bool { return $this->visible; } /** * Set comment default visibility. */ public function setVisible(bool $visibility): self { $this->visible = $visibility; return $this; } /** * Set fill color. */ public function setFillColor(Color $color): self { $this->fillColor = $color; return $this; } /** * Get fill color. */ public function getFillColor(): Color { return $this->fillColor; } public function setAlignment(string $alignment): self { $this->alignment = $alignment; return $this; } public function getAlignment(): string { return $this->alignment; } public function setTextboxDirection(string $textboxDirection): self { $this->textboxDirection = $textboxDirection; return $this; } public function getTextboxDirection(): string { return $this->textboxDirection; } /** * Get hash code. */ public function getHashCode(): string { return md5( $this->author . $this->text->getHashCode() . $this->width . $this->height . $this->marginLeft . $this->marginTop . ($this->visible ? 1 : 0) . $this->fillColor->getHashCode() . $this->alignment . $this->textboxDirection . ($this->hasBackgroundImage() ? $this->backgroundImage->getHashCode() : '') . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** * Convert to string. */ public function __toString(): string { return $this->text->getPlainText(); } /** * Check is background image exists. */ public function hasBackgroundImage(): bool { $path = $this->backgroundImage->getPath(); if (empty($path)) { return false; } return getimagesize($path) !== false; } /** * Returns background image. */ public function getBackgroundImage(): Drawing { return $this->backgroundImage; } /** * Sets background image. */ public function setBackgroundImage(Drawing $objDrawing): self { if (!array_key_exists($objDrawing->getType(), Drawing::IMAGE_TYPES_CONVERTION_MAP)) { throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); } $this->backgroundImage = $objDrawing; return $this; } /** * Sets size of comment as size of background image. */ public function setSizeAsBackgroundImage(): self { if ($this->hasBackgroundImage()) { $this->setWidth(SharedDrawing::pixelsToPoints($this->backgroundImage->getWidth()) . 'pt'); $this->setHeight(SharedDrawing::pixelsToPoints($this->backgroundImage->getHeight()) . 'pt'); } return $this; } } ================================================ FILE: src/PhpSpreadsheet/DefinedName.php ================================================ worksheet). */ protected bool $localOnly; /** * Scope. */ protected ?Worksheet $scope; /** * Whether this is a named range or a named formula. */ protected bool $isFormula; /** * Create a new Defined Name. */ public function __construct( string $name, ?Worksheet $worksheet = null, ?string $value = null, bool $localOnly = false, ?Worksheet $scope = null ) { if ($worksheet === null) { $worksheet = $scope; } // Set local members $this->name = $name; $this->worksheet = $worksheet; $this->value = (string) $value; $this->localOnly = $localOnly; // If local only, then the scope will be set to worksheet unless a scope is explicitly set $this->scope = ($localOnly === true) ? (($scope === null) ? $worksheet : $scope) : null; // If the range string contains characters that aren't associated with the range definition (A-Z,1-9 // for cell references, and $, or the range operators (colon comma or space), quotes and ! for // worksheet names // then this is treated as a named formula, and not a named range $this->isFormula = self::testIfFormula($this->value); } public function __destruct() { $this->worksheet = null; $this->scope = null; } /** * Create a new defined name, either a range or a formula. */ public static function createInstance( string $name, ?Worksheet $worksheet = null, ?string $value = null, bool $localOnly = false, ?Worksheet $scope = null ): self { $value = (string) $value; $isFormula = self::testIfFormula($value); if ($isFormula) { return new NamedFormula($name, $worksheet, $value, $localOnly, $scope); } return new NamedRange($name, $worksheet, $value, $localOnly, $scope); } public static function testIfFormula(string $value): bool { if (str_starts_with($value, '=')) { $value = substr($value, 1); } if (is_numeric($value)) { return true; } $segMatcher = false; foreach (explode("'", $value) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) $segMatcher = $segMatcher === false; if ( $segMatcher && (preg_match('/' . self::REGEXP_IDENTIFY_FORMULA . '/miu', $subVal)) ) { return true; } } return false; } /** * Get name. */ public function getName(): string { return $this->name; } /** * Set name. */ public function setName(string $name): self { if (!empty($name)) { // Old title $oldTitle = $this->name; // Re-attach if ($this->worksheet !== null) { $this->worksheet->getParentOrThrow()->removeNamedRange($this->name, $this->worksheet); } $this->name = $name; if ($this->worksheet !== null) { $this->worksheet->getParentOrThrow()->addDefinedName($this); } if ($this->worksheet !== null) { // New title $newTitle = $this->name; ReferenceHelper::getInstance()->updateNamedFormulae($this->worksheet->getParentOrThrow(), $oldTitle, $newTitle); } } return $this; } /** * Get worksheet. */ public function getWorksheet(): ?Worksheet { return $this->worksheet; } /** * Set worksheet. */ public function setWorksheet(?Worksheet $worksheet): self { $this->worksheet = $worksheet; return $this; } /** * Get range or formula value. */ public function getValue(): string { return $this->value; } /** * Set range or formula value. */ public function setValue(string $value): self { $this->value = $value; return $this; } /** * Get localOnly. */ public function getLocalOnly(): bool { return $this->localOnly; } /** * Set localOnly. */ public function setLocalOnly(bool $localScope): self { $this->localOnly = $localScope; $this->scope = $localScope ? $this->worksheet : null; return $this; } /** * Get scope. */ public function getScope(): ?Worksheet { return $this->scope; } /** * Set scope. */ public function setScope(?Worksheet $worksheet): self { $this->scope = $worksheet; $this->localOnly = $worksheet !== null; return $this; } /** * Identify whether this is a named range or a named formula. */ public function isFormula(): bool { return $this->isFormula; } /** * Resolve a named range to a regular cell range or formula. */ public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self { if ($sheetName === '') { $worksheet2 = $worksheet; } else { $worksheet2 = $worksheet->getParentOrThrow()->getSheetByName($sheetName); if ($worksheet2 === null) { return null; } } return $worksheet->getParentOrThrow()->getDefinedName($definedName, $worksheet2); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } ================================================ FILE: src/PhpSpreadsheet/Document/Properties.php ================================================ lastModifiedBy = $this->creator; $this->created = self::intOrFloatTimestamp(null); $this->modified = $this->created; } /** * Get Creator. */ public function getCreator(): string { return $this->creator; } /** * Set Creator. * * @return $this */ public function setCreator(string $creator): self { $this->creator = $creator; return $this; } /** * Get Last Modified By. */ public function getLastModifiedBy(): string { return $this->lastModifiedBy; } /** * Set Last Modified By. * * @return $this */ public function setLastModifiedBy(string $modifiedBy): self { $this->lastModifiedBy = $modifiedBy; return $this; } private static function intOrFloatTimestamp(null|bool|float|int|string $timestamp): float|int { if ($timestamp === null || is_bool($timestamp)) { $timestamp = (float) (new DateTime())->format('U'); } elseif (is_string($timestamp)) { if (is_numeric($timestamp)) { $timestamp = (float) $timestamp; } else { $timestamp = (string) preg_replace('/[.][0-9]*$/', '', $timestamp); $timestamp = (string) preg_replace('/^(\d{4})- (\d)/', '$1-0$2', $timestamp); $timestamp = (string) preg_replace('/^(\d{4}-\d{2})- (\d)/', '$1-0$2', $timestamp); $timestamp = (float) (new DateTime($timestamp))->format('U'); } } return IntOrFloat::evaluate($timestamp); } /** * Get Created. */ public function getCreated(): float|int { return $this->created; } /** * Set Created. * * @return $this */ public function setCreated(null|float|int|string $timestamp): self { $this->created = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Modified. */ public function getModified(): float|int { return $this->modified; } /** * Set Modified. * * @return $this */ public function setModified(null|float|int|string $timestamp): self { $this->modified = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Title. */ public function getTitle(): string { return $this->title; } /** * Set Title. * * @return $this */ public function setTitle(string $title): self { $this->title = $title; return $this; } /** * Get Description. */ public function getDescription(): string { return $this->description; } /** * Set Description. * * @return $this */ public function setDescription(string $description): self { $this->description = $description; return $this; } /** * Get Subject. */ public function getSubject(): string { return $this->subject; } /** * Set Subject. * * @return $this */ public function setSubject(string $subject): self { $this->subject = $subject; return $this; } /** * Get Keywords. */ public function getKeywords(): string { return $this->keywords; } /** * Set Keywords. * * @return $this */ public function setKeywords(string $keywords): self { $this->keywords = $keywords; return $this; } /** * Get Category. */ public function getCategory(): string { return $this->category; } /** * Set Category. * * @return $this */ public function setCategory(string $category): self { $this->category = $category; return $this; } /** * Get Company. */ public function getCompany(): string { return $this->company; } /** * Set Company. * * @return $this */ public function setCompany(string $company): self { $this->company = $company; return $this; } /** * Get Manager. */ public function getManager(): string { return $this->manager; } /** * Set Manager. * * @return $this */ public function setManager(string $manager): self { $this->manager = $manager; return $this; } /** * Get a List of Custom Property Names. * * @return string[] */ public function getCustomProperties(): array { return array_keys($this->customProperties); } /** * Check if a Custom Property is defined. */ public function isCustomPropertySet(string $propertyName): bool { return array_key_exists($propertyName, $this->customProperties); } /** * Get a Custom Property Value. */ public function getCustomPropertyValue(string $propertyName): bool|int|float|string|null { if (isset($this->customProperties[$propertyName])) { return $this->customProperties[$propertyName]['value']; } return null; } /** * Get a Custom Property Type. */ public function getCustomPropertyType(string $propertyName): ?string { return $this->customProperties[$propertyName]['type'] ?? null; } private function identifyPropertyType(bool|int|float|string|null $propertyValue): string { if (is_float($propertyValue)) { return self::PROPERTY_TYPE_FLOAT; } if (is_int($propertyValue)) { return self::PROPERTY_TYPE_INTEGER; } if (is_bool($propertyValue)) { return self::PROPERTY_TYPE_BOOLEAN; } return self::PROPERTY_TYPE_STRING; } /** * Set a Custom Property. * * @param ?string $propertyType see `self::VALID_PROPERTY_TYPE_LIST` * * @return $this */ public function setCustomProperty(string $propertyName, bool|int|float|string|null $propertyValue = '', ?string $propertyType = null): self { if (($propertyType === null) || (!in_array($propertyType, self::VALID_PROPERTY_TYPE_LIST))) { $propertyType = $this->identifyPropertyType($propertyValue); } $this->customProperties[$propertyName] = [ 'value' => self::convertProperty($propertyValue, $propertyType), 'type' => $propertyType, ]; return $this; } private const PROPERTY_TYPE_ARRAY = [ 'i' => self::PROPERTY_TYPE_INTEGER, // Integer 'i1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Signed Integer 'i2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Signed Integer 'i4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Signed Integer 'i8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Signed Integer 'int' => self::PROPERTY_TYPE_INTEGER, // Integer 'ui1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Unsigned Integer 'ui2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Unsigned Integer 'ui4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Unsigned Integer 'ui8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Unsigned Integer 'uint' => self::PROPERTY_TYPE_INTEGER, // Unsigned Integer 'f' => self::PROPERTY_TYPE_FLOAT, // Real Number 'r4' => self::PROPERTY_TYPE_FLOAT, // 4-Byte Real Number 'r8' => self::PROPERTY_TYPE_FLOAT, // 8-Byte Real Number 'decimal' => self::PROPERTY_TYPE_FLOAT, // Decimal 's' => self::PROPERTY_TYPE_STRING, // String 'empty' => self::PROPERTY_TYPE_STRING, // Empty 'null' => self::PROPERTY_TYPE_STRING, // Null 'lpstr' => self::PROPERTY_TYPE_STRING, // LPSTR 'lpwstr' => self::PROPERTY_TYPE_STRING, // LPWSTR 'bstr' => self::PROPERTY_TYPE_STRING, // Basic String 'd' => self::PROPERTY_TYPE_DATE, // Date and Time 'date' => self::PROPERTY_TYPE_DATE, // Date and Time 'filetime' => self::PROPERTY_TYPE_DATE, // File Time 'b' => self::PROPERTY_TYPE_BOOLEAN, // Boolean 'bool' => self::PROPERTY_TYPE_BOOLEAN, // Boolean ]; private const SPECIAL_TYPES = [ 'empty' => '', 'null' => null, ]; /** * Convert property to form desired by Excel. */ public static function convertProperty(bool|int|float|string|null $propertyValue, string $propertyType): bool|int|float|string|null { return self::SPECIAL_TYPES[$propertyType] ?? self::convertProperty2($propertyValue, $propertyType); } /** * Convert property to form desired by Excel. */ private static function convertProperty2(bool|int|float|string|null $propertyValue, string $type): bool|int|float|string|null { $propertyType = self::convertPropertyType($type); switch ($propertyType) { case self::PROPERTY_TYPE_INTEGER: $intValue = (int) $propertyValue; return ($type[0] === 'u') ? abs($intValue) : $intValue; case self::PROPERTY_TYPE_FLOAT: return (float) $propertyValue; case self::PROPERTY_TYPE_DATE: return self::intOrFloatTimestamp($propertyValue); case self::PROPERTY_TYPE_BOOLEAN: return is_bool($propertyValue) ? $propertyValue : ($propertyValue === 'true'); default: // includes string return $propertyValue; } } public static function convertPropertyType(string $propertyType): string { return self::PROPERTY_TYPE_ARRAY[$propertyType] ?? self::PROPERTY_TYPE_UNKNOWN; } public function getHyperlinkBase(): string { return $this->hyperlinkBase; } public function setHyperlinkBase(string $hyperlinkBase): self { $this->hyperlinkBase = $hyperlinkBase; return $this; } public function getViewport(): string { return $this->viewport; } public const SUGGESTED_VIEWPORT = 'width=device-width, initial-scale=1'; public function setViewport(string $viewport): self { $this->viewport = $viewport; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Document/Security.php ================================================ lockRevision || $this->lockStructure || $this->lockWindows; } public function getLockRevision(): bool { return $this->lockRevision; } public function setLockRevision(?bool $locked): self { if ($locked !== null) { $this->lockRevision = $locked; } return $this; } public function getLockStructure(): bool { return $this->lockStructure; } public function setLockStructure(?bool $locked): self { if ($locked !== null) { $this->lockStructure = $locked; } return $this; } public function getLockWindows(): bool { return $this->lockWindows; } public function setLockWindows(?bool $locked): self { if ($locked !== null) { $this->lockWindows = $locked; } return $this; } public function getRevisionsPassword(): string { return $this->revisionsPassword; } /** * Set RevisionsPassword. * * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setRevisionsPassword(?string $password, bool $alreadyHashed = false): static { if ($password !== null) { if ($this->advancedRevisionsPassword()) { if (!$alreadyHashed) { $password = PasswordHasher::hashPassword($password, $this->revisionsAlgorithmName, $this->revisionsSaltValue, $this->revisionsSpinCount); } $this->revisionsHashValue = $password; $this->revisionsPassword = ''; } else { if (!$alreadyHashed) { $password = PasswordHasher::hashPassword($password); } $this->revisionsPassword = $password; } } return $this; } public function getWorkbookPassword(): string { return $this->workbookPassword; } /** * Set WorkbookPassword. * * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setWorkbookPassword(?string $password, bool $alreadyHashed = false): static { if ($password !== null) { if ($this->advancedPassword()) { if (!$alreadyHashed) { $password = PasswordHasher::hashPassword($password, $this->workbookAlgorithmName, $this->workbookSaltValue, $this->workbookSpinCount); } $this->workbookHashValue = $password; $this->workbookPassword = ''; } else { if (!$alreadyHashed) { $password = PasswordHasher::hashPassword($password); } $this->workbookPassword = $password; } } return $this; } public function getWorkbookHashValue(): string { return $this->advancedPassword() ? $this->workbookHashValue : ''; } public function advancedPassword(): bool { return $this->workbookAlgorithmName !== '' && $this->workbookSaltValue !== '' && $this->workbookSpinCount > 0; } public function getWorkbookAlgorithmName(): string { return $this->workbookAlgorithmName; } public function setWorkbookAlgorithmName(string $workbookAlgorithmName): static { $this->workbookAlgorithmName = $workbookAlgorithmName; return $this; } public function getWorkbookSpinCount(): int { return $this->workbookSpinCount; } public function setWorkbookSpinCount(int $workbookSpinCount): static { $this->workbookSpinCount = $workbookSpinCount; return $this; } public function getWorkbookSaltValue(): string { return $this->workbookSaltValue; } public function setWorkbookSaltValue(string $workbookSaltValue, bool $base64Required): static { $this->workbookSaltValue = $base64Required ? base64_encode($workbookSaltValue) : $workbookSaltValue; return $this; } public function getRevisionsHashValue(): string { return $this->advancedRevisionsPassword() ? $this->revisionsHashValue : ''; } public function advancedRevisionsPassword(): bool { return $this->revisionsAlgorithmName !== '' && $this->revisionsSaltValue !== '' && $this->revisionsSpinCount > 0; } public function getRevisionsAlgorithmName(): string { return $this->revisionsAlgorithmName; } public function setRevisionsAlgorithmName(string $revisionsAlgorithmName): static { $this->revisionsAlgorithmName = $revisionsAlgorithmName; return $this; } public function getRevisionsSpinCount(): int { return $this->revisionsSpinCount; } public function setRevisionsSpinCount(int $revisionsSpinCount): static { $this->revisionsSpinCount = $revisionsSpinCount; return $this; } public function getRevisionsSaltValue(): string { return $this->revisionsSaltValue; } public function setRevisionsSaltValue(string $revisionsSaltValue, bool $base64Required): static { $this->revisionsSaltValue = $base64Required ? base64_encode($revisionsSaltValue) : $revisionsSaltValue; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Exception.php ================================================ */ protected array $items = []; /** * HashTable key map. * * @var array */ protected array $keyMap = []; /** * Create a new HashTable. * * @param T[] $source Optional source array to create HashTable from */ public function __construct(?array $source = []) { if ($source !== null) { // Create HashTable $this->addFromSource($source); } } /** * Add HashTable items from source. * * @param T[] $source Source array to create HashTable from */ public function addFromSource(?array $source = null): void { // Check if an array was passed if ($source === null) { return; } foreach ($source as $item) { $this->add($item); } } /** * Add HashTable item. * * @param T $source Item to add */ public function add(IComparable $source): void { $hash = $source->getHashCode(); if (!isset($this->items[$hash])) { $this->items[$hash] = $source; $this->keyMap[count($this->items) - 1] = $hash; } } /** * Remove HashTable item. * * @param T $source Item to remove */ public function remove(IComparable $source): void { $hash = $source->getHashCode(); if (isset($this->items[$hash])) { unset($this->items[$hash]); $deleteKey = -1; foreach ($this->keyMap as $key => $value) { if ($deleteKey >= 0) { $this->keyMap[$key - 1] = $value; } if ($value == $hash) { $deleteKey = $key; } } unset($this->keyMap[count($this->keyMap) - 1]); } } /** * Clear HashTable. */ public function clear(): void { $this->items = []; $this->keyMap = []; } /** * Count. */ public function count(): int { return count($this->items); } /** * Get index for hash code. */ public function getIndexForHashCode(string $hashCode): false|int { return array_search($hashCode, $this->keyMap, true); } /** * Get by index. * * @return null|T */ public function getByIndex(int $index): ?IComparable { if (isset($this->keyMap[$index])) { return $this->getByHashCode($this->keyMap[$index]); } return null; } /** * Get by hashcode. * * @return null|T */ public function getByHashCode(string $hashCode): ?IComparable { if (isset($this->items[$hashCode])) { return $this->items[$hashCode]; } return null; } /** * HashTable to array. * * @return T[] */ public function toArray(): array { return $this->items; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { // each member of this class is an array if (is_array($value)) { $array1 = $value; foreach ($array1 as $key1 => $value1) { if (is_object($value1)) { $array1[$key1] = clone $value1; } } $this->$key = $array1; } } } } ================================================ FILE: src/PhpSpreadsheet/Helper/Dimension.php ================================================ 96.0 / 2.54, self::UOM_MILLIMETERS => 96.0 / 25.4, self::UOM_INCHES => 96.0, self::UOM_PIXELS => 1.0, self::UOM_POINTS => 96.0 / 72, self::UOM_PICA => 96.0 * 12 / 72, ]; /** * Based on a standard column width of 8.54 units in MS Excel. */ const RELATIVE_UNITS = [ 'em' => 10.0 / 8.54, 'ex' => 10.0 / 8.54, 'ch' => 10.0 / 8.54, 'rem' => 10.0 / 8.54, 'vw' => 8.54, 'vh' => 8.54, 'vmin' => 8.54, 'vmax' => 8.54, '%' => 8.54 / 100, ]; /** * @var float|int If this is a width, then size is measured in pixels (if is set) * or in Excel's default column width units if $unit is null. * If this is a height, then size is measured in pixels () * or in points () if $unit is null. */ protected float|int $size; protected ?string $unit = null; public function __construct(string $dimension) { $size = 0.0; $unit = ''; $sscanf = sscanf($dimension, '%[1234567890.]%s'); if (is_array($sscanf)) { $size = (float) ($sscanf[0] ?? 0.0); $unit = strtolower($sscanf[1] ?? ''); } // If a UoM is specified, then convert the size to pixels for internal storage if (isset(self::ABSOLUTE_UNITS[$unit])) { $size *= self::ABSOLUTE_UNITS[$unit]; $this->unit = self::UOM_PIXELS; } elseif (isset(self::RELATIVE_UNITS[$unit])) { $size *= self::RELATIVE_UNITS[$unit]; $size = round($size, 4); } $this->size = $size; } public function width(): float { return (float) ($this->unit === null) ? $this->size : round(Drawing::pixelsToCellDimension((int) $this->size, new Font(false)), 4); } public function height(): float { return (float) ($this->unit === null) ? $this->size : $this->toUnit(self::UOM_POINTS); } public function toUnit(string $unitOfMeasure): float { $unitOfMeasure = strtolower($unitOfMeasure); if (!array_key_exists($unitOfMeasure, self::ABSOLUTE_UNITS)) { throw new Exception("{$unitOfMeasure} is not a vaid unit of measure"); } $size = $this->size; if ($this->unit === null) { $size = Drawing::cellDimensionToPixels($size, new Font(false)); } return $size / self::ABSOLUTE_UNITS[$unitOfMeasure]; } } ================================================ FILE: src/PhpSpreadsheet/Helper/Downloader.php ================================================ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xls' => 'application/vnd.ms-excel', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'csv' => 'text/csv', 'html' => 'text/html', 'pdf' => 'application/pdf', ]; public function __construct(string $folder, string $filename, ?string $filetype = null) { if ((is_dir($folder) === false) || (is_readable($folder) === false)) { throw new Exception('Folder is not accessible'); } $filepath = "{$folder}/{$filename}"; $this->filepath = (string) realpath($filepath); $this->filename = basename($filepath); clearstatcache(); if ((is_file($this->filepath) === false) || (is_readable($this->filepath) === false)) { throw new Exception('File not found, or not a regular file, or cannot be read'); } $filetype ??= pathinfo($filename, PATHINFO_EXTENSION); if (array_key_exists(strtolower($filetype), self::CONTENT_TYPES) === false) { throw new Exception('Invalid filetype: file cannot be downloaded'); } $this->filetype = strtolower($filetype); } public function download(): void { $this->headers(); readfile($this->filepath); } public function headers(): void { // I cannot tell what this ob_clean is paired with. // I have never seen a problem with it, but someone has - issue 3739. // Perhaps it should be removed altogether, // but making it conditional seems harmless, and safer. if ((int) ob_get_length() > 0) { ob_clean(); } $this->contentType(); $this->contentDisposition(); $this->cacheHeaders(); $this->fileSize(); flush(); } protected function contentType(): void { header('Content-Type: ' . self::CONTENT_TYPES[$this->filetype]); } protected function contentDisposition(): void { header('Content-Disposition: attachment;filename="' . $this->filename . '"'); } protected function cacheHeaders(): void { header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past $dt = new DateTimeImmutable(timezone: new DateTimeZone('UTC')); header('Last-Modified: ' . $dt->format('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 } protected function fileSize(): void { header('Content-Length: ' . filesize($this->filepath)); } } ================================================ FILE: src/PhpSpreadsheet/Helper/Handler.php ================================================ 'f0f8ff', 'antiquewhite' => 'faebd7', 'antiquewhite1' => 'ffefdb', 'antiquewhite2' => 'eedfcc', 'antiquewhite3' => 'cdc0b0', 'antiquewhite4' => '8b8378', 'aqua' => '00ffff', 'aquamarine1' => '7fffd4', 'aquamarine2' => '76eec6', 'aquamarine4' => '458b74', 'azure1' => 'f0ffff', 'azure2' => 'e0eeee', 'azure3' => 'c1cdcd', 'azure4' => '838b8b', 'beige' => 'f5f5dc', 'bisque1' => 'ffe4c4', 'bisque2' => 'eed5b7', 'bisque3' => 'cdb79e', 'bisque4' => '8b7d6b', 'black' => '000000', 'blanchedalmond' => 'ffebcd', 'blue' => '0000ff', 'blue1' => '0000ff', 'blue2' => '0000ee', 'blue4' => '00008b', 'blueviolet' => '8a2be2', 'brown' => 'a52a2a', 'brown1' => 'ff4040', 'brown2' => 'ee3b3b', 'brown3' => 'cd3333', 'brown4' => '8b2323', 'burlywood' => 'deb887', 'burlywood1' => 'ffd39b', 'burlywood2' => 'eec591', 'burlywood3' => 'cdaa7d', 'burlywood4' => '8b7355', 'cadetblue' => '5f9ea0', 'cadetblue1' => '98f5ff', 'cadetblue2' => '8ee5ee', 'cadetblue3' => '7ac5cd', 'cadetblue4' => '53868b', 'chartreuse1' => '7fff00', 'chartreuse2' => '76ee00', 'chartreuse3' => '66cd00', 'chartreuse4' => '458b00', 'chocolate' => 'd2691e', 'chocolate1' => 'ff7f24', 'chocolate2' => 'ee7621', 'chocolate3' => 'cd661d', 'coral' => 'ff7f50', 'coral1' => 'ff7256', 'coral2' => 'ee6a50', 'coral3' => 'cd5b45', 'coral4' => '8b3e2f', 'cornflowerblue' => '6495ed', 'cornsilk1' => 'fff8dc', 'cornsilk2' => 'eee8cd', 'cornsilk3' => 'cdc8b1', 'cornsilk4' => '8b8878', 'cyan1' => '00ffff', 'cyan2' => '00eeee', 'cyan3' => '00cdcd', 'cyan4' => '008b8b', 'darkgoldenrod' => 'b8860b', 'darkgoldenrod1' => 'ffb90f', 'darkgoldenrod2' => 'eead0e', 'darkgoldenrod3' => 'cd950c', 'darkgoldenrod4' => '8b6508', 'darkgreen' => '006400', 'darkkhaki' => 'bdb76b', 'darkolivegreen' => '556b2f', 'darkolivegreen1' => 'caff70', 'darkolivegreen2' => 'bcee68', 'darkolivegreen3' => 'a2cd5a', 'darkolivegreen4' => '6e8b3d', 'darkorange' => 'ff8c00', 'darkorange1' => 'ff7f00', 'darkorange2' => 'ee7600', 'darkorange3' => 'cd6600', 'darkorange4' => '8b4500', 'darkorchid' => '9932cc', 'darkorchid1' => 'bf3eff', 'darkorchid2' => 'b23aee', 'darkorchid3' => '9a32cd', 'darkorchid4' => '68228b', 'darksalmon' => 'e9967a', 'darkseagreen' => '8fbc8f', 'darkseagreen1' => 'c1ffc1', 'darkseagreen2' => 'b4eeb4', 'darkseagreen3' => '9bcd9b', 'darkseagreen4' => '698b69', 'darkslateblue' => '483d8b', 'darkslategray' => '2f4f4f', 'darkslategray1' => '97ffff', 'darkslategray2' => '8deeee', 'darkslategray3' => '79cdcd', 'darkslategray4' => '528b8b', 'darkturquoise' => '00ced1', 'darkviolet' => '9400d3', 'deeppink1' => 'ff1493', 'deeppink2' => 'ee1289', 'deeppink3' => 'cd1076', 'deeppink4' => '8b0a50', 'deepskyblue1' => '00bfff', 'deepskyblue2' => '00b2ee', 'deepskyblue3' => '009acd', 'deepskyblue4' => '00688b', 'dimgray' => '696969', 'dodgerblue1' => '1e90ff', 'dodgerblue2' => '1c86ee', 'dodgerblue3' => '1874cd', 'dodgerblue4' => '104e8b', 'firebrick' => 'b22222', 'firebrick1' => 'ff3030', 'firebrick2' => 'ee2c2c', 'firebrick3' => 'cd2626', 'firebrick4' => '8b1a1a', 'floralwhite' => 'fffaf0', 'forestgreen' => '228b22', 'fuchsia' => 'ff00ff', 'gainsboro' => 'dcdcdc', 'ghostwhite' => 'f8f8ff', 'gold1' => 'ffd700', 'gold2' => 'eec900', 'gold3' => 'cdad00', 'gold4' => '8b7500', 'goldenrod' => 'daa520', 'goldenrod1' => 'ffc125', 'goldenrod2' => 'eeb422', 'goldenrod3' => 'cd9b1d', 'goldenrod4' => '8b6914', 'gray' => 'bebebe', 'gray1' => '030303', 'gray10' => '1a1a1a', 'gray11' => '1c1c1c', 'gray12' => '1f1f1f', 'gray13' => '212121', 'gray14' => '242424', 'gray15' => '262626', 'gray16' => '292929', 'gray17' => '2b2b2b', 'gray18' => '2e2e2e', 'gray19' => '303030', 'gray2' => '050505', 'gray20' => '333333', 'gray21' => '363636', 'gray22' => '383838', 'gray23' => '3b3b3b', 'gray24' => '3d3d3d', 'gray25' => '404040', 'gray26' => '424242', 'gray27' => '454545', 'gray28' => '474747', 'gray29' => '4a4a4a', 'gray3' => '080808', 'gray30' => '4d4d4d', 'gray31' => '4f4f4f', 'gray32' => '525252', 'gray33' => '545454', 'gray34' => '575757', 'gray35' => '595959', 'gray36' => '5c5c5c', 'gray37' => '5e5e5e', 'gray38' => '616161', 'gray39' => '636363', 'gray4' => '0a0a0a', 'gray40' => '666666', 'gray41' => '696969', 'gray42' => '6b6b6b', 'gray43' => '6e6e6e', 'gray44' => '707070', 'gray45' => '737373', 'gray46' => '757575', 'gray47' => '787878', 'gray48' => '7a7a7a', 'gray49' => '7d7d7d', 'gray5' => '0d0d0d', 'gray50' => '7f7f7f', 'gray51' => '828282', 'gray52' => '858585', 'gray53' => '878787', 'gray54' => '8a8a8a', 'gray55' => '8c8c8c', 'gray56' => '8f8f8f', 'gray57' => '919191', 'gray58' => '949494', 'gray59' => '969696', 'gray6' => '0f0f0f', 'gray60' => '999999', 'gray61' => '9c9c9c', 'gray62' => '9e9e9e', 'gray63' => 'a1a1a1', 'gray64' => 'a3a3a3', 'gray65' => 'a6a6a6', 'gray66' => 'a8a8a8', 'gray67' => 'ababab', 'gray68' => 'adadad', 'gray69' => 'b0b0b0', 'gray7' => '121212', 'gray70' => 'b3b3b3', 'gray71' => 'b5b5b5', 'gray72' => 'b8b8b8', 'gray73' => 'bababa', 'gray74' => 'bdbdbd', 'gray75' => 'bfbfbf', 'gray76' => 'c2c2c2', 'gray77' => 'c4c4c4', 'gray78' => 'c7c7c7', 'gray79' => 'c9c9c9', 'gray8' => '141414', 'gray80' => 'cccccc', 'gray81' => 'cfcfcf', 'gray82' => 'd1d1d1', 'gray83' => 'd4d4d4', 'gray84' => 'd6d6d6', 'gray85' => 'd9d9d9', 'gray86' => 'dbdbdb', 'gray87' => 'dedede', 'gray88' => 'e0e0e0', 'gray89' => 'e3e3e3', 'gray9' => '171717', 'gray90' => 'e5e5e5', 'gray91' => 'e8e8e8', 'gray92' => 'ebebeb', 'gray93' => 'ededed', 'gray94' => 'f0f0f0', 'gray95' => 'f2f2f2', 'gray97' => 'f7f7f7', 'gray98' => 'fafafa', 'gray99' => 'fcfcfc', 'green' => '00ff00', 'green1' => '00ff00', 'green2' => '00ee00', 'green3' => '00cd00', 'green4' => '008b00', 'greenyellow' => 'adff2f', 'honeydew1' => 'f0fff0', 'honeydew2' => 'e0eee0', 'honeydew3' => 'c1cdc1', 'honeydew4' => '838b83', 'hotpink' => 'ff69b4', 'hotpink1' => 'ff6eb4', 'hotpink2' => 'ee6aa7', 'hotpink3' => 'cd6090', 'hotpink4' => '8b3a62', 'indianred' => 'cd5c5c', 'indianred1' => 'ff6a6a', 'indianred2' => 'ee6363', 'indianred3' => 'cd5555', 'indianred4' => '8b3a3a', 'ivory1' => 'fffff0', 'ivory2' => 'eeeee0', 'ivory3' => 'cdcdc1', 'ivory4' => '8b8b83', 'khaki' => 'f0e68c', 'khaki1' => 'fff68f', 'khaki2' => 'eee685', 'khaki3' => 'cdc673', 'khaki4' => '8b864e', 'lavender' => 'e6e6fa', 'lavenderblush1' => 'fff0f5', 'lavenderblush2' => 'eee0e5', 'lavenderblush3' => 'cdc1c5', 'lavenderblush4' => '8b8386', 'lawngreen' => '7cfc00', 'lemonchiffon1' => 'fffacd', 'lemonchiffon2' => 'eee9bf', 'lemonchiffon3' => 'cdc9a5', 'lemonchiffon4' => '8b8970', 'light' => 'eedd82', 'lightblue' => 'add8e6', 'lightblue1' => 'bfefff', 'lightblue2' => 'b2dfee', 'lightblue3' => '9ac0cd', 'lightblue4' => '68838b', 'lightcoral' => 'f08080', 'lightcyan1' => 'e0ffff', 'lightcyan2' => 'd1eeee', 'lightcyan3' => 'b4cdcd', 'lightcyan4' => '7a8b8b', 'lightgoldenrod1' => 'ffec8b', 'lightgoldenrod2' => 'eedc82', 'lightgoldenrod3' => 'cdbe70', 'lightgoldenrod4' => '8b814c', 'lightgoldenrodyellow' => 'fafad2', 'lightgray' => 'd3d3d3', 'lightpink' => 'ffb6c1', 'lightpink1' => 'ffaeb9', 'lightpink2' => 'eea2ad', 'lightpink3' => 'cd8c95', 'lightpink4' => '8b5f65', 'lightsalmon1' => 'ffa07a', 'lightsalmon2' => 'ee9572', 'lightsalmon3' => 'cd8162', 'lightsalmon4' => '8b5742', 'lightseagreen' => '20b2aa', 'lightskyblue' => '87cefa', 'lightskyblue1' => 'b0e2ff', 'lightskyblue2' => 'a4d3ee', 'lightskyblue3' => '8db6cd', 'lightskyblue4' => '607b8b', 'lightslateblue' => '8470ff', 'lightslategray' => '778899', 'lightsteelblue' => 'b0c4de', 'lightsteelblue1' => 'cae1ff', 'lightsteelblue2' => 'bcd2ee', 'lightsteelblue3' => 'a2b5cd', 'lightsteelblue4' => '6e7b8b', 'lightyellow1' => 'ffffe0', 'lightyellow2' => 'eeeed1', 'lightyellow3' => 'cdcdb4', 'lightyellow4' => '8b8b7a', 'lime' => '00ff00', 'limegreen' => '32cd32', 'linen' => 'faf0e6', 'magenta' => 'ff00ff', 'magenta2' => 'ee00ee', 'magenta3' => 'cd00cd', 'magenta4' => '8b008b', 'maroon' => 'b03060', 'maroon1' => 'ff34b3', 'maroon2' => 'ee30a7', 'maroon3' => 'cd2990', 'maroon4' => '8b1c62', 'medium' => '66cdaa', 'mediumaquamarine' => '66cdaa', 'mediumblue' => '0000cd', 'mediumorchid' => 'ba55d3', 'mediumorchid1' => 'e066ff', 'mediumorchid2' => 'd15fee', 'mediumorchid3' => 'b452cd', 'mediumorchid4' => '7a378b', 'mediumpurple' => '9370db', 'mediumpurple1' => 'ab82ff', 'mediumpurple2' => '9f79ee', 'mediumpurple3' => '8968cd', 'mediumpurple4' => '5d478b', 'mediumseagreen' => '3cb371', 'mediumslateblue' => '7b68ee', 'mediumspringgreen' => '00fa9a', 'mediumturquoise' => '48d1cc', 'mediumvioletred' => 'c71585', 'midnightblue' => '191970', 'mintcream' => 'f5fffa', 'mistyrose1' => 'ffe4e1', 'mistyrose2' => 'eed5d2', 'mistyrose3' => 'cdb7b5', 'mistyrose4' => '8b7d7b', 'moccasin' => 'ffe4b5', 'navajowhite1' => 'ffdead', 'navajowhite2' => 'eecfa1', 'navajowhite3' => 'cdb38b', 'navajowhite4' => '8b795e', 'navy' => '000080', 'navyblue' => '000080', 'oldlace' => 'fdf5e6', 'olive' => '808000', 'olivedrab' => '6b8e23', 'olivedrab1' => 'c0ff3e', 'olivedrab2' => 'b3ee3a', 'olivedrab4' => '698b22', 'orange' => 'ffa500', 'orange1' => 'ffa500', 'orange2' => 'ee9a00', 'orange3' => 'cd8500', 'orange4' => '8b5a00', 'orangered1' => 'ff4500', 'orangered2' => 'ee4000', 'orangered3' => 'cd3700', 'orangered4' => '8b2500', 'orchid' => 'da70d6', 'orchid1' => 'ff83fa', 'orchid2' => 'ee7ae9', 'orchid3' => 'cd69c9', 'orchid4' => '8b4789', 'pale' => 'db7093', 'palegoldenrod' => 'eee8aa', 'palegreen' => '98fb98', 'palegreen1' => '9aff9a', 'palegreen2' => '90ee90', 'palegreen3' => '7ccd7c', 'palegreen4' => '548b54', 'paleturquoise' => 'afeeee', 'paleturquoise1' => 'bbffff', 'paleturquoise2' => 'aeeeee', 'paleturquoise3' => '96cdcd', 'paleturquoise4' => '668b8b', 'palevioletred' => 'db7093', 'palevioletred1' => 'ff82ab', 'palevioletred2' => 'ee799f', 'palevioletred3' => 'cd6889', 'palevioletred4' => '8b475d', 'papayawhip' => 'ffefd5', 'peachpuff1' => 'ffdab9', 'peachpuff2' => 'eecbad', 'peachpuff3' => 'cdaf95', 'peachpuff4' => '8b7765', 'pink' => 'ffc0cb', 'pink1' => 'ffb5c5', 'pink2' => 'eea9b8', 'pink3' => 'cd919e', 'pink4' => '8b636c', 'plum' => 'dda0dd', 'plum1' => 'ffbbff', 'plum2' => 'eeaeee', 'plum3' => 'cd96cd', 'plum4' => '8b668b', 'powderblue' => 'b0e0e6', 'purple' => 'a020f0', 'rebeccapurple' => '663399', 'purple1' => '9b30ff', 'purple2' => '912cee', 'purple3' => '7d26cd', 'purple4' => '551a8b', 'red' => 'ff0000', 'red1' => 'ff0000', 'red2' => 'ee0000', 'red3' => 'cd0000', 'red4' => '8b0000', 'rosybrown' => 'bc8f8f', 'rosybrown1' => 'ffc1c1', 'rosybrown2' => 'eeb4b4', 'rosybrown3' => 'cd9b9b', 'rosybrown4' => '8b6969', 'royalblue' => '4169e1', 'royalblue1' => '4876ff', 'royalblue2' => '436eee', 'royalblue3' => '3a5fcd', 'royalblue4' => '27408b', 'saddlebrown' => '8b4513', 'salmon' => 'fa8072', 'salmon1' => 'ff8c69', 'salmon2' => 'ee8262', 'salmon3' => 'cd7054', 'salmon4' => '8b4c39', 'sandybrown' => 'f4a460', 'seagreen1' => '54ff9f', 'seagreen2' => '4eee94', 'seagreen3' => '43cd80', 'seagreen4' => '2e8b57', 'seashell1' => 'fff5ee', 'seashell2' => 'eee5de', 'seashell3' => 'cdc5bf', 'seashell4' => '8b8682', 'sienna' => 'a0522d', 'sienna1' => 'ff8247', 'sienna2' => 'ee7942', 'sienna3' => 'cd6839', 'sienna4' => '8b4726', 'silver' => 'c0c0c0', 'skyblue' => '87ceeb', 'skyblue1' => '87ceff', 'skyblue2' => '7ec0ee', 'skyblue3' => '6ca6cd', 'skyblue4' => '4a708b', 'slateblue' => '6a5acd', 'slateblue1' => '836fff', 'slateblue2' => '7a67ee', 'slateblue3' => '6959cd', 'slateblue4' => '473c8b', 'slategray' => '708090', 'slategray1' => 'c6e2ff', 'slategray2' => 'b9d3ee', 'slategray3' => '9fb6cd', 'slategray4' => '6c7b8b', 'snow1' => 'fffafa', 'snow2' => 'eee9e9', 'snow3' => 'cdc9c9', 'snow4' => '8b8989', 'springgreen1' => '00ff7f', 'springgreen2' => '00ee76', 'springgreen3' => '00cd66', 'springgreen4' => '008b45', 'steelblue' => '4682b4', 'steelblue1' => '63b8ff', 'steelblue2' => '5cacee', 'steelblue3' => '4f94cd', 'steelblue4' => '36648b', 'tan' => 'd2b48c', 'tan1' => 'ffa54f', 'tan2' => 'ee9a49', 'tan3' => 'cd853f', 'tan4' => '8b5a2b', 'teal' => '008080', 'thistle' => 'd8bfd8', 'thistle1' => 'ffe1ff', 'thistle2' => 'eed2ee', 'thistle3' => 'cdb5cd', 'thistle4' => '8b7b8b', 'tomato1' => 'ff6347', 'tomato2' => 'ee5c42', 'tomato3' => 'cd4f39', 'tomato4' => '8b3626', 'turquoise' => '40e0d0', 'turquoise1' => '00f5ff', 'turquoise2' => '00e5ee', 'turquoise3' => '00c5cd', 'turquoise4' => '00868b', 'violet' => 'ee82ee', 'violetred' => 'd02090', 'violetred1' => 'ff3e96', 'violetred2' => 'ee3a8c', 'violetred3' => 'cd3278', 'violetred4' => '8b2252', 'wheat' => 'f5deb3', 'wheat1' => 'ffe7ba', 'wheat2' => 'eed8ae', 'wheat3' => 'cdba96', 'wheat4' => '8b7e66', 'white' => 'ffffff', 'whitesmoke' => 'f5f5f5', 'yellow' => 'ffff00', 'yellow1' => 'ffff00', 'yellow2' => 'eeee00', 'yellow3' => 'cdcd00', 'yellow4' => '8b8b00', 'yellowgreen' => '9acd32', ]; private ?string $face = null; private ?string $size = null; private ?string $color = null; private bool $bold = false; private bool $italic = false; private bool $underline = false; private bool $superscript = false; private bool $subscript = false; private bool $strikethrough = false; /** @var callable[] */ protected array $startTagCallbacks; /** @var callable[] */ protected array $endTagCallbacks; /** @var mixed[] */ private array $stack = []; public string $stringData = ''; private RichText $richTextObject; private bool $preserveWhiteSpace = false; public function __construct() { if (!isset($this->startTagCallbacks)) { $this->startTagCallbacks = [ 'font' => $this->startFontTag(...), 'b' => $this->startBoldTag(...), 'strong' => $this->startBoldTag(...), 'i' => $this->startItalicTag(...), 'em' => $this->startItalicTag(...), 'u' => $this->startUnderlineTag(...), 'ins' => $this->startUnderlineTag(...), 'del' => $this->startStrikethruTag(...), 's' => $this->startStrikethruTag(...), 'sup' => $this->startSuperscriptTag(...), 'sub' => $this->startSubscriptTag(...), ]; } if (!isset($this->endTagCallbacks)) { $this->endTagCallbacks = [ 'font' => $this->endFontTag(...), 'b' => $this->endBoldTag(...), 'strong' => $this->endBoldTag(...), 'i' => $this->endItalicTag(...), 'em' => $this->endItalicTag(...), 'u' => $this->endUnderlineTag(...), 'ins' => $this->endUnderlineTag(...), 'del' => $this->endStrikethruTag(...), 's' => $this->endStrikethruTag(...), 'sup' => $this->endSuperscriptTag(...), 'sub' => $this->endSubscriptTag(...), 'br' => $this->breakTag(...), 'p' => $this->breakTag(...), 'h1' => $this->breakTag(...), 'h2' => $this->breakTag(...), 'h3' => $this->breakTag(...), 'h4' => $this->breakTag(...), 'h5' => $this->breakTag(...), 'h6' => $this->breakTag(...), ]; } } private function initialise(): void { $this->face = $this->size = $this->color = null; $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; $this->stack = []; $this->stringData = ''; } /** * Parse HTML formatting and return the resulting RichText. */ public function toRichTextObject(string $html, bool $preserveWhiteSpace = false): RichText { $this->initialise(); // Create a new DOM object $dom = new DOMDocument(); // Load the HTML file into the DOM object // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup $prefix = ''; @$dom->loadHTML($prefix . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // Discard excess white space $dom->preserveWhiteSpace = false; $this->richTextObject = new RichText(); $this->preserveWhiteSpace = $preserveWhiteSpace; $this->parseElements($dom); $this->preserveWhiteSpace = false; // Clean any further spurious whitespace $this->cleanWhitespace(); return $this->richTextObject; } private function cleanWhitespace(): void { foreach ($this->richTextObject->getRichTextElements() as $key => $element) { $text = $element->getText(); // Trim any leading spaces on the first run if ($key == 0) { $text = ltrim($text); } // Trim any spaces immediately after a line break $text = (string) preg_replace('/\n */mu', "\n", $text); $element->setText($text); } } private function buildTextRun(): void { $text = $this->stringData; if (trim($text) === '') { return; } $richtextRun = $this->richTextObject->createTextRun($this->stringData); $font = $richtextRun->getFont(); if ($font !== null) { if ($this->face) { $font->setName($this->face); } if ($this->size) { $font->setSize($this->size); } if ($this->color) { $font->setColor(new Color('ff' . $this->color)); } if ($this->bold) { $font->setBold(true); } if ($this->italic) { $font->setItalic(true); } if ($this->underline) { $font->setUnderline(Font::UNDERLINE_SINGLE); } if ($this->superscript) { $font->setSuperscript(true); } if ($this->subscript) { $font->setSubscript(true); } if ($this->strikethrough) { $font->setStrikethrough(true); } } $this->stringData = ''; } private function rgbToColour(string $rgbValue): string { preg_match_all('/\d+/', $rgbValue, $values); foreach ($values[0] as &$value) { $value = str_pad(dechex((int) $value), 2, '0', STR_PAD_LEFT); } return implode('', $values[0]); } public static function colourNameLookup(string $colorName): string { /** @var string[] */ $temp = static::COLOUR_MAP; return $temp[$colorName] ?? ''; } protected function startFontTag(DOMElement $tag): void { $attrs = $tag->attributes ?? []; /** @var DOMAttr $attribute */ foreach ($attrs as $attribute) { $attributeName = strtolower($attribute->name); $attributeName = preg_replace('/^html:/', '', $attributeName) ?? $attributeName; // in case from Xml spreadsheet $attributeValue = $attribute->value; if ($attributeName === 'color') { if (preg_match('/rgb\s*\(/', $attributeValue)) { $this->$attributeName = $this->rgbToColour($attributeValue); } elseif (str_starts_with(trim($attributeValue), '#')) { $this->$attributeName = ltrim($attributeValue, '#'); } else { $this->$attributeName = static::colourNameLookup($attributeValue); } } elseif ($attributeName === 'face' || $attributeName === 'size') { $this->$attributeName = $attributeValue; } } } protected function endFontTag(): void { $this->face = $this->size = $this->color = null; } protected function startBoldTag(): void { $this->bold = true; } protected function endBoldTag(): void { $this->bold = false; } protected function startItalicTag(): void { $this->italic = true; } protected function endItalicTag(): void { $this->italic = false; } protected function startUnderlineTag(): void { $this->underline = true; } protected function endUnderlineTag(): void { $this->underline = false; } protected function startSubscriptTag(): void { $this->subscript = true; } protected function endSubscriptTag(): void { $this->subscript = false; } protected function startSuperscriptTag(): void { $this->superscript = true; } protected function endSuperscriptTag(): void { $this->superscript = false; } protected function startStrikethruTag(): void { $this->strikethrough = true; } protected function endStrikethruTag(): void { $this->strikethrough = false; } public function breakTag(): void { $this->stringData .= "\n"; } private function parseTextNode(DOMText $textNode): void { if ($this->preserveWhiteSpace) { $domText = $textNode->nodeValue ?? ''; } else { $domText = (string) preg_replace( '/\s+/u', ' ', str_replace(["\r", "\n"], ' ', $textNode->nodeValue ?? '') ); } $this->stringData .= $domText; $this->buildTextRun(); } public function addStartTagCallback(string $tag, callable $callback): void { $this->startTagCallbacks[$tag] = $callback; } public function addEndTagCallback(string $tag, callable $callback): void { $this->endTagCallbacks[$tag] = $callback; } /** @param callable[] $callbacks */ private function handleCallback(DOMElement $element, string $callbackTag, array $callbacks): void { if (isset($callbacks[$callbackTag])) { $elementHandler = $callbacks[$callbackTag]; call_user_func($elementHandler, $element, $this); } } private function parseElementNode(DOMElement $element): void { $callbackTag = strtolower($element->nodeName); $this->stack[] = $callbackTag; $this->handleCallback($element, $callbackTag, $this->startTagCallbacks); $this->parseElements($element); array_pop($this->stack); $this->handleCallback($element, $callbackTag, $this->endTagCallbacks); } private function parseElements(DOMNode $element): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { $this->parseTextNode($child); } elseif ($child instanceof DOMElement) { $this->parseElementNode($child); } } } } ================================================ FILE: src/PhpSpreadsheet/Helper/Sample.php ================================================ getScriptFilename() === 'index'; } /** * Return the page title. */ public function getPageTitle(): string { return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename(); } /** * Return the page heading. */ public function getPageHeading(): string { return $this->isIndex() ? '' : '

' . str_replace('_', ' ', $this->getScriptFilename()) . '

'; } /** * Returns an array of all known samples. * * @return string[][] [$name => $path] */ public function getSamples(): array { // Populate samples $baseDir = realpath(__DIR__ . '/../../../samples'); if ($baseDir === false) { // @codeCoverageIgnoreStart throw new RuntimeException('realpath returned false'); // @codeCoverageIgnoreEnd } $directory = new RecursiveDirectoryIterator($baseDir); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH); $files = []; /** @var string[] $file */ foreach ($regex as $file) { $file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0])); $info = pathinfo($file); $category = str_replace('_', ' ', $info['dirname'] ?? ''); $name = str_replace('_', ' ', (string) preg_replace('/(|\.php)/', '', $info['filename'])); if (!in_array($category, ['.', 'bootstrap', 'templates']) && $name !== 'Header') { if (!isset($files[$category])) { $files[$category] = []; } $files[$category][$name] = $file; } } // Sort everything ksort($files); foreach ($files as &$f) { asort($f); } return $files; } /** * Write documents. * * @param string[] $writers */ public function write(Spreadsheet $spreadsheet, string $filename, array $writers = ['Xlsx', 'Xls'], bool $withCharts = false, ?callable $writerCallback = null, bool $resetActiveSheet = true): void { // Set active sheet index to the first sheet, so Excel opens this as the first sheet if ($resetActiveSheet) { $spreadsheet->setActiveSheetIndex(0); } // Write documents foreach ($writers as $writerType) { $path = $this->getFilename($filename, mb_strtolower($writerType)); if (preg_match('/(mpdf|tcpdf)$/', $path)) { $path .= '.pdf'; } $writer = IOFactory::createWriter($spreadsheet, $writerType); $writer->setIncludeCharts($withCharts); if ($writerCallback !== null) { $writerCallback($writer); } $callStartTime = microtime(true); $writer->save($path); $this->logWrite($writer, $path, $callStartTime); $this->addDownloadLink($path); } $this->logEndingNotes(); } public function addDownloadLink(string $path): void { if ($this->isCli() === false) { // @codeCoverageIgnoreStart echo 'Download ' . basename($path) . '
'; // @codeCoverageIgnoreEnd } } protected function isDirOrMkdir(string $folder): bool { return \is_dir($folder) || \mkdir($folder); } /** * Returns the temporary directory and make sure it exists. */ public function getTemporaryFolder(): string { $tempFolder = sys_get_temp_dir() . '/phpspreadsheet'; if (!$this->isDirOrMkdir($tempFolder)) { throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); } return $tempFolder; } /** * Returns the filename that should be used for sample output. */ public function getFilename(string $filename, string $extension = 'xlsx'): string { $originalExtension = pathinfo($filename, PATHINFO_EXTENSION); return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename)); } /** * Return a random temporary file name. */ public function getTemporaryFilename(string $extension = 'xlsx'): string { $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-'); if ($temporaryFilename === false) { // @codeCoverageIgnoreStart throw new RuntimeException('tempnam returned false'); // @codeCoverageIgnoreEnd } unlink($temporaryFilename); return $temporaryFilename . '.' . $extension; } public function log(mixed $message): void { $eol = $this->isCli() ? PHP_EOL : '
'; echo ($this->isCli() ? date('H:i:s ') : '') . StringHelper::convertToString($message) . $eol; } /** * Render chart as part of running chart samples in browser. * Charts are not rendered in unit tests, which are command line. * * @codeCoverageIgnore */ public function renderChart(Chart $chart, string $fileName, ?Spreadsheet $spreadsheet = null): void { if ($this->isCli() === true) { return; } Settings::setChartRenderer(MtJpGraphRenderer::class); $fileName = $this->getFilename($fileName, 'png'); $title = $chart->getTitle(); $caption = null; if ($title !== null) { $calculatedTitle = $title->getCalculatedTitle($spreadsheet); if ($calculatedTitle !== null) { $caption = $title->getCaption(); $title->setCaption($calculatedTitle); } } try { $chart->render($fileName); $this->log('Rendered image: ' . $fileName); $imageData = @file_get_contents($fileName); if ($imageData !== false) { echo '
'; } else { $this->log('Unable to open chart' . PHP_EOL); } } catch (Throwable $e) { $this->log('Error rendering chart: ' . $e->getMessage() . PHP_EOL); } if (isset($title, $caption)) { $title->setCaption($caption); } Settings::unsetChartRenderer(); } public function titles(string $category, string $functionName, ?string $description = null): void { $this->log(sprintf('%s Functions:', $category)); $description === null ? $this->log(sprintf('Function: %s()', rtrim($functionName, '()'))) : $this->log(sprintf('Function: %s() - %s.', rtrim($functionName, '()'), rtrim($description, '.'))); } /** @param mixed[][] $matrix */ public function displayGrid(array $matrix, null|bool|TextGridRightAlign $numbersRight = null): void { $renderer = new TextGrid($matrix, $this->isCli()); if (is_bool($numbersRight)) { $numbersRight = $numbersRight ? TextGridRightAlign::numeric : TextGridRightAlign::none; } if ($numbersRight !== null) { $renderer->setNumbersRight($numbersRight); } echo $renderer->render(); } public function logCalculationResult( Worksheet $worksheet, string $functionName, string $formulaCell, ?string $descriptionCell = null ): void { if ($descriptionCell !== null) { $this->log($worksheet->getCell($descriptionCell)->getValueString()); } $this->log($worksheet->getCell($formulaCell)->getValueString()); $this->log(sprintf('%s() Result is ', $functionName) . $worksheet->getCell($formulaCell)->getCalculatedValueString()); } /** * Log ending notes. */ public function logEndingNotes(): void { // Do not show execution time for index $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB'); } /** * Log a line about the write operation. */ public function logWrite(IWriter $writer, string $path, float $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; $reflection = new ReflectionClass($writer); $format = $reflection->getShortName(); $codePath = $this->isCli() ? $path : "$path"; $message = "Write {$format} format to {$codePath} in " . sprintf('%.4f', $callTime) . ' seconds'; $this->log($message); } /** * Log a line about the read operation. */ public function logRead(string $format, string $path, float $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; $message = "Read {$format} format from {$path} in " . sprintf('%.4f', $callTime) . ' seconds'; $this->log($message); } } ================================================ FILE: src/PhpSpreadsheet/Helper/Size.php ================================================ \d*\.?\d+)(?Ppt|px|em)?$/i'; protected bool $valid = false; protected string $size = ''; protected string $unit = ''; public function __construct(string $size) { if (1 === preg_match(self::REGEXP_SIZE_VALIDATION, $size, $matches)) { $this->valid = true; $this->size = $matches['size']; $this->unit = $matches['unit'] ?? 'pt'; } } public function valid(): bool { return $this->valid; } public function size(): string { return $this->size; } public function unit(): string { return $this->unit; } public function __toString(): string { return $this->size . $this->unit; } } ================================================ FILE: src/PhpSpreadsheet/Helper/TextGrid.php ================================================ rows = array_keys($matrix); $this->columns = array_keys($matrix[$this->rows[0]]); $matrix = array_values($matrix); array_walk( $matrix, function (&$row): void { $row = array_values($row); } ); $this->matrix = $matrix; $this->isCli = $isCli; $this->rowDividers = $rowDividers; $this->rowHeaders = $rowHeaders; $this->columnHeaders = $columnHeaders; $this->numbersRight = $numbersRight; } public function setNumbersRight(TextGridRightAlign $numbersRight): void { $this->numbersRight = $numbersRight; } public function render(): string { $this->gridDisplay = $this->isCli ? '' : ('
' . PHP_EOL);

        if (!empty($this->rows)) {
            $maxRow = max($this->rows);
            $maxRowLength = $this->strlen((string) $maxRow) + 1;
            $columnWidths = $this->getColumnWidths();

            $this->renderColumnHeader($maxRowLength, $columnWidths);
            $this->renderRows($maxRowLength, $columnWidths);
            if (!$this->rowDividers) {
                $this->renderFooter($maxRowLength, $columnWidths);
            }
        }

        $this->gridDisplay .= $this->isCli ? '' : '
'; return $this->gridDisplay; } /** @param int[] $columnWidths */ protected function renderRows(int $maxRowLength, array $columnWidths): void { foreach ($this->matrix as $row => $rowData) { if ($this->rowHeaders) { $this->gridDisplay .= '|' . str_pad((string) $this->rows[$row], $maxRowLength, ' ', STR_PAD_LEFT) . ' '; } $this->renderCells($rowData, $columnWidths); $this->gridDisplay .= '|' . PHP_EOL; if ($this->rowDividers) { $this->renderFooter($maxRowLength, $columnWidths); } } } /** * @param mixed[] $rowData * @param int[] $columnWidths */ protected function renderCells(array $rowData, array $columnWidths): void { foreach ($rowData as $column => $cell) { $valueForLength = $this->getString($cell); $displayCell = $this->isCli ? $valueForLength : htmlentities($valueForLength); $this->gridDisplay .= '| '; if ($this->rightAlign($displayCell, $cell)) { $this->gridDisplay .= str_repeat(' ', $columnWidths[$column] - $this->strlen($valueForLength)) . $displayCell . ' '; } else { $this->gridDisplay .= $displayCell . str_repeat(' ', $columnWidths[$column] - $this->strlen($valueForLength) + 1); } } } protected function rightAlign(string $displayCell, mixed $cell = null): bool { return ($this->numbersRight === TextGridRightAlign::numeric && is_numeric($displayCell)) || ($this->numbersRight === TextGridRightAlign::floatOrInt && (is_int($cell) || is_float($cell))); } /** @param int[] $columnWidths */ protected function renderColumnHeader(int $maxRowLength, array &$columnWidths): void { if (!$this->columnHeaders) { $this->renderFooter($maxRowLength, $columnWidths); return; } foreach ($this->columns as $column => $reference) { /** @var string $reference */ $columnWidths[$column] = max($columnWidths[$column], $this->strlen($reference)); } if ($this->rowHeaders) { $this->gridDisplay .= str_repeat(' ', $maxRowLength + 2); } foreach ($this->columns as $column => $reference) { $this->gridDisplay .= '+-' . str_repeat('-', $columnWidths[$column] + 1); } $this->gridDisplay .= '+' . PHP_EOL; if ($this->rowHeaders) { $this->gridDisplay .= str_repeat(' ', $maxRowLength + 2); } foreach ($this->columns as $column => $reference) { /** @var scalar $reference */ $this->gridDisplay .= '| ' . str_pad((string) $reference, $columnWidths[$column] + 1, ' '); } $this->gridDisplay .= '|' . PHP_EOL; $this->renderFooter($maxRowLength, $columnWidths); } /** @param int[] $columnWidths */ protected function renderFooter(int $maxRowLength, array $columnWidths): void { if ($this->rowHeaders) { $this->gridDisplay .= '+' . str_repeat('-', $maxRowLength + 1); } foreach ($this->columns as $column => $reference) { $this->gridDisplay .= '+-'; $this->gridDisplay .= str_pad((string) '', $columnWidths[$column] + 1, '-'); } $this->gridDisplay .= '+' . PHP_EOL; } /** @return int[] */ protected function getColumnWidths(): array { $columnCount = count($this->matrix, COUNT_RECURSIVE) / count($this->matrix); $columnWidths = []; for ($column = 0; $column < $columnCount; ++$column) { $columnWidths[] = $this->getColumnWidth(array_column($this->matrix, $column)); } return $columnWidths; } /** @param mixed[] $columnData */ protected function getColumnWidth(array $columnData): int { $columnWidth = 0; $columnData = array_values($columnData); foreach ($columnData as $columnValue) { $columnWidth = max($columnWidth, $this->strlen($this->getString($columnValue))); } return $columnWidth; } protected function getString(mixed $value): string { return StringHelper::convertToString($value, convertBool: true); } protected function strlen(string $value): int { return mb_strlen($value); } } ================================================ FILE: src/PhpSpreadsheet/Helper/TextGridRightAlign.php ================================================ > */ private static array $readers = [ self::READER_XLSX => Reader\Xlsx::class, self::READER_XLS => Reader\Xls::class, self::READER_XML => Reader\Xml::class, self::READER_ODS => Reader\Ods::class, self::READER_SLK => Reader\Slk::class, self::READER_GNUMERIC => Reader\Gnumeric::class, self::READER_HTML => Reader\Html::class, self::READER_CSV => Reader\Csv::class, ]; /** @var array> */ private static array $writers = [ self::WRITER_XLS => Writer\Xls::class, self::WRITER_XLSX => Writer\Xlsx::class, self::WRITER_ODS => Writer\Ods::class, self::WRITER_CSV => Writer\Csv::class, self::WRITER_HTML => Writer\Html::class, 'Tcpdf' => Writer\Pdf\Tcpdf::class, 'Dompdf' => Writer\Pdf\Dompdf::class, 'Mpdf' => Writer\Pdf\Mpdf::class, ]; /** @internal */ public static function restoreDefaultReadersAndWriters(): void { self::$readers = [ self::READER_XLSX => Reader\Xlsx::class, self::READER_XLS => Reader\Xls::class, self::READER_XML => Reader\Xml::class, self::READER_ODS => Reader\Ods::class, self::READER_SLK => Reader\Slk::class, self::READER_GNUMERIC => Reader\Gnumeric::class, self::READER_HTML => Reader\Html::class, self::READER_CSV => Reader\Csv::class, ]; self::$writers = [ self::WRITER_XLS => Writer\Xls::class, self::WRITER_XLSX => Writer\Xlsx::class, self::WRITER_ODS => Writer\Ods::class, self::WRITER_CSV => Writer\Csv::class, self::WRITER_HTML => Writer\Html::class, 'Tcpdf' => Writer\Pdf\Tcpdf::class, 'Dompdf' => Writer\Pdf\Dompdf::class, 'Mpdf' => Writer\Pdf\Mpdf::class, ]; } /** * Create Writer\IWriter. */ public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter { /** @var class-string */ $className = $writerType; if (!in_array($writerType, self::$writers, true)) { if (!isset(self::$writers[$writerType])) { throw new Writer\Exception("No writer found for type $writerType"); } // Instantiate writer $className = self::$writers[$writerType]; } return new $className($spreadsheet); } /** * Create IReader. */ public static function createReader(string $readerType): IReader { /** @var class-string */ $className = $readerType; if (!in_array($readerType, self::$readers, true)) { if (!isset(self::$readers[$readerType])) { throw new Reader\Exception("No reader found for type $readerType"); } // Instantiate reader $className = self::$readers[$readerType]; } return new $className(); } /** * Loads Spreadsheet from file using automatic Reader\IReader resolution. * * @param string $filename The name of the spreadsheet file * @param int $flags the optional second parameter flags may be used to identify specific elements * that should be loaded, but which won't be loaded by default, using these values: * IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file. * IReader::READ_DATA_ONLY - Read cell values only, not formatting or merge structure. * IReader::IGNORE_EMPTY_CELLS - Don't load empty cells into the model. * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try * all possible Readers until it finds a match; but this allows you to pass in a * list of Readers so it will only try the subset that you specify here. * Values in this list can be any of the constant values defined in the set * IOFactory::READER_*. */ public static function load(string $filename, int $flags = 0, ?array $readers = null): Spreadsheet { $reader = self::createReaderForFile($filename, $readers); return $reader->load($filename, $flags); } /** * Identify file type using automatic IReader resolution. * * @param string[] $readers */ public static function identify(string $filename, ?array $readers = null, bool $fullClassName = false): string { $reader = self::createReaderForFile($filename, $readers); $className = $reader::class; if ($fullClassName) { return $className; } $classType = explode('\\', $className); return array_pop($classType); } /** * Create Reader\IReader for file using automatic IReader resolution. * * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try * all possible Readers until it finds a match; but this allows you to pass in a * list of Readers so it will only try the subset that you specify here. * Values in this list can be any of the constant values defined in the set * IOFactory::READER_*. */ public static function createReaderForFile(string $filename, ?array $readers = null): IReader { File::assertFile($filename); $testReaders = self::$readers; if ($readers !== null) { $readers = array_map('strtoupper', $readers); $testReaders = array_filter( self::$readers, fn (string $readerType): bool => in_array(strtoupper($readerType), $readers, true), ARRAY_FILTER_USE_KEY ); } // First, lucky guess by inspecting file extension $guessedReader = self::getReaderTypeFromExtension($filename); if (($guessedReader !== null) && array_key_exists($guessedReader, $testReaders)) { $reader = self::createReader($guessedReader); // Let's see if we are lucky if ($reader->canRead($filename)) { return $reader; } } // If we reach here then "lucky guess" didn't give any result // Try walking through all the options in self::$readers (or the selected subset) foreach ($testReaders as $readerType => $class) { // Ignore our original guess, we know that won't work if ($readerType !== $guessedReader) { $reader = self::createReader($readerType); if ($reader->canRead($filename)) { return $reader; } } } throw new Reader\Exception('Unable to identify a reader for this file'); } /** * Guess a reader type from the file extension, if any. */ private static function getReaderTypeFromExtension(string $filename): ?string { $pathinfo = pathinfo($filename); if (!isset($pathinfo['extension'])) { return null; } return match (strtolower($pathinfo['extension'])) { // Excel (OfficeOpenXML) Spreadsheet 'xlsx', // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded) 'xlsm', // Excel (OfficeOpenXML) Template 'xltx', // Excel (OfficeOpenXML) Macro Template (macros will be discarded) 'xltm' => 'Xlsx', // Excel (BIFF) Spreadsheet 'xls', // Excel (BIFF) Template 'xlt' => 'Xls', // Open/Libre Offic Calc 'ods', // Open/Libre Offic Calc Template 'ots' => 'Ods', 'slk' => 'Slk', // Excel 2003 SpreadSheetML 'xml' => 'Xml', 'gnumeric' => 'Gnumeric', 'htm', 'html' => 'Html', // Do nothing // We must not try to use CSV reader since it loads // all files including Excel files etc. 'csv' => null, default => null, }; } /** * Register a writer with its type and class name. * * @param class-string $writerClass */ public static function registerWriter(string $writerType, string $writerClass): void { // We want phpstan to validate caller, but still need this test if (!is_a($writerClass, IWriter::class, true)) { //* @phpstan-ignore-line throw new Writer\Exception('Registered writers must implement ' . IWriter::class); } self::$writers[$writerType] = $writerClass; } /** * Register a reader with its type and class name. * * @param class-string $readerClass */ public static function registerReader(string $readerType, string $readerClass): void { // We want phpstan to validate caller, but still need this test if (!is_a($readerClass, IReader::class, true)) { //* @phpstan-ignore-line throw new Reader\Exception('Registered readers must implement ' . IReader::class); } self::$readers[$readerType] = $readerClass; } } ================================================ FILE: src/PhpSpreadsheet/NamedFormula.php ================================================ value; } /** * Set the formula value. */ public function setFormula(string $formula): self { if (!empty($formula)) { $this->value = $formula; } return $this; } } ================================================ FILE: src/PhpSpreadsheet/NamedRange.php ================================================ value; } /** * Set the range value. */ public function setRange(string $range): self { if (!empty($range)) { $this->value = $range; } return $this; } /** @return string[] */ public function getCellsInRange(): array { $range = $this->value; if (str_starts_with($range, '=')) { $range = substr($range, 1); } return Coordinate::extractAllCellReferencesInRange($range); } } ================================================ FILE: src/PhpSpreadsheet/Reader/BaseReader.php ================================================ readFilter = new DefaultReadFilter(); } public function getReadDataOnly(): bool { return $this->readDataOnly; } public function setReadDataOnly(bool $readCellValuesOnly): self { $this->readDataOnly = $readCellValuesOnly; return $this; } public function getReadEmptyCells(): bool { return $this->readEmptyCells; } public function setReadEmptyCells(bool $readEmptyCells): self { $this->readEmptyCells = $readEmptyCells; return $this; } public function getIgnoreRowsWithNoCells(): bool { return $this->ignoreRowsWithNoCells; } public function setIgnoreRowsWithNoCells(bool $ignoreRowsWithNoCells): self { $this->ignoreRowsWithNoCells = $ignoreRowsWithNoCells; return $this; } public function getIncludeCharts(): bool { return $this->includeCharts; } public function setIncludeCharts(bool $includeCharts): self { $this->includeCharts = $includeCharts; return $this; } public function getEnableDrawingPassThrough(): bool { return $this->enableDrawingPassThrough; } public function setEnableDrawingPassThrough(bool $enableDrawingPassThrough): self { $this->enableDrawingPassThrough = $enableDrawingPassThrough; return $this; } /** @return null|string[] */ public function getLoadSheetsOnly(): ?array { return $this->loadSheetsOnly; } /** @param null|string|string[] $sheetList */ public function setLoadSheetsOnly(string|array|null $sheetList): self { if ($sheetList === null) { return $this->setLoadAllSheets(); } $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList]; return $this; } public function setLoadAllSheets(): self { $this->loadSheetsOnly = null; return $this; } public function getReadFilter(): IReadFilter { return $this->readFilter; } public function setReadFilter(IReadFilter $readFilter): self { $this->readFilter = $readFilter; return $this; } /** * USE WITH CAUTION (and in conjunction with setIsWhiteListed)! * Allow external images; * these can be specified within a spreadsheet * in a way that can subject the caller to security exploits. */ public function setAllowExternalImages(bool $allowExternalImages): self { $this->allowExternalImages = $allowExternalImages; return $this; } public function getAllowExternalImages(): bool { return $this->allowExternalImages; } /** * USE WITH CAUTION! * Supply a callback to determine whether a path should be whitelisted, * used in conjunction with setAllowExternalImages; * supplying a method which might return true * can subject the caller to security exploits. * * @param Closure(string):bool $isWhitelisted */ public function setIsWhitelisted(Closure $isWhitelisted): self { $this->isWhitelisted = $isWhitelisted; return $this; } /** * Create a blank sheet if none are read, * possibly due to a typo when using LoadSheetsOnly. */ public function setCreateBlankSheetIfNoneRead(bool $createBlankSheetIfNoneRead): self { $this->createBlankSheetIfNoneRead = $createBlankSheetIfNoneRead; return $this; } public function getSecurityScanner(): ?XmlScanner { return $this->securityScanner; } public function getSecurityScannerOrThrow(): XmlScanner { if ($this->securityScanner === null) { throw new ReaderException('Security scanner is unexpectedly null'); } return $this->securityScanner; } protected function processFlags(int $flags): void { if (((bool) ($flags & self::LOAD_WITH_CHARTS)) === true) { $this->setIncludeCharts(true); } if (((bool) ($flags & self::READ_DATA_ONLY)) === true) { $this->setReadDataOnly(true); } if (((bool) ($flags & self::IGNORE_EMPTY_CELLS)) === true) { $this->setReadEmptyCells(false); } if (((bool) ($flags & self::IGNORE_ROWS_WITH_NO_CELLS)) === true) { $this->setIgnoreRowsWithNoCells(true); } if (((bool) ($flags & self::ALLOW_EXTERNAL_IMAGES)) === true) { $this->setAllowExternalImages(true); } if (((bool) ($flags & self::DONT_ALLOW_EXTERNAL_IMAGES)) === true) { $this->setAllowExternalImages(false); } if (((bool) ($flags & self::CREATE_BLANK_SHEET_IF_NONE_READ)) === true) { $this->setCreateBlankSheetIfNoneRead(true); } } protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { throw new PhpSpreadsheetException('Reader classes must implement their own loadSpreadsheetFromFile() method'); } /** * Loads Spreadsheet from file. * * @param int $flags the optional second parameter flags may be used to identify specific elements * that should be loaded, but which won't be loaded by default, using these values: * IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file */ public function load(string $filename, int $flags = 0): Spreadsheet { $this->processFlags($flags); try { return $this->loadSpreadsheetFromFile($filename); } catch (ReaderException $e) { throw $e; } } /** * Open file for reading. */ protected function openFile(string $filename): void { $fileHandle = false; if ($filename) { File::assertFile($filename); // Open file $fileHandle = fopen($filename, 'rb'); } if ($fileHandle === false) { throw new ReaderException('Could not open file ' . $filename . ' for reading.'); } $this->fileHandle = $fileHandle; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { throw new PhpSpreadsheetException('Reader classes must implement their own listWorksheetInfo() method'); } /** * Returns names of the worksheets from a file, * possibly without parsing the whole file to a Spreadsheet object. * Readers will often have a more efficient method with which * they can override this method. * * @return string[] */ public function listWorksheetNames(string $filename): array { $returnArray = []; $info = $this->listWorksheetInfo($filename); foreach ($info as $infoArray) { $returnArray[] = $infoArray['worksheetName']; } return $returnArray; } public function getValueBinder(): ?IValueBinder { return $this->valueBinder; } public function setValueBinder(?IValueBinder $valueBinder): self { $this->valueBinder = $valueBinder; return $this; } protected function newSpreadsheet(): Spreadsheet { return new Spreadsheet(); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Csv/Delimiter.php ================================================ */ protected array $counts = []; protected int $numberLines = 0; protected ?string $delimiter = null; /** * @param resource $fileHandle */ public function __construct($fileHandle, string $escapeCharacter, string $enclosure) { $this->fileHandle = $fileHandle; $this->escapeCharacter = $escapeCharacter; $this->enclosure = $enclosure; $this->countPotentialDelimiters(); } public function getDefaultDelimiter(): string { return self::POTENTIAL_DELIMITERS[0]; } public function linesCounted(): int { return $this->numberLines; } protected function countPotentialDelimiters(): void { $this->counts = array_fill_keys(self::POTENTIAL_DELIMITERS, []); $delimiterKeys = array_flip(self::POTENTIAL_DELIMITERS); // Count how many times each of the potential delimiters appears in each line $this->numberLines = 0; while (($line = $this->getNextLine()) !== false && (++$this->numberLines < 1000)) { $this->countDelimiterValues($line, $delimiterKeys); } } /** @param array $delimiterKeys */ protected function countDelimiterValues(string $line, array $delimiterKeys): void { $splitString = mb_str_split($line, 1, 'UTF-8'); $distribution = array_count_values($splitString); $countLine = array_intersect_key($distribution, $delimiterKeys); foreach (self::POTENTIAL_DELIMITERS as $delimiter) { $this->counts[$delimiter][] = $countLine[$delimiter] ?? 0; } } public function infer(): ?string { // Calculate the mean square deviations for each delimiter // (ignoring delimiters that haven't been found consistently) $meanSquareDeviations = []; $middleIdx = (int) floor(($this->numberLines - 1) / 2); foreach (self::POTENTIAL_DELIMITERS as $delimiter) { $series = $this->counts[$delimiter]; sort($series); $median = ($this->numberLines % 2) ? $series[$middleIdx] : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2; if ($median === 0) { continue; } $meanSquareDeviations[$delimiter] = array_reduce( $series, fn ($sum, $value): int|float => $sum + ($value - $median) ** 2 ) / count($series); } // ... and pick the delimiter with the smallest mean square deviation // (in case of ties, the order in potentialDelimiters is respected) $min = INF; foreach (self::POTENTIAL_DELIMITERS as $delimiter) { if (!isset($meanSquareDeviations[$delimiter])) { continue; } if ($meanSquareDeviations[$delimiter] < $min) { $min = $meanSquareDeviations[$delimiter]; $this->delimiter = $delimiter; } } return $this->delimiter; } /** * Get the next full line from the file. * * @return false|string */ public function getNextLine() { $line = ''; $enclosure = ($this->escapeCharacter === '' ? '' : ('(?escapeCharacter, '/') . ')')) . preg_quote($this->enclosure, '/'); do { // Get the next line in the file $newLine = fgets($this->fileHandle); // Return false if there is no next line if ($newLine === false) { return false; } // Add the new line to the line passed in $line = $line . $newLine; // Drop everything that is enclosed to avoid counting false positives in enclosures $line = (string) preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line); // See if we have any enclosures left in the line // if we still have an enclosure then we need to read the next line as well } while (preg_match('/(' . $enclosure . ')/', $line) > 0); return ($line !== '') ? $line : false; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Csv.php ================================================ inputEncoding = $encoding; return $this; } public function getInputEncoding(): string { return $this->inputEncoding; } public function setFallbackEncoding(string $fallbackEncoding): self { $this->fallbackEncoding = $fallbackEncoding; return $this; } public function getFallbackEncoding(): string { return $this->fallbackEncoding; } /** * Move filepointer past any BOM marker. */ protected function skipBOM(): void { rewind($this->fileHandle); if (fgets($this->fileHandle, self::UTF8_BOM_LEN + 1) !== self::UTF8_BOM) { rewind($this->fileHandle); } } /** * Identify any separator that is explicitly set in the file. */ protected function checkSeparator(): void { $line = fgets($this->fileHandle); if ($line === false) { return; } if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) { $this->delimiter = substr($line, 4, 1); return; } $this->skipBOM(); } /** * Infer the separator if it isn't explicitly set in the file or specified by the user. */ protected function inferSeparator(): void { $temp = $this->delimiter; if ($temp !== null) { return; } $inferenceEngine = new Delimiter($this->fileHandle, $this->getEscapeCharacter(), $this->enclosure); // If number of lines is 0, nothing to infer : fall back to the default if ($inferenceEngine->linesCounted() === 0) { $this->delimiter = $inferenceEngine->getDefaultDelimiter(); $this->skipBOM(); return; } $this->delimiter = $inferenceEngine->infer(); // If no delimiter could be detected, fall back to the default if ($this->delimiter === null) { $this->delimiter = $inferenceEngine->getDefaultDelimiter(); } $this->skipBOM(); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { // Open file $this->openFileOrMemory($filename); $fileHandle = $this->fileHandle; // Skip BOM, if any $this->skipBOM(); $this->checkSeparator(); $this->inferSeparator(); $worksheetInfo = [ [ 'worksheetName' => 'Worksheet', 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ], ]; $delimiter = $this->delimiter ?? ''; // Loop through each line of the file in turn $rowData = self::getCsv($fileHandle, 0, $delimiter, $this->enclosure, $this->escapeCharacter); while (is_array($rowData)) { ++$worksheetInfo[0]['totalRows']; $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); $rowData = self::getCsv($fileHandle, 0, $delimiter, $this->enclosure, $this->escapeCharacter); } $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1, true); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; $worksheetInfo[0]['sheetState'] = Worksheet::SHEETSTATE_VISIBLE; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads Spreadsheet from string. */ public function loadSpreadsheetFromString(string $contents): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); // Load into this instance return $this->loadStringOrFile('data://text/plain,' . urlencode($contents), $spreadsheet, true); } private function openFileOrMemory(string $filename): void { // Open file $fhandle = $this->canRead($filename); if (!$fhandle) { throw new ReaderException($filename . ' is an Invalid Spreadsheet file.'); } if ($this->inputEncoding === 'UTF-8') { $encoding = self::guessEncodingBom($filename); if ($encoding !== '') { $this->inputEncoding = $encoding; } } if ($this->inputEncoding === self::GUESS_ENCODING) { $this->inputEncoding = self::guessEncoding($filename, $this->fallbackEncoding); } $this->openFile($filename); if ($this->inputEncoding !== 'UTF-8') { fclose($this->fileHandle); $entireFile = file_get_contents($filename); $fileHandle = fopen('php://memory', 'r+b'); if ($fileHandle !== false && $entireFile !== false) { $this->fileHandle = $fileHandle; $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); fwrite($this->fileHandle, $data); $this->skipBOM(); } } } public function setTestAutoDetect(bool $value): self { $this->testAutodetect = $value; return $this; } private function setAutoDetect(?string $value, int $version = PHP_VERSION_ID): ?string { $retVal = null; if ($value !== null && $this->testAutodetect && $version < 90000) { $retVal2 = @ini_set('auto_detect_line_endings', $value); if (is_string($retVal2)) { $retVal = $retVal2; } } return $retVal; } public function castFormattedNumberToNumeric( bool $castFormattedNumberToNumeric, bool $preserveNumericFormatting = false ): void { $this->castFormattedNumberToNumeric = $castFormattedNumberToNumeric; $this->preserveNumericFormatting = $preserveNumericFormatting; } /** * Open data uri for reading. */ private function openDataUri(string $filename): void { $fileHandle = fopen($filename, 'rb'); if ($fileHandle === false) { // @codeCoverageIgnoreStart throw new ReaderException('Could not open file ' . $filename . ' for reading.'); // @codeCoverageIgnoreEnd } $this->fileHandle = $fileHandle; } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { return $this->loadStringOrFile($filename, $spreadsheet, false); } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ private function loadStringOrFile(string $filename, Spreadsheet $spreadsheet, bool $dataUri): Spreadsheet { // Deprecated in Php8.1 $iniset = $this->setAutoDetect('1'); try { $this->loadStringOrFile2($filename, $spreadsheet, $dataUri); $this->setAutoDetect($iniset); } catch (Throwable $e) { $this->setAutoDetect($iniset); throw $e; } return $spreadsheet; } private function loadStringOrFile2(string $filename, Spreadsheet $spreadsheet, bool $dataUri): void { // Open file if ($dataUri) { $this->openDataUri($filename); } else { $this->openFileOrMemory($filename); } $fileHandle = $this->fileHandle; // Skip BOM, if any $this->skipBOM(); $this->checkSeparator(); $this->inferSeparator(); // Create new PhpSpreadsheet object while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $sheet = $spreadsheet->setActiveSheetIndex($this->sheetIndex); if ($this->sheetNameIsFileName) { $sheet->setTitle(substr(basename($filename, '.csv'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH)); } // Set our starting row based on whether we're in contiguous mode or not $currentRow = 1; $outRow = 0; // Loop through each line of the file in turn $delimiter = $this->delimiter ?? ''; $rowData = self::getCsv($fileHandle, 0, $delimiter, $this->enclosure, $this->escapeCharacter); $valueBinder = $this->valueBinder ?? Cell::getValueBinder(); $preserveBooleanString = method_exists($valueBinder, 'getBooleanConversion') && $valueBinder->getBooleanConversion(); $this->getTrue = Calculation::getTRUE(); $this->getFalse = Calculation::getFALSE(); $this->thousandsSeparator = StringHelper::getThousandsSeparator(); $this->decimalSeparator = StringHelper::getDecimalSeparator(); while (is_array($rowData)) { $noOutputYet = true; $columnLetter = 'A'; foreach ($rowData as $rowDatum) { if ($preserveBooleanString) { $rowDatum = $rowDatum ?? ''; } else { $this->convertBoolean($rowDatum); } $numberFormatMask = $this->castFormattedNumberToNumeric ? $this->convertFormattedNumber($rowDatum) : ''; if (($rowDatum !== '' || $this->preserveNullString) && $this->readFilter->readCell($columnLetter, $currentRow)) { if ($this->contiguous) { if ($noOutputYet) { $noOutputYet = false; ++$outRow; } } else { $outRow = $currentRow; } // Set basic styling for the value (Note that this could be overloaded by styling in a value binder) if ($numberFormatMask !== '') { $sheet->getStyle($columnLetter . $outRow) ->getNumberFormat() ->setFormatCode($numberFormatMask); } // Set cell value $sheet->getCell($columnLetter . $outRow)->setValue($rowDatum); } StringHelper::stringIncrement($columnLetter); } $rowData = self::getCsv($fileHandle, 0, $delimiter, $this->enclosure, $this->escapeCharacter); ++$currentRow; } // Close file fclose($fileHandle); } /** * Convert string true/false to boolean, and null to null-string. */ private function convertBoolean(mixed &$rowDatum): void { if (is_string($rowDatum)) { if (strcasecmp($this->getTrue, $rowDatum) === 0 || strcasecmp('true', $rowDatum) === 0) { $rowDatum = true; } elseif (strcasecmp($this->getFalse, $rowDatum) === 0 || strcasecmp('false', $rowDatum) === 0) { $rowDatum = false; } } else { $rowDatum = $rowDatum ?? ''; } } /** * Convert numeric strings to int or float values. */ private function convertFormattedNumber(mixed &$rowDatum): string { $numberFormatMask = ''; if ($this->castFormattedNumberToNumeric === true && is_string($rowDatum)) { $numeric = str_replace( [$this->thousandsSeparator, $this->decimalSeparator], ['', '.'], $rowDatum ); if (is_numeric($numeric)) { $decimalPos = strpos($rowDatum, $this->decimalSeparator); if ($this->preserveNumericFormatting === true) { $numberFormatMask = (str_contains($rowDatum, $this->thousandsSeparator)) ? '#,##0' : '0'; if ($decimalPos !== false) { $decimals = strlen($rowDatum) - $decimalPos - 1; $numberFormatMask .= '.' . str_repeat('0', min($decimals, 6)); } } $rowDatum = ($decimalPos !== false) ? (float) $numeric : (int) $numeric; } } return $numberFormatMask; } public function getDelimiter(): ?string { return $this->delimiter; } public function setDelimiter(?string $delimiter): self { $this->delimiter = $delimiter; return $this; } public function getEnclosure(): string { return $this->enclosure; } public function setEnclosure(string $enclosure): self { if ($enclosure == '') { $enclosure = '"'; } $this->enclosure = $enclosure; return $this; } public function getSheetIndex(): int { return $this->sheetIndex; } public function setSheetIndex(int $indexValue): self { $this->sheetIndex = $indexValue; return $this; } public function setContiguous(bool $contiguous): self { $this->contiguous = $contiguous; return $this; } public function getContiguous(): bool { return $this->contiguous; } /** * Php9 intends to drop support for this parameter in fgetcsv. * Not yet ready to mark deprecated in order to give users * a migration path. */ public function setEscapeCharacter(string $escapeCharacter, int $version = PHP_VERSION_ID): self { if ($version >= 90000 && $escapeCharacter !== '') { throw new ReaderException('Escape character must be null string for Php9+'); } $this->escapeCharacter = $escapeCharacter; return $this; } public function getEscapeCharacter(int $version = PHP_VERSION_ID): string { return $this->escapeCharacter ?? self::getDefaultEscapeCharacter($version); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); } catch (ReaderException) { return false; } fclose($this->fileHandle); // Trust file extension if any $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (in_array($extension, ['csv', 'tsv'])) { return true; } // Attempt to guess mimetype $type = mime_content_type($filename); $supportedTypes = [ 'application/csv', 'text/csv', 'text/plain', 'inode/x-empty', 'application/x-empty', // has now replaced previous 'text/html', ]; return in_array($type, $supportedTypes, true); } private static function guessEncodingTestNoBom(string &$encoding, string &$contents, string $compare, string $setEncoding): void { if ($encoding === '') { $pos = strpos($contents, $compare); if ($pos !== false && $pos % strlen($compare) === 0) { $encoding = $setEncoding; } } } private static function guessEncodingNoBom(string $filename): string { $encoding = ''; $contents = (string) file_get_contents($filename); self::guessEncodingTestNoBom($encoding, $contents, self::UTF32BE_LF, 'UTF-32BE'); self::guessEncodingTestNoBom($encoding, $contents, self::UTF32LE_LF, 'UTF-32LE'); self::guessEncodingTestNoBom($encoding, $contents, self::UTF16BE_LF, 'UTF-16BE'); self::guessEncodingTestNoBom($encoding, $contents, self::UTF16LE_LF, 'UTF-16LE'); if ($encoding === '' && preg_match('//u', $contents) === 1) { $encoding = 'UTF-8'; } return $encoding; } private static function guessEncodingTestBom(string &$encoding, string $first4, string $compare, string $setEncoding): void { if ($encoding === '') { if (str_starts_with($first4, $compare)) { $encoding = $setEncoding; } } } public static function guessEncodingBom(string $filename, ?string $convertString = null): string { $encoding = ''; $first4 = $convertString ?? (string) file_get_contents($filename, false, null, 0, 4); self::guessEncodingTestBom($encoding, $first4, self::UTF8_BOM, 'UTF-8'); self::guessEncodingTestBom($encoding, $first4, self::UTF16BE_BOM, 'UTF-16BE'); self::guessEncodingTestBom($encoding, $first4, self::UTF32BE_BOM, 'UTF-32BE'); self::guessEncodingTestBom($encoding, $first4, self::UTF32LE_BOM, 'UTF-32LE'); self::guessEncodingTestBom($encoding, $first4, self::UTF16LE_BOM, 'UTF-16LE'); return $encoding; } public static function guessEncoding(string $filename, string $dflt = self::DEFAULT_FALLBACK_ENCODING): string { $encoding = self::guessEncodingBom($filename); if ($encoding === '') { $encoding = self::guessEncodingNoBom($filename); } return ($encoding === '') ? $dflt : $encoding; } public function setPreserveNullString(bool $value): self { $this->preserveNullString = $value; return $this; } public function getPreserveNullString(): bool { return $this->preserveNullString; } public function setSheetNameIsFileName(bool $sheetNameIsFileName): self { $this->sheetNameIsFileName = $sheetNameIsFileName; return $this; } /** * Php8.4 deprecates use of anything other than null string * as escape Character. * * @param resource $stream * @param null|int<0, max> $length * * @return array|false */ private static function getCsv( $stream, ?int $length = null, string $separator = ',', string $enclosure = '"', ?string $escape = null, int $version = PHP_VERSION_ID ): array|false { $escape = $escape ?? self::getDefaultEscapeCharacter(); if ($version >= 80400 && $escape !== '') { return @fgetcsv($stream, $length, $separator, $enclosure, $escape); } return fgetcsv($stream, $length, $separator, $enclosure, $escape); } public static function affectedByPhp9( string $filename, string $inputEncoding = 'UTF-8', ?string $delimiter = null, string $enclosure = '"', string $escapeCharacter = '\\', int $version = PHP_VERSION_ID ): bool { if ($version < 70400 || $version >= 90000) { throw new ReaderException('Function valid only for Php7.4 or Php8'); } $reader1 = new self(); $reader1->setInputEncoding($inputEncoding) ->setTestAutoDetect(true) ->setEscapeCharacter($escapeCharacter) ->setDelimiter($delimiter) ->setEnclosure($enclosure); $spreadsheet1 = $reader1->load($filename); $sheet1 = $spreadsheet1->getActiveSheet(); $array1 = $sheet1->toArray(null, false, false); $spreadsheet1->disconnectWorksheets(); $reader2 = new self(); $reader2->setInputEncoding($inputEncoding) ->setTestAutoDetect(false) ->setEscapeCharacter('') ->setDelimiter($delimiter) ->setEnclosure($enclosure); $spreadsheet2 = $reader2->load($filename); $sheet2 = $spreadsheet2->getActiveSheet(); $array2 = $sheet2->toArray(null, false, false); $spreadsheet2->disconnectWorksheets(); return $array1 !== $array2; } /** * The character that will be supplied to fgetcsv * when escapeCharacter is null. * It is anticipated that it will conditionally be set * to null-string for Php9 and above. */ private static function getDefaultEscapeCharacter(int $version = PHP_VERSION_ID): string { return $version < 90000 ? '\\' : ''; } } ================================================ FILE: src/PhpSpreadsheet/Reader/DefaultReadFilter.php ================================================ spreadsheet = $spreadsheet; } public function printInformation(SimpleXMLElement $sheet): self { if (isset($sheet->PrintInformation, $sheet->PrintInformation[0])) { $printInformation = $sheet->PrintInformation[0]; $setup = $this->spreadsheet->getActiveSheet()->getPageSetup(); $attributes = $printInformation->Scale->attributes(); if (isset($attributes['percentage'])) { $setup->setScale((int) $attributes['percentage']); } $pageOrder = (string) $printInformation->order; if ($pageOrder === 'r_then_d') { $setup->setPageOrder(WorksheetPageSetup::PAGEORDER_OVER_THEN_DOWN); } elseif ($pageOrder === 'd_then_r') { $setup->setPageOrder(WorksheetPageSetup::PAGEORDER_DOWN_THEN_OVER); } $orientation = (string) $printInformation->orientation; if ($orientation !== '') { $setup->setOrientation($orientation); } $attributes = $printInformation->hcenter->attributes(); if (isset($attributes['value'])) { $setup->setHorizontalCentered((bool) (string) $attributes['value']); } $attributes = $printInformation->vcenter->attributes(); if (isset($attributes['value'])) { $setup->setVerticalCentered((bool) (string) $attributes['value']); } } return $this; } public function sheetMargins(SimpleXMLElement $sheet): self { if (isset($sheet->PrintInformation, $sheet->PrintInformation->Margins)) { $marginSet = [ // Default Settings 'top' => 0.75, 'header' => 0.3, 'left' => 0.7, 'right' => 0.7, 'bottom' => 0.75, 'footer' => 0.3, ]; $marginSet = $this->buildMarginSet($sheet, $marginSet); $this->adjustMargins($marginSet); } return $this; } /** * @param float[] $marginSet * * @return float[] */ private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array { foreach ($sheet->PrintInformation->Margins->children(Gnumeric::NAMESPACE_GNM) as $key => $margin) { $marginAttributes = $margin->attributes(); $marginSize = ($marginAttributes['Points']) ?? 72; // Default is 72pt // Convert value in points to inches $marginSize = PageMargins::fromPoints((float) $marginSize); $marginSet[$key] = $marginSize; } return $marginSet; } /** @param float[] $marginSet */ private function adjustMargins(array $marginSet): void { foreach ($marginSet as $key => $marginSize) { // Gnumeric is quirky in the way it displays the header/footer values: // header is actually the sum of top and header; footer is actually the sum of bottom and footer // then top is actually the header value, and bottom is actually the footer value switch ($key) { case 'left': case 'right': $this->sheetMargin($key, $marginSize); break; case 'top': $this->sheetMargin($key, $marginSet['header'] ?? 0); break; case 'bottom': $this->sheetMargin($key, $marginSet['footer'] ?? 0); break; case 'header': $this->sheetMargin($key, ($marginSet['top'] ?? 0) - $marginSize); break; case 'footer': $this->sheetMargin($key, ($marginSet['bottom'] ?? 0) - $marginSize); break; } } } private function sheetMargin(string $key, float $marginSize): void { switch ($key) { case 'top': $this->spreadsheet->getActiveSheet()->getPageMargins()->setTop($marginSize); break; case 'bottom': $this->spreadsheet->getActiveSheet()->getPageMargins()->setBottom($marginSize); break; case 'left': $this->spreadsheet->getActiveSheet()->getPageMargins()->setLeft($marginSize); break; case 'right': $this->spreadsheet->getActiveSheet()->getPageMargins()->setRight($marginSize); break; case 'header': $this->spreadsheet->getActiveSheet()->getPageMargins()->setHeader($marginSize); break; case 'footer': $this->spreadsheet->getActiveSheet()->getPageMargins()->setFooter($marginSize); break; } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Gnumeric/Properties.php ================================================ spreadsheet = $spreadsheet; } private function docPropertiesOld(SimpleXMLElement $gnmXML): void { $docProps = $this->spreadsheet->getProperties(); foreach ($gnmXML->Summary->Item as $summaryItem) { $propertyName = $summaryItem->name; $propertyValue = $summaryItem->{'val-string'}; switch ($propertyName) { case 'title': $docProps->setTitle(trim($propertyValue)); break; case 'comments': $docProps->setDescription(trim($propertyValue)); break; case 'keywords': $docProps->setKeywords(trim($propertyValue)); break; case 'category': $docProps->setCategory(trim($propertyValue)); break; case 'manager': $docProps->setManager(trim($propertyValue)); break; case 'author': $docProps->setCreator(trim($propertyValue)); $docProps->setLastModifiedBy(trim($propertyValue)); break; case 'company': $docProps->setCompany(trim($propertyValue)); break; } } } private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void { $docProps = $this->spreadsheet->getProperties(); foreach ($officePropertyDC as $propertyName => $propertyValue) { $propertyValue = trim((string) $propertyValue); switch ($propertyName) { case 'title': $docProps->setTitle($propertyValue); break; case 'subject': $docProps->setSubject($propertyValue); break; case 'creator': $docProps->setCreator($propertyValue); $docProps->setLastModifiedBy($propertyValue); break; case 'date': $creationDate = $propertyValue; $docProps->setModified($creationDate); break; case 'description': $docProps->setDescription($propertyValue); break; } } } private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta): void { $docProps = $this->spreadsheet->getProperties(); foreach ($officePropertyMeta as $propertyName => $propertyValue) { $attributes = $propertyValue->attributes(Gnumeric::NAMESPACE_META); $propertyValue = trim((string) $propertyValue); switch ($propertyName) { case 'keyword': $docProps->setKeywords($propertyValue); break; case 'initial-creator': $docProps->setCreator($propertyValue); $docProps->setLastModifiedBy($propertyValue); break; case 'creation-date': $creationDate = $propertyValue; $docProps->setCreated($creationDate); break; case 'user-defined': if ($attributes) { [, $attrName] = explode(':', (string) $attributes['name']); $this->userDefinedProperties($attrName, $propertyValue); } break; } } } private function userDefinedProperties(string $attrName, string $propertyValue): void { $docProps = $this->spreadsheet->getProperties(); switch ($attrName) { case 'publisher': $docProps->setCompany($propertyValue); break; case 'category': $docProps->setCategory($propertyValue); break; case 'manager': $docProps->setManager($propertyValue); break; } } public function readProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML): void { $officeXML = $xml->children(Gnumeric::NAMESPACE_OFFICE); if (!empty($officeXML)) { $officeDocXML = $officeXML->{'document-meta'}; $officeDocMetaXML = $officeDocXML->meta; foreach ($officeDocMetaXML as $officePropertyData) { $officePropertyDC = $officePropertyData->children(Gnumeric::NAMESPACE_DC); $this->docPropertiesDC($officePropertyDC); $officePropertyMeta = $officePropertyData->children(Gnumeric::NAMESPACE_META); $this->docPropertiesMeta($officePropertyMeta); } } elseif (isset($gnmXML->Summary)) { $this->docPropertiesOld($gnmXML); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Gnumeric/Styles.php ================================================ */ public static array $mappings = [ 'borderStyle' => [ '0' => Border::BORDER_NONE, '1' => Border::BORDER_THIN, '2' => Border::BORDER_MEDIUM, '3' => Border::BORDER_SLANTDASHDOT, '4' => Border::BORDER_DASHED, '5' => Border::BORDER_THICK, '6' => Border::BORDER_DOUBLE, '7' => Border::BORDER_DOTTED, '8' => Border::BORDER_MEDIUMDASHED, '9' => Border::BORDER_DASHDOT, '10' => Border::BORDER_MEDIUMDASHDOT, '11' => Border::BORDER_DASHDOTDOT, '12' => Border::BORDER_MEDIUMDASHDOTDOT, '13' => Border::BORDER_MEDIUMDASHDOTDOT, ], 'fillType' => [ '1' => Fill::FILL_SOLID, '2' => Fill::FILL_PATTERN_DARKGRAY, '3' => Fill::FILL_PATTERN_MEDIUMGRAY, '4' => Fill::FILL_PATTERN_LIGHTGRAY, '5' => Fill::FILL_PATTERN_GRAY125, '6' => Fill::FILL_PATTERN_GRAY0625, '7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe '8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe '9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe '10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe '11' => Fill::FILL_PATTERN_DARKGRID, // diagonal crosshatch '12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch '13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL, '14' => Fill::FILL_PATTERN_LIGHTVERTICAL, '15' => Fill::FILL_PATTERN_LIGHTUP, '16' => Fill::FILL_PATTERN_LIGHTDOWN, '17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch '18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch ], 'horizontal' => [ '1' => Alignment::HORIZONTAL_GENERAL, '2' => Alignment::HORIZONTAL_LEFT, '4' => Alignment::HORIZONTAL_RIGHT, '8' => Alignment::HORIZONTAL_CENTER, '16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, '32' => Alignment::HORIZONTAL_JUSTIFY, '64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, ], 'underline' => [ '1' => Font::UNDERLINE_SINGLE, '2' => Font::UNDERLINE_DOUBLE, '3' => Font::UNDERLINE_SINGLEACCOUNTING, '4' => Font::UNDERLINE_DOUBLEACCOUNTING, ], 'vertical' => [ '1' => Alignment::VERTICAL_TOP, '2' => Alignment::VERTICAL_BOTTOM, '4' => Alignment::VERTICAL_CENTER, '8' => Alignment::VERTICAL_JUSTIFY, ], ]; public function __construct(Spreadsheet $spreadsheet, bool $readDataOnly) { $this->spreadsheet = $spreadsheet; $this->readDataOnly = $readDataOnly; } public function read(SimpleXMLElement $sheet, int $maxRow, int $maxCol): void { if ($sheet->Styles->StyleRegion !== null) { $this->readStyles($sheet->Styles->StyleRegion, $maxRow, $maxCol); } } private function readStyles(SimpleXMLElement $styleRegion, int $maxRow, int $maxCol): void { foreach ($styleRegion as $style) { $styleAttributes = $style->attributes(); if ($styleAttributes !== null && ($styleAttributes['startRow'] <= $maxRow) && ($styleAttributes['startCol'] <= $maxCol)) { $cellRange = $this->readStyleRange($styleAttributes, $maxCol, $maxRow); $styleAttributes = $style->Style->attributes(); /** @var mixed[][] */ $styleArray = []; // We still set the number format mask for date/time values, even if readDataOnly is true // so that we can identify whether a float is a float or a date value $formatCode = $styleAttributes ? (string) $styleAttributes['Format'] : null; if ($formatCode && Date::isDateTimeFormatCode($formatCode)) { $styleArray['numberFormat']['formatCode'] = $formatCode; } if ($this->readDataOnly === false && $styleAttributes !== null) { // If readDataOnly is false, we set all formatting information $styleArray['numberFormat']['formatCode'] = $formatCode; $styleArray = $this->readStyle($styleArray, $styleAttributes, $style); } /** @var mixed[][] $styleArray */ $this->spreadsheet ->getActiveSheet() ->getStyle($cellRange) ->applyFromArray($styleArray); } } } /** @param mixed[][] $styleArray */ private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void { if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) { $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH; } elseif (isset($srssb->Diagonal)) { $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP; } elseif (isset($srssb->{'Rev-Diagonal'})) { $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes()); $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN; } } /** @param mixed[][] $styleArray */ private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void { $ucDirection = ucfirst($direction); if (isset($srssb->$ucDirection)) { /** @var SimpleXMLElement */ $temp = $srssb->$ucDirection; $styleArray['borders'][$direction] = self::parseBorderAttributes($temp->attributes()); } } private function calcRotation(SimpleXMLElement $styleAttributes): int { $rotation = (int) $styleAttributes->Rotation; if ($rotation >= 270 && $rotation <= 360) { $rotation -= 360; } $rotation = (abs($rotation) > 90) ? 0 : $rotation; return $rotation; } /** @param mixed[][] $styleArray */ private static function addStyle(array &$styleArray, string $key, string $value): void { if (array_key_exists($value, self::$mappings[$key])) { $styleArray[$key] = self::$mappings[$key][$value]; //* @phpstan-ignore-line } } /** @param mixed[][] $styleArray */ private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void { if (array_key_exists($value, self::$mappings[$key])) { $styleArray[$key1][$key] = self::$mappings[$key][$value]; } } /** @return mixed[][] */ private static function parseBorderAttributes(?SimpleXMLElement $borderAttributes): array { /** @var mixed[][] */ $styleArray = []; if ($borderAttributes !== null) { if (isset($borderAttributes['Color'])) { $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); } self::addStyle($styleArray, 'borderStyle', (string) $borderAttributes['Style']); } /** @var mixed[][] $styleArray */ return $styleArray; } private static function parseGnumericColour(string $gnmColour): string { [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour); $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); return $gnmR . $gnmG . $gnmB; } /** @param mixed[][] $styleArray */ private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void { $RGB = self::parseGnumericColour((string) $styleAttributes['Fore']); /** @var mixed[][][] $styleArray */ $styleArray['font']['color']['rgb'] = $RGB; $RGB = self::parseGnumericColour((string) $styleAttributes['Back']); $shade = (string) $styleAttributes['Shade']; if (($RGB !== '000000') || ($shade !== '0')) { $RGB2 = self::parseGnumericColour((string) $styleAttributes['PatternColor']); if ($shade === '1') { $styleArray['fill']['startColor']['rgb'] = $RGB; $styleArray['fill']['endColor']['rgb'] = $RGB2; } else { $styleArray['fill']['endColor']['rgb'] = $RGB; $styleArray['fill']['startColor']['rgb'] = $RGB2; } self::addStyle2($styleArray, 'fill', 'fillType', $shade); } } private function readStyleRange(SimpleXMLElement $styleAttributes, int $maxCol, int $maxRow): string { $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1); $startRow = $styleAttributes['startRow'] + 1; $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1); $endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']); $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow; return $cellRange; } /** * @param mixed[][] $styleArray * * @return mixed[] */ private function readStyle(array $styleArray, SimpleXMLElement $styleAttributes, SimpleXMLElement $style): array { self::addStyle2($styleArray, 'alignment', 'horizontal', (string) $styleAttributes['HAlign']); self::addStyle2($styleArray, 'alignment', 'vertical', (string) $styleAttributes['VAlign']); $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1'; $styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes); $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1'; $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0; $this->addColors($styleArray, $styleAttributes); $fontAttributes = $style->Style->Font->attributes(); if ($fontAttributes !== null) { $styleArray['font']['name'] = (string) $style->Style->Font; $styleArray['font']['size'] = (int) ($fontAttributes['Unit']); $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1'; $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1'; $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1'; self::addStyle2($styleArray, 'font', 'underline', (string) $fontAttributes['Underline']); switch ($fontAttributes['Script']) { case '1': $styleArray['font']['superscript'] = true; break; case '-1': $styleArray['font']['subscript'] = true; break; } } if (isset($style->Style->StyleBorder)) { $srssb = $style->Style->StyleBorder; $this->addBorderStyle($srssb, $styleArray, 'top'); $this->addBorderStyle($srssb, $styleArray, 'bottom'); $this->addBorderStyle($srssb, $styleArray, 'left'); $this->addBorderStyle($srssb, $styleArray, 'right'); $this->addBorderDiagonal($srssb, $styleArray); } // TO DO /* if (isset($style->Style->HyperLink)) { $hyperlink = $style->Style->HyperLink->attributes(); } */ return $styleArray; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Gnumeric.php ================================================ */ private array $expressions = []; /** * Spreadsheet shared across all functions. */ private Spreadsheet $spreadsheet; private ReferenceHelper $referenceHelper; /** @var array{'dataType': string[]} */ public static array $mappings = [ 'dataType' => [ '10' => DataType::TYPE_NULL, '20' => DataType::TYPE_BOOL, '30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel '40' => DataType::TYPE_NUMERIC, // Float '50' => DataType::TYPE_ERROR, '60' => DataType::TYPE_STRING, //'70': // Cell Range //'80': // Array ], ]; /** * Create a new Gnumeric. */ public function __construct() { parent::__construct(); $this->referenceHelper = ReferenceHelper::getInstance(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { $data = null; if (File::testFileNoThrow($filename)) { $data = $this->gzfileGetContents($filename); if (!str_contains($data, self::NAMESPACE_GNM)) { $data = ''; } } return !empty($data); } private static function matchXml(XMLReader $xml, string $expectedLocalName): bool { return $xml->namespaceURI === self::NAMESPACE_GNM && $xml->localName === $expectedLocalName && $xml->nodeType === XMLReader::ELEMENT; } /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * * @return string[] */ public function listWorksheetNames(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an invalid Gnumeric file.'); } $xml = new XMLReader(); $contents = $this->gzfileGetContents($filename); $xml->xml($contents); $xml->setParserProperty(2, true); $worksheetNames = []; while ($xml->read()) { if (self::matchXml($xml, 'SheetName')) { $xml->read(); // Move onto the value node $worksheetNames[] = (string) $xml->value; } elseif (self::matchXml($xml, 'Sheets')) { // break out of the loop once we've got our sheet names rather than parse the entire file break; } } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an invalid Gnumeric file.'); } $xml = new XMLReader(); $contents = $this->gzfileGetContents($filename); $xml->xml($contents); $xml->setParserProperty(2, true); $worksheetInfo = []; while ($xml->read()) { if (self::matchXml($xml, 'Sheet')) { $tmpInfo = [ 'worksheetName' => '', 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, 'sheetState' => Worksheet::SHEETSTATE_VISIBLE, ]; $visibility = $xml->getAttribute('Visibility'); if ((string) $visibility === self::GNM_SHEET_VISIBILITY_HIDDEN) { $tmpInfo['sheetState'] = Worksheet::SHEETSTATE_HIDDEN; } while ($xml->read()) { if (self::matchXml($xml, 'Name')) { $xml->read(); // Move onto the value node $tmpInfo['worksheetName'] = (string) $xml->value; } elseif (self::matchXml($xml, 'MaxCol')) { $xml->read(); // Move onto the value node $tmpInfo['lastColumnIndex'] = (int) $xml->value; $tmpInfo['totalColumns'] = (int) $xml->value + 1; } elseif (self::matchXml($xml, 'MaxRow')) { $xml->read(); // Move onto the value node $tmpInfo['totalRows'] = (int) $xml->value + 1; break; } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1, true); $worksheetInfo[] = $tmpInfo; } } return $worksheetInfo; } private function gzfileGetContents(string $filename): string { $data = ''; $contents = @file_get_contents($filename); if ($contents !== false) { if (str_starts_with($contents, "\x1f\x8b")) { // Check if gzlib functions are available if (function_exists('gzdecode')) { $contents = @gzdecode($contents); if ($contents !== false) { $data = $contents; } } } else { $data = $contents; } } if ($data !== '') { $data = $this->getSecurityScannerOrThrow()->scan($data); } return $data; } /** @return mixed[] */ public static function gnumericMappings(): array { return array_merge(self::$mappings, Styles::$mappings); } private function processComments(SimpleXMLElement $sheet): void { if ((!$this->readDataOnly) && (isset($sheet->Objects))) { foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) { $commentAttributes = $comment->attributes(); // Only comment objects are handled at the moment if ($commentAttributes && $commentAttributes->Text) { $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound) ->setAuthor((string) $commentAttributes->Author) ->setText($this->parseRichText((string) $commentAttributes->Text)); } } } } private static function testSimpleXml(mixed $value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file into Spreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { $this->spreadsheet = $spreadsheet; File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an invalid Gnumeric file.'); } $gFileData = $this->gzfileGetContents($filename); /** @var XmlScanner */ $securityScanner = $this->securityScanner; $xml2 = simplexml_load_string($securityScanner->scan($gFileData)); $xml = self::testSimpleXml($xml2); $gnmXML = $xml->children(self::NAMESPACE_GNM); (new Properties($this->spreadsheet))->readProperties($xml, $gnmXML); $worksheetID = 0; $sheetCreated = false; foreach ($gnmXML->Sheets->Sheet as $sheetOrNull) { $sheet = self::testSimpleXml($sheetOrNull); $worksheetName = (string) $sheet->Name; if (is_array($this->loadSheetsOnly) && !in_array($worksheetName, $this->loadSheetsOnly, true)) { continue; } $maxRow = $maxCol = 0; // Create new Worksheet $this->spreadsheet->createSheet(); $sheetCreated = true; $this->spreadsheet->setActiveSheetIndex($worksheetID); // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet // name in line with the formula, not the reverse $this->spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); $visibility = $sheet->attributes()['Visibility'] ?? self::GNM_SHEET_VISIBILITY_VISIBLE; if ((string) $visibility !== self::GNM_SHEET_VISIBILITY_VISIBLE) { $this->spreadsheet->getActiveSheet()->setSheetState(Worksheet::SHEETSTATE_HIDDEN); } if (!$this->readDataOnly) { (new PageSetup($this->spreadsheet)) ->printInformation($sheet) ->sheetMargins($sheet); } foreach ($sheet->Cells->Cell as $cellOrNull) { $cell = self::testSimpleXml($cellOrNull); $cellAttributes = self::testSimpleXml($cell->attributes()); $row = (int) $cellAttributes->Row + 1; $column = (int) $cellAttributes->Col; $maxRow = max($maxRow, $row); $maxCol = max($maxCol, $column); $column = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) { continue; } $this->loadCell($cell, $worksheetName, $cellAttributes, $column, $row); } if ($sheet->Styles !== null) { (new Styles($this->spreadsheet, $this->readDataOnly))->read($sheet, $maxRow, $maxCol); } $this->processComments($sheet); $this->processColumnWidths($sheet, $maxCol); $this->processRowHeights($sheet, $maxRow); $this->processMergedCells($sheet); $this->processAutofilter($sheet); $this->setSelectedCells($sheet); ++$worksheetID; } if ($this->createBlankSheetIfNoneRead && !$sheetCreated) { $this->spreadsheet->createSheet(); } $this->processDefinedNames($gnmXML); $this->setSelectedSheet($gnmXML); // Return return $this->spreadsheet; } private function setSelectedSheet(SimpleXMLElement $gnmXML): void { if (isset($gnmXML->UIData)) { $attributes = self::testSimpleXml($gnmXML->UIData->attributes()); $selectedSheet = (int) $attributes['SelectedTab']; $this->spreadsheet->setActiveSheetIndex($selectedSheet); } } private function setSelectedCells(?SimpleXMLElement $sheet): void { if ($sheet !== null && isset($sheet->Selections)) { foreach ($sheet->Selections as $selection) { $startCol = (int) ($selection->StartCol ?? 0); $startRow = (int) ($selection->StartRow ?? 0) + 1; $endCol = (int) ($selection->EndCol ?? $startCol); $endRow = (int) ($selection->endRow ?? 0) + 1; $startColumn = Coordinate::stringFromColumnIndex($startCol + 1); $endColumn = Coordinate::stringFromColumnIndex($endCol + 1); $startCell = "{$startColumn}{$startRow}"; $endCell = "{$endColumn}{$endRow}"; $selectedRange = $startCell . (($endCell !== $startCell) ? ':' . $endCell : ''); $this->spreadsheet->getActiveSheet()->setSelectedCell($selectedRange); break; } } } private function processMergedCells(?SimpleXMLElement $sheet): void { // Handle Merged Cells in this worksheet if ($sheet !== null && isset($sheet->MergedRegions)) { foreach ($sheet->MergedRegions->Merge as $mergeCells) { if (str_contains((string) $mergeCells, ':')) { $this->spreadsheet->getActiveSheet()->mergeCells($mergeCells, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } } private function processAutofilter(?SimpleXMLElement $sheet): void { if ($sheet !== null && isset($sheet->Filters)) { foreach ($sheet->Filters->Filter as $autofilter) { $attributes = $autofilter->attributes(); if (isset($attributes['Area'])) { $this->spreadsheet->getActiveSheet()->setAutoFilter((string) $attributes['Area']); } } } } private function setColumnWidth(int $whichColumn, float $defaultWidth): void { $this->spreadsheet->getActiveSheet() ->getColumnDimension( Coordinate::stringFromColumnIndex($whichColumn + 1) ) ->setWidth($defaultWidth); } private function setColumnInvisible(int $whichColumn): void { $this->spreadsheet->getActiveSheet() ->getColumnDimension( Coordinate::stringFromColumnIndex($whichColumn + 1) ) ->setVisible(false); } private function processColumnLoop(int $whichColumn, int $maxCol, ?SimpleXMLElement $columnOverride, float $defaultWidth): int { $columnOverride = self::testSimpleXml($columnOverride); $columnAttributes = self::testSimpleXml($columnOverride->attributes()); $column = $columnAttributes['No']; $columnWidth = ((float) $columnAttributes['Unit']) / 5.4; $hidden = (isset($columnAttributes['Hidden'])) && ((string) $columnAttributes['Hidden'] == '1'); $columnCount = (int) ($columnAttributes['Count'] ?? 1); while ($whichColumn < $column) { $this->setColumnWidth($whichColumn, $defaultWidth); ++$whichColumn; } while (($whichColumn < ($column + $columnCount)) && ($whichColumn <= $maxCol)) { $this->setColumnWidth($whichColumn, $columnWidth); if ($hidden) { $this->setColumnInvisible($whichColumn); } ++$whichColumn; } return $whichColumn; } private function processColumnWidths(?SimpleXMLElement $sheet, int $maxCol): void { if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Cols))) { // Column Widths $defaultWidth = 0; $columnAttributes = $sheet->Cols->attributes(); if ($columnAttributes !== null) { $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; } $whichColumn = 0; foreach ($sheet->Cols->ColInfo as $columnOverride) { $whichColumn = $this->processColumnLoop($whichColumn, $maxCol, $columnOverride, $defaultWidth); } while ($whichColumn <= $maxCol) { $this->setColumnWidth($whichColumn, $defaultWidth); ++$whichColumn; } } } private function setRowHeight(int $whichRow, float $defaultHeight): void { $this->spreadsheet ->getActiveSheet() ->getRowDimension($whichRow) ->setRowHeight($defaultHeight); } private function setRowInvisible(int $whichRow): void { $this->spreadsheet ->getActiveSheet() ->getRowDimension($whichRow) ->setVisible(false); } private function processRowLoop(int $whichRow, int $maxRow, ?SimpleXMLElement $rowOverride, float $defaultHeight): int { $rowOverride = self::testSimpleXml($rowOverride); $rowAttributes = self::testSimpleXml($rowOverride->attributes()); $row = $rowAttributes['No']; $rowHeight = (float) $rowAttributes['Unit']; $hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1'); $rowCount = (int) ($rowAttributes['Count'] ?? 1); while ($whichRow < $row) { ++$whichRow; $this->setRowHeight($whichRow, $defaultHeight); } while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) { ++$whichRow; $this->setRowHeight($whichRow, $rowHeight); if ($hidden) { $this->setRowInvisible($whichRow); } } return $whichRow; } private function processRowHeights(?SimpleXMLElement $sheet, int $maxRow): void { if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Rows))) { // Row Heights $defaultHeight = 0; $rowAttributes = $sheet->Rows->attributes(); if ($rowAttributes !== null) { $defaultHeight = (float) $rowAttributes['DefaultSizePts']; } $whichRow = 0; foreach ($sheet->Rows->RowInfo as $rowOverride) { $whichRow = $this->processRowLoop($whichRow, $maxRow, $rowOverride, $defaultHeight); } // never executed, I can't figure out any circumstances // under which it would be executed, and, even if // such exist, I'm not convinced this is needed. //while ($whichRow < $maxRow) { // ++$whichRow; // $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow)->setRowHeight($defaultHeight); //} } } private function processDefinedNames(?SimpleXMLElement $gnmXML): void { // Loop through definedNames (global named ranges) if ($gnmXML !== null && isset($gnmXML->Names)) { foreach ($gnmXML->Names->Name as $definedName) { $name = (string) $definedName->name; $value = (string) $definedName->value; if (stripos($value, '#REF!') !== false || empty($value)) { continue; } $value = str_replace("\\'", "''", $value); [$worksheetName] = Worksheet::extractSheetTitle($value, true, true); $worksheet = $this->spreadsheet->getSheetByName($worksheetName); // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet if ($worksheet !== null) { $this->spreadsheet->addDefinedName(DefinedName::createInstance($name, $worksheet, $value)); } } } } private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } private function loadCell( SimpleXMLElement $cell, string $worksheetName, SimpleXMLElement $cellAttributes, string $column, int $row ): void { $ValueType = $cellAttributes->ValueType; $ExprID = (string) $cellAttributes->ExprID; $rows = (int) ($cellAttributes->Rows ?? 0); $cols = (int) ($cellAttributes->Cols ?? 0); $type = DataType::TYPE_FORMULA; $isArrayFormula = ($rows > 0 && $cols > 0); $arrayFormulaRange = $isArrayFormula ? $this->getArrayFormulaRange($column, $row, $cols, $rows) : null; if ($ExprID > '') { if (((string) $cell) > '') { // Formula $this->expressions[$ExprID] = [ 'column' => (int) $cellAttributes->Col, 'row' => (int) $cellAttributes->Row, 'formula' => (string) $cell, ]; } else { // Shared Formula $expression = $this->expressions[$ExprID]; $cell = $this->referenceHelper->updateFormulaReferences( $expression['formula'], 'A1', $cellAttributes->Col - $expression['column'], $cellAttributes->Row - $expression['row'], $worksheetName ); } $type = DataType::TYPE_FORMULA; } elseif ($isArrayFormula === false) { $vtype = (string) $ValueType; if (array_key_exists($vtype, self::$mappings['dataType'])) { $type = self::$mappings['dataType'][$vtype]; } if ($vtype === '20') { // Boolean $cell = $cell == 'TRUE'; } } $this->spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit((string) $cell, $type); if ($arrayFormulaRange === null) { $this->spreadsheet->getActiveSheet()->getCell($column . $row)->setFormulaAttributes(null); } else { $this->spreadsheet->getActiveSheet()->getCell($column . $row)->setFormulaAttributes(['t' => 'array', 'ref' => $arrayFormulaRange]); } if (isset($cellAttributes->ValueFormat)) { $this->spreadsheet->getActiveSheet()->getCell($column . $row) ->getStyle()->getNumberFormat() ->setFormatCode((string) $cellAttributes->ValueFormat); } } private function getArrayFormulaRange(string $column, int $row, int $cols, int $rows): string { $arrayFormulaRange = $column . $row; $arrayFormulaRange .= ':' . Coordinate::stringFromColumnIndex( Coordinate::columnIndexFromString($column) + $cols - 1 ) . (string) ($row + $rows - 1); return $arrayFormulaRange; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Html.php ================================================ [ 'font' => [ 'bold' => true, 'size' => 24, ], ], // Bold, 24pt 'h2' => [ 'font' => [ 'bold' => true, 'size' => 18, ], ], // Bold, 18pt 'h3' => [ 'font' => [ 'bold' => true, 'size' => 13.5, ], ], // Bold, 13.5pt 'h4' => [ 'font' => [ 'bold' => true, 'size' => 12, ], ], // Bold, 12pt 'h5' => [ 'font' => [ 'bold' => true, 'size' => 10, ], ], // Bold, 10pt 'h6' => [ 'font' => [ 'bold' => true, 'size' => 7.5, ], ], // Bold, 7.5pt 'a' => [ 'font' => [ 'underline' => true, 'color' => [ 'argb' => Color::COLOR_BLUE, ], ], ], // Blue underlined 'hr' => [ 'borders' => [ 'bottom' => [ 'borderStyle' => Border::BORDER_THIN, 'color' => [ Color::COLOR_BLACK, ], ], ], ], // Bottom border 'strong' => [ 'font' => [ 'bold' => true, ], ], // Bold 'b' => [ 'font' => [ 'bold' => true, ], ], // Bold 'i' => [ 'font' => [ 'italic' => true, ], ], // Italic 'em' => [ 'font' => [ 'italic' => true, ], ], // Italic ]; /** @var array */ protected array $rowspan = []; /** * Default setting uses current setting of libxml_use_internal_errors. * It will probably change to 'true' in a future release. */ protected ?bool $suppressLoadWarnings = null; /** @var LibXMLError[] */ protected array $libxmlMessages = []; /** * Suppress load warning messages, keeping them available * in $this->libxmlMessages(). */ public function setSuppressLoadWarnings(?bool $suppressLoadWarnings): self { $this->suppressLoadWarnings = $suppressLoadWarnings; return $this; } /** @return LibXMLError[] */ public function getLibxmlMessages(): array { return $this->libxmlMessages; } /** * Create a new HTML Reader instance. */ public function __construct() { parent::__construct(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Validate that the current file is an HTML file. */ public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); } catch (Exception) { return false; } $beginning = preg_replace(self::STARTS_WITH_BOM, '', $this->readBeginning()) ?? ''; $startWithTag = self::startsWithTag($beginning); $containsTags = self::containsTags($beginning); $endsWithTag = self::endsWithTag($this->readEnding()); fclose($this->fileHandle); return $startWithTag && $containsTags && $endsWithTag; } private function readBeginning(): string { fseek($this->fileHandle, 0); return (string) fread($this->fileHandle, self::TEST_SAMPLE_SIZE); } private function readEnding(): string { $meta = stream_get_meta_data($this->fileHandle); // Phpstan incorrectly flags following line for Php8.2-, corrected in 8.3 $filename = $meta['uri']; //@phpstan-ignore-line clearstatcache(true, $filename); $size = (int) filesize($filename); if ($size === 0) { return ''; } $blockSize = self::TEST_SAMPLE_SIZE; if ($size < $blockSize) { $blockSize = $size; } fseek($this->fileHandle, $size - $blockSize); return (string) fread($this->fileHandle, $blockSize); } private static function startsWithTag(string $data): bool { return str_starts_with(trim($data), '<'); } private static function endsWithTag(string $data): bool { return str_ends_with(trim($data), '>'); } private static function containsTags(string $data): bool { return strlen($data) !== strlen(strip_tags($data)); } /** * Loads Spreadsheet from file. */ public function loadSpreadsheetFromFile(string $filename): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Data Array used for testing only, should write to * Spreadsheet object on completion of tests. * * @deprecated 5.4.0 No replacement. * * @var mixed[][] */ protected array $dataArray = []; protected int $tableLevel = 0; /** @var string[] */ protected array $nestedColumn = ['A']; protected function setTableStartColumn(string $column): string { if ($this->tableLevel == 0) { $column = 'A'; } ++$this->tableLevel; $this->nestedColumn[$this->tableLevel] = $column; return $this->nestedColumn[$this->tableLevel]; } protected function getTableStartColumn(): string { return $this->nestedColumn[$this->tableLevel]; } protected function releaseTableStartColumn(): string { --$this->tableLevel; return array_pop($this->nestedColumn) ?? ''; } /** * Flush cell. * * @param string[] $attributeArray * * @param-out string $cellContentx */ protected function flushCell(Worksheet $sheet, string $column, int|string $row, mixed &$cellContentx, array $attributeArray): void { $cellContent = $cellContentx; if (is_string($cellContent)) { // Simple String content if (trim($cellContent) > '') { // Only actually write it if there's content in the string // Write to worksheet to be done here... // ... we return the cell, so we can mess about with styles more easily // Set cell value explicitly if there is data-type attribute if (isset($attributeArray['data-checkbox'])) { $sheet->getStyle($column . $row) ->setCheckBox(true); } if (isset($attributeArray['data-type'])) { $datatype = $attributeArray['data-type']; if (in_array($datatype, [DataType::TYPE_STRING, DataType::TYPE_STRING2, DataType::TYPE_INLINE])) { //Prevent to Excel treat string with beginning equal sign or convert big numbers to scientific number if (str_starts_with($cellContent, '=')) { $sheet->getCell($column . $row) ->getStyle() ->setQuotePrefix(true); } } if ($datatype === DataType::TYPE_BOOL) { // This is the case where we can set cellContent to bool rather than string if ($cellContent === '☑') { $cellContent = true; $sheet->getStyle($column . $row) ->setCheckBox(true); } elseif ($cellContent === '☐') { $cellContent = false; $sheet->getStyle($column . $row) ->setCheckBox(true); } else { $cellContent = self::convertBoolean($cellContent); if (!is_bool($cellContent)) { $attributeArray['data-type'] = DataType::TYPE_STRING; } } } //catching the Exception and ignoring the invalid data types $hyperlink = $sheet->hyperlinkExists($column . $row) ? $sheet->getHyperlink($column . $row) : null; try { if (isset($attributeArray['data-formula'])) { $sheet->setCellValueExplicit($column . $row, $attributeArray['data-formula'], DataType::TYPE_FORMULA); $sheet->getCell($column . $row) ->setCalculatedValue( $cellContent ); } else { $sheet->setCellValueExplicit($column . $row, $cellContent, $attributeArray['data-type']); } } catch (SpreadsheetException) { $sheet->setCellValue($column . $row, $cellContent); } $sheet->setHyperlink($column . $row, $hyperlink); } else { $hyperlink = null; if ($sheet->hyperlinkExists($column . $row)) { $hyperlink = $sheet->getHyperlink($column . $row); } $sheet->setCellValue($column . $row, $cellContent); $sheet->setHyperlink($column . $row, $hyperlink); } $this->dataArray[$row][$column] = $cellContent; // @phpstan-ignore-line } } else { // We have a Rich Text run. // I don't actually see any way to reach this line. // TODO // @phpstan-ignore-next-line $this->dataArray[$row][$column] = 'RICH TEXT: ' . StringHelper::convertToString($cellContent); // @codeCoverageIgnore } $cellContentx = ''; } /** @var array> */ private static array $falseTrueArray = []; private static function convertBoolean(?string $cellContent): bool|string { if ($cellContent === '1') { return true; } if ($cellContent === '0' || $cellContent === '' || $cellContent === null) { return false; } if (empty(self::$falseTrueArray)) { $calc = Calculation::getInstance(); self::$falseTrueArray = $calc->getFalseTrueArray(); } if (in_array(mb_strtoupper($cellContent), self::$falseTrueArray[1], true)) { return true; } if (in_array(mb_strtoupper($cellContent), self::$falseTrueArray[0], true)) { return false; } return $cellContent; } private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void { $attributeArray = []; /** @var DOMAttr $attribute */ foreach (($child->attributes ?? []) as $attribute) { $attributeArray[$attribute->name] = $attribute->value; } if ($child->nodeName === 'body') { $row = 1; $column = 'A'; $cellContent = ''; $this->tableLevel = 0; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementTitle($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementTitle(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'title') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); try { $sheet->setTitle($cellContent, true, true); $sheet->getParent()?->getProperties()?->setTitle($cellContent); } catch (SpreadsheetException) { // leave default title if too long or illegal chars } $cellContent = ''; } else { $this->processDomElementSpanEtc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private const SPAN_ETC = ['span', 'div', 'font', 'i', 'em', 'strong', 'b']; /** @param string[] $attributeArray */ private function processDomElementSpanEtc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if (in_array((string) $child->nodeName, self::SPAN_ETC, true)) { if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') { $sheet->getComment($column . $row) ->getText() ->createTextRun($child->textContent); if (isset($attributeArray['dir']) && $attributeArray['dir'] === 'rtl') { $sheet->getComment($column . $row)->setTextboxDirection(Comment::TEXTBOX_DIRECTION_RTL); } if (isset($attributeArray['style'])) { $alignStyle = $attributeArray['style']; if (preg_match('/\btext-align:\s*(left|right|center|justify)\b/', (string) $alignStyle, $matches) === 1) { $sheet->getComment($column . $row)->setAlignment($matches[1]); } } } else { $this->processDomElement($child, $sheet, $row, $column, $cellContent); } if (isset(self::FORMATS[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray(self::FORMATS[$child->nodeName]); } } else { $this->processDomElementHr($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementHr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'hr') { $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); ++$row; $sheet->getStyle($column . $row)->applyFromArray(self::FORMATS[$child->nodeName]); ++$row; } // fall through to br $this->processDomElementBr($sheet, $row, $column, $cellContent, $child, $attributeArray); } /** @param string[] $attributeArray */ private function processDomElementBr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'br' || $child->nodeName === 'hr') { if ($this->tableLevel > 0) { // If we're inside a table, replace with a newline and set the cell to wrap $cellContent .= "\n"; $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); } else { // Otherwise flush our existing content and move the row cursor on $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); ++$row; } } else { $this->processDomElementA($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementA(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'a') { foreach ($attributeArray as $attributeName => $attributeValue) { switch ($attributeName) { case 'href': $sheet->getCell($column . $row)->getHyperlink()->setUrl($attributeValue); $sheet->getStyle($column . $row)->applyFromArray(self::FORMATS[$child->nodeName]); break; case 'class': if ($attributeValue === 'comment-indicator') { break; // Ignore - it's just a red square. } } } // no idea why this should be needed //$cellContent .= ' '; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementH1Etc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private const H1_ETC = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p']; /** @param string[] $attributeArray */ private function processDomElementH1Etc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if (in_array((string) $child->nodeName, self::H1_ETC, true)) { if ($this->tableLevel > 0) { // If we're inside a table, replace with a newline $cellContent .= $cellContent ? "\n" : ''; $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); ++$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); if (isset(self::FORMATS[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray(self::FORMATS[$child->nodeName]); } ++$row; $column = 'A'; } } else { $this->processDomElementLi($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementLi(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'li') { if ($this->tableLevel > 0) { // If we're inside a table, replace with a newline $cellContent .= $cellContent ? "\n" : ''; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); } ++$row; $this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); $column = 'A'; } } else { $this->processDomElementImg($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementImg(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'img') { $this->insertImage($sheet, $column, $row, $attributeArray); } else { $this->processDomElementTable($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private string $currentColumn = 'A'; /** @param string[] $attributeArray */ private function processDomElementTable(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'table') { if (isset($attributeArray['class'])) { $classes = explode(' ', $attributeArray['class']); $sheet->setShowGridlines(in_array('gridlines', $classes, true)); $sheet->setPrintGridlines(in_array('gridlinesp', $classes, true)); } if (isset($attributeArray['data-printarea'])) { $sheet->getPageSetup() ->setPrintArea($attributeArray['data-printarea']); } if ('rtl' === ($attributeArray['dir'] ?? '')) { $sheet->setRightToLeft(true); } $this->currentColumn = 'A'; $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); $column = $this->setTableStartColumn($column); if ($this->tableLevel > 1 && $row > 1) { --$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); $column = $this->releaseTableStartColumn(); if ($this->tableLevel > 1) { StringHelper::stringIncrement($column); } else { ++$row; } } else { $this->processDomElementTr($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementTr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'col') { $this->applyInlineStyle($sheet, -1, $this->currentColumn, $attributeArray); StringHelper::stringIncrement($this->currentColumn); } elseif ($child->nodeName === 'tr') { $column = $this->getTableStartColumn(); $cellContent = ''; $this->processDomElement($child, $sheet, $row, $column, $cellContent); if (isset($attributeArray['height'])) { $sheet->getRowDimension($row)->setRowHeight((float) $attributeArray['height']); } ++$row; } else { $this->processDomElementThTdOther($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementThTdOther(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName !== 'td' && $child->nodeName !== 'th') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementThTd($sheet, $row, $column, $cellContent, $child, $attributeArray); } } /** @param string[] $attributeArray */ private function processDomElementBgcolor(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['bgcolor'])) { $sheet->getStyle("$column$row")->applyFromArray( [ 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => $this->getStyleColor($attributeArray['bgcolor'])], ], ] ); } } /** @param string[] $attributeArray */ private function processDomElementWidth(Worksheet $sheet, string $column, array $attributeArray): void { if (isset($attributeArray['width'])) { $sheet->getColumnDimension($column)->setWidth((new CssDimension($attributeArray['width']))->width()); } } /** @param string[] $attributeArray */ private function processDomElementHeight(Worksheet $sheet, int $row, array $attributeArray): void { if (isset($attributeArray['height'])) { $sheet->getRowDimension($row)->setRowHeight((new CssDimension($attributeArray['height']))->height()); } } /** @param string[] $attributeArray */ private function processDomElementAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['align'])) { $sheet->getStyle($column . $row)->getAlignment()->setHorizontal($attributeArray['align']); } } /** @param string[] $attributeArray */ private function processDomElementVAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['valign'])) { $sheet->getStyle($column . $row)->getAlignment()->setVertical($attributeArray['valign']); } } /** @param string[] $attributeArray */ private function processDomElementDataFormat(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['data-format'])) { $sheet->getStyle($column . $row)->getNumberFormat()->setFormatCode($attributeArray['data-format']); } } /** @param string[] $attributeArray */ private function processDomElementThTd(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { while (isset($this->rowspan[$column . $row])) { $temp = (string) $column; $column = StringHelper::stringIncrement($temp); } $this->processDomElement($child, $sheet, $row, $column, $cellContent); // apply inline style $this->applyInlineStyle($sheet, $row, $column, $attributeArray); /** @var string $cellContent */ $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); $this->processDomElementBgcolor($sheet, $row, $column, $attributeArray); $this->processDomElementWidth($sheet, $column, $attributeArray); $this->processDomElementHeight($sheet, $row, $attributeArray); $this->processDomElementAlign($sheet, $row, $column, $attributeArray); $this->processDomElementVAlign($sheet, $row, $column, $attributeArray); $this->processDomElementDataFormat($sheet, $row, $column, $attributeArray); if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { //create merging rowspan and colspan $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { StringHelper::stringIncrement($columnTo); } $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { $this->rowspan[$value] = true; } $sheet->mergeCells($range); $column = $columnTo; } elseif (isset($attributeArray['rowspan'])) { //create merging rowspan $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { $this->rowspan[$value] = true; } $sheet->mergeCells($range); } elseif (isset($attributeArray['colspan'])) { //create merging colspan $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { StringHelper::stringIncrement($columnTo); } $sheet->mergeCells($column . $row . ':' . $columnTo . $row); $column = $columnTo; } StringHelper::stringIncrement($column); } protected function processDomElement(DOMNode $element, Worksheet $sheet, int &$row, string &$column, string &$cellContent): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { $domText = (string) preg_replace('/\s+/', ' ', trim($child->nodeValue ?? '')); if ($domText === "\u{a0}") { $domText = ''; } // simply append the text if the cell content is a plain text string $cellContent .= $domText; // but if we have a rich text run instead, we need to append it correctly // TODO } elseif ($child instanceof DOMElement) { $this->processDomElementBody($sheet, $row, $column, $cellContent, $child); } } } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { // Validate if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid HTML file.'); } // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object if (is_bool($this->suppressLoadWarnings)) { $useErrors = libxml_use_internal_errors($this->suppressLoadWarnings); } else { $useErrors = null; } try { $convert = $this->getSecurityScannerOrThrow()->scanFile($filename); $convert = static::replaceNonAsciiIfNeeded($convert); $loaded = ($convert === null) ? false : $dom->loadHTML($convert); } catch (Throwable $e) { $loaded = false; } finally { $this->libxmlMessages = libxml_get_errors(); if (is_bool($useErrors)) { libxml_use_internal_errors($useErrors); } } if ($loaded === false) { throw new Exception('Failed to load file ' . $filename . ' as a DOM Document', 0, $e ?? null); } self::loadProperties($dom, $spreadsheet); return $this->loadDocument($dom, $spreadsheet); } private static function loadProperties(DOMDocument $dom, Spreadsheet $spreadsheet): void { $properties = $spreadsheet->getProperties(); foreach ($dom->getElementsByTagName('meta') as $meta) { $metaContent = (string) $meta->getAttribute('content'); if ($metaContent !== '') { $metaName = (string) $meta->getAttribute('name'); switch ($metaName) { case 'author': $properties->setCreator($metaContent); break; case 'category': $properties->setCategory($metaContent); break; case 'company': $properties->setCompany($metaContent); break; case 'created': $properties->setCreated($metaContent); break; case 'description': $properties->setDescription($metaContent); break; case 'keywords': $properties->setKeywords($metaContent); break; case 'lastModifiedBy': $properties->setLastModifiedBy($metaContent); break; case 'manager': $properties->setManager($metaContent); break; case 'modified': $properties->setModified($metaContent); break; case 'subject': $properties->setSubject($metaContent); break; case 'title': $properties->setTitle($metaContent); break; case 'viewport': $properties->setViewport($metaContent); break; default: if (preg_match('/^custom[.](bool|date|float|int|string)[.](.+)$/', $metaName, $matches) === 1) { match ($matches[1]) { 'bool' => $properties->setCustomProperty($matches[2], (bool) $metaContent, Properties::PROPERTY_TYPE_BOOLEAN), 'float' => $properties->setCustomProperty($matches[2], (float) $metaContent, Properties::PROPERTY_TYPE_FLOAT), 'int' => $properties->setCustomProperty($matches[2], (int) $metaContent, Properties::PROPERTY_TYPE_INTEGER), 'date' => $properties->setCustomProperty($matches[2], $metaContent, Properties::PROPERTY_TYPE_DATE), // string default => $properties->setCustomProperty($matches[2], $metaContent, Properties::PROPERTY_TYPE_STRING), }; } } } } if (!empty($dom->baseURI)) { $properties->setHyperlinkBase($dom->baseURI); } } /** @param string[] $matches */ private static function replaceNonAscii(array $matches): string { return '&#' . mb_ord($matches[0], 'UTF-8') . ';'; } /** @internal */ protected static function replaceNonAsciiIfNeeded(string $convert): ?string { if (preg_match(self::STARTS_WITH_BOM, $convert) !== 1 && preg_match(self::DECLARES_CHARSET, $convert) !== 1) { $lowend = "\u{80}"; $highend = "\u{10ffff}"; $regexp = "/[$lowend-$highend]/u"; /** @var callable $callback */ $callback = [self::class, 'replaceNonAscii']; $convert = preg_replace_callback($regexp, $callback, $convert); } return $convert; } /** * Spreadsheet from content. */ public function loadFromString(string $content, ?Spreadsheet $spreadsheet = null): Spreadsheet { // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object if (is_bool($this->suppressLoadWarnings)) { $useErrors = libxml_use_internal_errors($this->suppressLoadWarnings); } else { $useErrors = null; } try { $convert = $this->getSecurityScannerOrThrow()->scan($content); $convert = static::replaceNonAsciiIfNeeded($convert); $loaded = ($convert === null) ? false : $dom->loadHTML($convert); } catch (Throwable $e) { $loaded = false; } finally { $this->libxmlMessages = libxml_get_errors(); if (is_bool($useErrors)) { libxml_use_internal_errors($useErrors); } } if ($loaded === false) { throw new Exception('Failed to load content as a DOM Document', 0, $e ?? null); } $spreadsheet = $spreadsheet ?? $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); self::loadProperties($dom, $spreadsheet); return $this->loadDocument($dom, $spreadsheet); } /** * Loads PhpSpreadsheet from DOMDocument into PhpSpreadsheet instance. */ private function loadDocument(DOMDocument $document, Spreadsheet $spreadsheet): Spreadsheet { while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); // Discard white space $document->preserveWhiteSpace = false; $row = 0; $column = 'A'; $content = ''; $this->rowspan = []; $this->processDomElement($document, $spreadsheet->getActiveSheet(), $row, $column, $content); // Return return $spreadsheet; } /** * Get sheet index. */ public function getSheetIndex(): int { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex(int $sheetIndex): static { $this->sheetIndex = $sheetIndex; return $this; } /** * Apply inline css inline style. * * NOTES : * Currently only intended for td & th element, * and only takes 'background-color' and 'color'; property with HEX color * * TODO : * - Implement to other properties, such as border * * @param string[] $attributeArray */ private function applyInlineStyle(Worksheet &$sheet, int $row, string $column, array $attributeArray): void { if (!isset($attributeArray['style'])) { return; } if ($row <= 0 || $column === '') { $cellStyle = new Style(); } elseif (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { StringHelper::stringIncrement($columnTo); } $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); $cellStyle = $sheet->getStyle($range); } elseif (isset($attributeArray['rowspan'])) { $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); $cellStyle = $sheet->getStyle($range); } elseif (isset($attributeArray['colspan'])) { $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { StringHelper::stringIncrement($columnTo); } $range = $column . $row . ':' . $columnTo . $row; $cellStyle = $sheet->getStyle($range); } else { $cellStyle = $sheet->getStyle($column . $row); } // add color styles (background & text) from dom element,currently support : td & th, using ONLY inline css style with RGB color $styles = explode(';', $attributeArray['style']); foreach ($styles as $st) { $value = explode(':', $st); $styleName = trim($value[0]); $styleValue = isset($value[1]) ? trim($value[1]) : null; $styleValueString = (string) $styleValue; if (!$styleName) { continue; } switch ($styleName) { case 'background': case 'background-color': $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; } $cellStyle->applyFromArray(['fill' => ['fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => $styleColor]]]); break; case 'color': $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; } $cellStyle->applyFromArray(['font' => ['color' => ['rgb' => $styleColor]]]); break; case 'border': $this->setBorderStyle($cellStyle, $styleValueString, 'allBorders'); break; case 'border-top': $this->setBorderStyle($cellStyle, $styleValueString, 'top'); break; case 'border-bottom': $this->setBorderStyle($cellStyle, $styleValueString, 'bottom'); break; case 'border-left': $this->setBorderStyle($cellStyle, $styleValueString, 'left'); break; case 'border-right': $this->setBorderStyle($cellStyle, $styleValueString, 'right'); break; case 'font-size': $cellStyle->getFont()->setSize( (float) $styleValue ); break; case 'direction': if ($styleValue === 'rtl') { $cellStyle->getAlignment() ->setReadOrder(Alignment::READORDER_RTL); } elseif ($styleValue === 'ltr') { $cellStyle->getAlignment() ->setReadOrder(Alignment::READORDER_LTR); } break; case 'font-weight': if ($styleValue === 'bold' || $styleValue >= 500) { $cellStyle->getFont()->setBold(true); } break; case 'font-style': if ($styleValue === 'italic') { $cellStyle->getFont()->setItalic(true); } break; case 'font-family': $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString)); break; case 'text-decoration': switch ($styleValue) { case 'underline': $cellStyle->getFont()->setUnderline(Font::UNDERLINE_SINGLE); break; case 'line-through': $cellStyle->getFont()->setStrikethrough(true); break; } break; case 'text-align': $cellStyle->getAlignment()->setHorizontal($styleValueString); break; case 'vertical-align': $cellStyle->getAlignment()->setVertical($styleValueString); break; case 'width': if ($column !== '') { $sheet->getColumnDimension($column)->setWidth( (new CssDimension($styleValue ?? ''))->width() ); } break; case 'height': if ($row > 0) { $sheet->getRowDimension($row)->setRowHeight( (new CssDimension($styleValue ?? ''))->height() ); } break; case 'word-wrap': $cellStyle->getAlignment()->setWrapText( $styleValue === 'break-word' ); break; case 'text-indent': $indentDimension = new CssDimension($styleValueString); $indent = $indentDimension ->toUnit(CssDimension::UOM_PIXELS); $cellStyle->getAlignment()->setIndent( (int) ($indent / Alignment::INDENT_UNITS_TO_PIXELS) ); break; } } } /** * Check if has #, so we can get clean hex. */ public function getStyleColor(?string $value): string { $value = (string) $value; if (str_starts_with($value, '#')) { return substr($value, 1); } return HelperHtml::colourNameLookup($value); } /** @param string[] $attributes */ private function insertImage(Worksheet $sheet, string $column, int $row, array $attributes): void { if (!isset($attributes['src'])) { return; } $styleArray = self::getStyleArray($attributes); $src = $attributes['src']; if (!str_starts_with($src, 'data:')) { $src = urldecode($src); } $width = isset($attributes['width']) ? (float) $attributes['width'] : ($styleArray['width'] ?? null); $height = isset($attributes['height']) ? (float) $attributes['height'] : ($styleArray['height'] ?? null); $name = $attributes['alt'] ?? null; $drawing = new Drawing(); $drawing->setPath($src, false, allowExternal: $this->allowExternalImages, isWhitelisted: $this->isWhitelisted); if ($drawing->getPath() === '') { return; } $drawing->setWorksheet($sheet); $drawing->setCoordinates($column . $row); $drawing->setOffsetX(0); $drawing->setOffsetY(10); $drawing->setResizeProportional(true); if ($name) { $drawing->setName($name); } /** @var null|scalar $width */ /** @var null|scalar $height */ if ($width) { if ($height) { $drawing->setWidthAndHeight((int) $width, (int) $height); } else { $drawing->setWidth((int) $width); } } elseif ($height) { $drawing->setHeight((int) $height); } $sheet->getColumnDimension($column)->setWidth( $drawing->getWidth() / 6 ); $sheet->getRowDimension($row)->setRowHeight( $drawing->getHeight() * 0.9 ); if (isset($styleArray['opacity'])) { $opacity = $styleArray['opacity']; if (is_numeric($opacity)) { $drawing->setOpacity((int) ($opacity * 100000)); } } } /** * @param string[] $attributes * * @return mixed[] */ private static function getStyleArray(array $attributes): array { $styleArray = []; if (isset($attributes['style'])) { $styles = explode(';', $attributes['style']); foreach ($styles as $style) { $value = explode(':', $style); if (count($value) === 2) { $arrayKey = trim($value[0]); $arrayValue = trim($value[1]); if ($arrayKey === 'width') { if (str_ends_with($arrayValue, 'px')) { $arrayValue = (string) (((float) substr($arrayValue, 0, -2))); } else { $arrayValue = (new CssDimension($arrayValue))->toUnit(CssDimension::UOM_PIXELS); } } elseif ($arrayKey === 'height') { if (str_ends_with($arrayValue, 'px')) { $arrayValue = substr($arrayValue, 0, -2); } else { $arrayValue = (new CssDimension($arrayValue))->toUnit(CssDimension::UOM_PIXELS); } } $styleArray[$arrayKey] = $arrayValue; } } } return $styleArray; } private const BORDER_MAPPINGS = [ 'dash-dot' => Border::BORDER_DASHDOT, 'dash-dot-dot' => Border::BORDER_DASHDOTDOT, 'dashed' => Border::BORDER_DASHED, 'dotted' => Border::BORDER_DOTTED, 'double' => Border::BORDER_DOUBLE, 'hair' => Border::BORDER_HAIR, 'medium' => Border::BORDER_MEDIUM, 'medium-dashed' => Border::BORDER_MEDIUMDASHED, 'medium-dash-dot' => Border::BORDER_MEDIUMDASHDOT, 'medium-dash-dot-dot' => Border::BORDER_MEDIUMDASHDOTDOT, 'none' => Border::BORDER_NONE, 'slant-dash-dot' => Border::BORDER_SLANTDASHDOT, 'solid' => Border::BORDER_THIN, 'thick' => Border::BORDER_THICK, ]; /** @return array */ public static function getBorderMappings(): array { return self::BORDER_MAPPINGS; } /** * Map html border style to PhpSpreadsheet border style. */ public function getBorderStyle(string $style): ?string { return self::BORDER_MAPPINGS[$style] ?? null; } private function setBorderStyle(Style $cellStyle, string $styleValue, string $type): void { if (trim($styleValue) === Border::BORDER_NONE) { $borderStyle = Border::BORDER_NONE; $color = null; } else { $borderArray = explode(' ', $styleValue); $borderCount = count($borderArray); if ($borderCount >= 3) { $borderStyle = $borderArray[1]; $color = $borderArray[2]; } else { $borderStyle = $borderArray[0]; $color = $borderArray[1] ?? null; } } $cellStyle->applyFromArray([ 'borders' => [ $type => [ 'borderStyle' => $this->getBorderStyle($borderStyle), 'color' => ['rgb' => $this->getStyleColor($color)], ], ], ]); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { $info = []; $spreadsheet = $this->newSpreadsheet(); $this->loadIntoExisting($filename, $spreadsheet); foreach ($spreadsheet->getAllSheets() as $sheet) { $newEntry = ['worksheetName' => $sheet->getTitle()]; $newEntry['lastColumnLetter'] = $sheet->getHighestDataColumn(); $newEntry['lastColumnIndex'] = Coordinate::columnIndexFromString($sheet->getHighestDataColumn()) - 1; $newEntry['totalRows'] = $sheet->getHighestDataRow(); $newEntry['totalColumns'] = $newEntry['lastColumnIndex'] + 1; $newEntry['sheetState'] = Worksheet::SHEETSTATE_VISIBLE; $info[] = $newEntry; } $spreadsheet->disconnectWorksheets(); return $info; } } ================================================ FILE: src/PhpSpreadsheet/Reader/IReadFilter.php ================================================ readAutoFilters($workbookData); } protected function readAutoFilters(DOMElement $workbookData): void { $databases = $workbookData->getElementsByTagNameNS($this->tableNs, 'database-ranges'); foreach ($databases as $autofilters) { foreach ($autofilters->childNodes as $autofilter) { $autofilterRange = $this->getAttributeValue($autofilter, 'target-range-address'); if ($autofilterRange !== null) { $baseAddress = FormulaTranslator::convertToExcelAddressValue($autofilterRange); $this->spreadsheet->getActiveSheet()->setAutoFilter($baseAddress); } } } } protected function getAttributeValue(?DOMNode $node, string $attributeName): ?string { if ($node !== null && $node->attributes !== null) { $attribute = $node->attributes->getNamedItemNS( $this->tableNs, $attributeName ); if ($attribute !== null) { return $attribute->nodeValue; } } return null; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Ods/BaseLoader.php ================================================ spreadsheet = $spreadsheet; $this->tableNs = $tableNs; } abstract public function read(DOMElement $workbookData): void; } ================================================ FILE: src/PhpSpreadsheet/Reader/Ods/DefinedNames.php ================================================ readDefinedRanges($workbookData); $this->readDefinedExpressions($workbookData); } /** * Read any Named Ranges that are defined in this spreadsheet. */ protected function readDefinedRanges(DOMElement $workbookData): void { $namedRanges = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-range'); foreach ($namedRanges as $definedNameElement) { $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); $range = $definedNameElement->getAttributeNS($this->tableNs, 'cell-range-address'); /** @var non-empty-string $baseAddress */ $baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress); $range = FormulaTranslator::convertToExcelAddressValue($range); $this->addDefinedName($baseAddress, $definedName, $range); } } /** * Read any Named Formulae that are defined in this spreadsheet. */ protected function readDefinedExpressions(DOMElement $workbookData): void { $namedExpressions = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-expression'); foreach ($namedExpressions as $definedNameElement) { $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); $expression = $definedNameElement->getAttributeNS($this->tableNs, 'expression'); /** @var non-empty-string $baseAddress */ $baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress); $expression = substr($expression, strpos($expression, ':=') + 1); $expression = FormulaTranslator::convertToExcelFormulaValue($expression); $this->addDefinedName($baseAddress, $definedName, $expression); } } /** * Assess scope and store the Defined Name. * * @param non-empty-string $baseAddress */ private function addDefinedName(string $baseAddress, string $definedName, string $value): void { [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true, true); $worksheet = $this->spreadsheet->getSheetByName($sheetReference); // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet if ($worksheet !== null) { $this->spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value)); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php ================================================ setDomNameSpaces($styleDom); $this->readPageSettingStyles($styleDom); $this->readStyleMasterLookup($styleDom); } private function setDomNameSpaces(DOMDocument $styleDom): void { $this->officeNs = (string) $styleDom->lookupNamespaceUri('office'); $this->stylesNs = (string) $styleDom->lookupNamespaceUri('style'); $this->stylesFo = (string) $styleDom->lookupNamespaceUri('fo'); $this->tableNs = (string) $styleDom->lookupNamespaceUri('table'); } private function readPageSettingStyles(DOMDocument $styleDom): void { $item0 = $styleDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles')->item(0); $styles = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($this->stylesNs, 'page-layout'); foreach ($styles as $styleSet) { $styleName = $styleSet->getAttributeNS($this->stylesNs, 'name'); $pageLayoutProperties = $styleSet->getElementsByTagNameNS($this->stylesNs, 'page-layout-properties')->item(0); $styleOrientation = $pageLayoutProperties?->getAttributeNS($this->stylesNs, 'print-orientation'); $styleScale = $pageLayoutProperties?->getAttributeNS($this->stylesNs, 'scale-to'); $stylePrintOrder = $pageLayoutProperties?->getAttributeNS($this->stylesNs, 'print-page-order'); $centered = $pageLayoutProperties?->getAttributeNS($this->stylesNs, 'table-centering'); $marginLeft = $pageLayoutProperties?->getAttributeNS($this->stylesFo, 'margin-left'); $marginRight = $pageLayoutProperties?->getAttributeNS($this->stylesFo, 'margin-right'); $marginTop = $pageLayoutProperties?->getAttributeNS($this->stylesFo, 'margin-top'); $marginBottom = $pageLayoutProperties?->getAttributeNS($this->stylesFo, 'margin-bottom'); $header = $styleSet->getElementsByTagNameNS($this->stylesNs, 'header-style')->item(0); $headerProperties = $header?->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')?->item(0); $marginHeader = $headerProperties?->getAttributeNS($this->stylesFo, 'min-height'); $footer = $styleSet->getElementsByTagNameNS($this->stylesNs, 'footer-style')->item(0); $footerProperties = $footer?->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')?->item(0); $marginFooter = $footerProperties?->getAttributeNS($this->stylesFo, 'min-height'); $this->pageLayoutStyles[$styleName] = (object) [ 'orientation' => $styleOrientation ?: PageSetup::ORIENTATION_DEFAULT, 'scale' => $styleScale ?: 100, 'printOrder' => $stylePrintOrder, 'horizontalCentered' => $centered === 'horizontal' || $centered === 'both', 'verticalCentered' => $centered === 'vertical' || $centered === 'both', // margin size is already stored in inches, so no UOM conversion is required 'marginLeft' => (float) ($marginLeft ?? 0.7), 'marginRight' => (float) ($marginRight ?? 0.7), 'marginTop' => (float) ($marginTop ?? 0.3), 'marginBottom' => (float) ($marginBottom ?? 0.3), 'marginHeader' => (float) ($marginHeader ?? 0.45), 'marginFooter' => (float) ($marginFooter ?? 0.45), ]; } } private function readStyleMasterLookup(DOMDocument $styleDom): void { $item0 = $styleDom->getElementsByTagNameNS($this->officeNs, 'master-styles')->item(0); $styleMasterLookup = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($this->stylesNs, 'master-page'); foreach ($styleMasterLookup as $styleMasterSet) { $styleMasterName = $styleMasterSet->getAttributeNS($this->stylesNs, 'name'); $pageLayoutName = $styleMasterSet->getAttributeNS($this->stylesNs, 'page-layout-name'); $this->masterPrintStylesCrossReference[$styleMasterName] = $pageLayoutName; } } public function readStyleCrossReferences(DOMDocument $contentDom): void { $item0 = $contentDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles')->item(0); $styleXReferences = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($this->stylesNs, 'style'); foreach ($styleXReferences as $styleXreferenceSet) { $styleXRefName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'name'); $stylePageLayoutName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'master-page-name'); $styleFamilyName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'family'); if (!empty($styleFamilyName) && $styleFamilyName === 'table') { $styleVisibility = 'true'; foreach ($styleXreferenceSet->getElementsByTagNameNS($this->stylesNs, 'table-properties') as $tableProperties) { $styleVisibility = $tableProperties->getAttributeNS($this->tableNs, 'display'); } $this->tableStylesCrossReference[$styleXRefName] = $styleVisibility; } if (!empty($stylePageLayoutName)) { $this->masterStylesCrossReference[$styleXRefName] = $stylePageLayoutName; } } } public function setVisibilityForWorksheet(Worksheet $worksheet, string $styleName): void { if (!array_key_exists($styleName, $this->tableStylesCrossReference)) { return; } $worksheet->setSheetState( $this->tableStylesCrossReference[$styleName] === 'false' ? Worksheet::SHEETSTATE_HIDDEN : Worksheet::SHEETSTATE_VISIBLE ); } public function setPrintSettingsForWorksheet(Worksheet $worksheet, string $styleName): void { if (!array_key_exists($styleName, $this->masterStylesCrossReference)) { return; } $masterStyleName = $this->masterStylesCrossReference[$styleName]; if (!array_key_exists($masterStyleName, $this->masterPrintStylesCrossReference)) { return; } $printSettingsIndex = $this->masterPrintStylesCrossReference[$masterStyleName]; if (!array_key_exists($printSettingsIndex, $this->pageLayoutStyles)) { return; } /** @var (object{orientation: string, scale: int|string, printOrder: ?string, * horizontalCentered: bool, verticalCentered: bool, marginLeft: float, marginRight: float, marginTop: float, * marginBottom: float, marginHeader: float, marginFooter: float}&stdClass) */ $printSettings = $this->pageLayoutStyles[$printSettingsIndex]; $worksheet->getPageSetup() ->setOrientation($printSettings->orientation ?? PageSetup::ORIENTATION_DEFAULT) ->setPageOrder($printSettings->printOrder === 'ltr' ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER) ->setScale((int) trim((string) $printSettings->scale, '%')) ->setHorizontalCentered($printSettings->horizontalCentered) ->setVerticalCentered($printSettings->verticalCentered); $worksheet->getPageMargins() ->setLeft($printSettings->marginLeft) ->setRight($printSettings->marginRight) ->setTop($printSettings->marginTop) ->setBottom($printSettings->marginBottom) ->setHeader($printSettings->marginHeader) ->setFooter($printSettings->marginFooter); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Ods/Properties.php ================================================ spreadsheet = $spreadsheet; } /** @param array{meta?: string, office?: string, dc?: string} $namespacesMeta */ public function load(SimpleXMLElement $xml, array $namespacesMeta): void { $docProps = $this->spreadsheet->getProperties(); $officeProperty = $xml->children($namespacesMeta['office'] ?? ''); foreach ($officeProperty as $officePropertyData) { if (isset($namespacesMeta['dc'])) { $officePropertiesDC = $officePropertyData->children($namespacesMeta['dc']); $this->setCoreProperties($docProps, $officePropertiesDC); } $officePropertyMeta = null; if (isset($namespacesMeta['dc'])) { $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta'] ?? ''); } $officePropertyMeta = $officePropertyMeta ?? []; foreach ($officePropertyMeta as $propertyName => $propertyValue) { $this->setMetaProperties($namespacesMeta, $propertyValue, $propertyName, $docProps); } } } private function setCoreProperties(DocumentProperties $docProps, SimpleXMLElement $officePropertyDC): void { foreach ($officePropertyDC as $propertyName => $propertyValue) { $propertyValue = (string) $propertyValue; switch ($propertyName) { case 'title': $docProps->setTitle($propertyValue); break; case 'subject': $docProps->setSubject($propertyValue); break; case 'creator': $docProps->setCreator($propertyValue); $docProps->setLastModifiedBy($propertyValue); break; case 'date': $docProps->setModified($propertyValue); break; case 'description': $docProps->setDescription($propertyValue); break; } } } /** @param array{meta?: string, office?: mixed, dc?: mixed} $namespacesMeta */ private function setMetaProperties( array $namespacesMeta, SimpleXMLElement $propertyValue, string $propertyName, DocumentProperties $docProps ): void { $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta'] ?? ''); $propertyValue = (string) $propertyValue; switch ($propertyName) { case 'initial-creator': $docProps->setCreator($propertyValue); break; case 'keyword': $docProps->setKeywords($propertyValue); break; case 'creation-date': $docProps->setCreated($propertyValue); break; case 'user-defined': $name2 = (string) ($propertyValueAttributes['name'] ?? ''); if ($name2 === 'Company') { $docProps->setCompany($propertyValue); } elseif ($name2 === 'category') { $docProps->setCategory($propertyValue); } else { $this->setUserDefinedProperty($propertyValueAttributes, $propertyValue, $docProps); } break; } } /** @param iterable $propertyValueAttributes */ private function setUserDefinedProperty(iterable $propertyValueAttributes, string $propertyValue, DocumentProperties $docProps): void { $propertyValueName = ''; $propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING; foreach ($propertyValueAttributes as $key => $value) { if ($key == 'name') { /** @var scalar $value */ $propertyValueName = (string) $value; } elseif ($key == 'value-type') { /** @var string $value */ switch ($value) { case 'date': $propertyValue = DocumentProperties::convertProperty($propertyValue, 'date'); $propertyValueType = DocumentProperties::PROPERTY_TYPE_DATE; break; case 'boolean': $propertyValue = DocumentProperties::convertProperty($propertyValue, 'bool'); $propertyValueType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; break; case 'float': $propertyValue = DocumentProperties::convertProperty($propertyValue, 'r4'); $propertyValueType = DocumentProperties::PROPERTY_TYPE_FLOAT; break; default: $propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING; } } } $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Ods.php ================================================ securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { $mimeType = 'UNKNOWN'; // Load file if (File::testFileNoThrow($filename, '')) { $zip = new ZipArchive(); if ($zip->open($filename) === true) { // check if it is an OOXML archive $stat = $zip->statName('mimetype'); if (!empty($stat) && ($stat['size'] <= 255)) { $mimeType = $zip->getFromName($stat['name']); } elseif ($zip->statName('META-INF/manifest.xml')) { $xml = simplexml_load_string( $this->getSecurityScannerOrThrow() ->scan( $zip->getFromName( 'META-INF/manifest.xml' ) ) ); if ($xml !== false) { $namespacesContent = $xml->getNamespaces(true); if (isset($namespacesContent['manifest'])) { $manifest = $xml->children($namespacesContent['manifest']); foreach ($manifest as $manifestDataSet) { $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); if ($manifestAttributes && $manifestAttributes->{'full-path'} == '/') { $mimeType = (string) $manifestAttributes->{'media-type'}; break; } } } } } $zip->close(); } } return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; } /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. * * @return string[] */ public function listWorksheetNames(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $xml = new XMLReader(); $xml->xml( $this->getSecurityScannerOrThrow() ->scanFile( 'zip://' . realpath($filename) . '#' . self::INITIAL_FILE ) ); $xml->setParserProperty(2, true); // Step into the first level of content of the XML $xml->read(); while ($xml->read()) { // Quickly jump through to the office:body node while ($xml->name !== 'office:body') { if ($xml->isEmptyElement) { $xml->read(); } else { $xml->next(); } } // Now read each node until we find our first table:table node while ($xml->read()) { $xmlName = $xml->name; if ($xmlName == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { // Loop through each table:table node reading the table:name attribute for each worksheet name do { $worksheetName = $xml->getAttribute('table:name'); if (!empty($worksheetName)) { $worksheetNames[] = $worksheetName; } $xml->next(); } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT); } } } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $xml = new XMLReader(); $xml->xml( $this->getSecurityScannerOrThrow() ->scanFile( 'zip://' . realpath($filename) . '#' . self::INITIAL_FILE ) ); $xml->setParserProperty(2, true); // Step into the first level of content of the XML $xml->read(); $tableVisibility = []; $lastTableStyle = ''; while ($xml->read()) { if ($xml->name === 'style:style') { $styleType = $xml->getAttribute('style:family'); if ($styleType === 'table') { $lastTableStyle = $xml->getAttribute('style:name'); } } elseif ($xml->name === 'style:table-properties') { $visibility = $xml->getAttribute('table:display'); $tableVisibility[$lastTableStyle] = ($visibility === 'false') ? Worksheet::SHEETSTATE_HIDDEN : Worksheet::SHEETSTATE_VISIBLE; } elseif ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { $worksheetNames[] = $xml->getAttribute('table:name'); $styleName = $xml->getAttribute('table:style-name') ?? ''; $visibility = $tableVisibility[$styleName] ?? ''; $tmpInfo = [ 'worksheetName' => (string) $xml->getAttribute('table:name'), 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, 'sheetState' => $visibility, ]; // Loop through each child node of the table:table element reading $currRow = 0; do { $xml->read(); if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { $rowspan = $xml->getAttribute('table:number-rows-repeated'); $rowspan = empty($rowspan) ? 1 : (int) $rowspan; $currRow += $rowspan; $currCol = 0; // Step into the row $xml->read(); do { $doread = true; if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { $mergeSize = $xml->getAttribute('table:number-columns-repeated'); $mergeSize = empty($mergeSize) ? 1 : (int) $mergeSize; $currCol += $mergeSize; if (!$xml->isEmptyElement) { $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCol); $tmpInfo['totalRows'] = $currRow; $xml->next(); $doread = false; } } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { $mergeSize = $xml->getAttribute('table:number-columns-repeated'); $currCol += (int) $mergeSize; } if ($doread) { $xml->read(); } } while ($xml->name != 'table:table-row'); } } while ($xml->name != 'table:table'); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1, true); $worksheetInfo[] = $tmpInfo; } } return $worksheetInfo; } /** * Loads PhpSpreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** @var array */ private array $allStyles; private int $highestDataIndex; /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { File::assertFile($filename, self::INITIAL_FILE); $zip = new ZipArchive(); $zip->open($filename); // Meta $xml = @simplexml_load_string( $this->getSecurityScannerOrThrow() ->scan($zip->getFromName('meta.xml')) ); if ($xml === false) { throw new Exception('Unable to read data from {$pFilename}'); } /** @var array{meta?: string, office?: string, dc?: string} */ $namespacesMeta = $xml->getNamespaces(true); (new DocumentProperties($spreadsheet))->load($xml, $namespacesMeta); // Styles $this->allStyles = []; $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( $this->getSecurityScannerOrThrow() ->scan($zip->getFromName('styles.xml')) ); $officeNs = (string) $dom->lookupNamespaceUri('office'); $styleNs = (string) $dom->lookupNamespaceUri('style'); $fontNs = (string) $dom->lookupNamespaceUri('fo'); $automaticStyle0 = $this->readDataOnly ? null : $dom->getElementsByTagNameNS($officeNs, 'styles')->item(0); $automaticStyles = ($automaticStyle0 === null) ? [] : $automaticStyle0->getElementsByTagNameNS($styleNs, 'default-style'); foreach ($automaticStyles as $automaticStyle) { $styleFamily = $automaticStyle->getAttributeNS($styleNs, 'family'); if ($styleFamily === 'table-cell') { $fonts = []; foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'text-properties') as $textProperty) { $fonts = $this->getFontStyles($textProperty, $styleNs, $fontNs); } if (!empty($fonts)) { $spreadsheet->getDefaultStyle() ->getFont() ->applyFromArray($fonts); } } } $automaticStyles = ($automaticStyle0 === null) ? [] : $automaticStyle0->getElementsByTagNameNS($styleNs, 'style'); foreach ($automaticStyles as $automaticStyle) { $styleName = $automaticStyle->getAttributeNS($styleNs, 'name'); $styleFamily = $automaticStyle->getAttributeNS($styleNs, 'family'); if ($styleFamily === 'table-cell') { $fills = $fonts = []; foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'text-properties') as $textProperty) { $fonts = $this->getFontStyles($textProperty, $styleNs, $fontNs); } foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'table-cell-properties') as $tableCellProperty) { $fills = $this->getFillStyles($tableCellProperty, $fontNs); } if ($styleName !== '') { if (!empty($fonts)) { $this->allStyles[$styleName]['font'] = $fonts; if ($styleName === 'Default') { $spreadsheet->getDefaultStyle() ->getFont() ->applyFromArray($fonts); } } if (!empty($fills)) { $this->allStyles[$styleName]['fill'] = $fills; if ($styleName === 'Default') { $spreadsheet->getDefaultStyle() ->getFill() ->applyFromArray($fills); } } } } } $pageSettings = new PageSettings($dom); // Main Content $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( $this->getSecurityScannerOrThrow() ->scan($zip->getFromName(self::INITIAL_FILE)) ); $tableNs = (string) $dom->lookupNamespaceUri('table'); $textNs = (string) $dom->lookupNamespaceUri('text'); $xlinkNs = (string) $dom->lookupNamespaceUri('xlink'); $pageSettings->readStyleCrossReferences($dom); $autoFilterReader = new AutoFilter($spreadsheet, $tableNs); $definedNameReader = new DefinedNames($spreadsheet, $tableNs); $columnWidths = []; $automaticStyle0 = $this->readDataOnly ? null : $dom->getElementsByTagNameNS($officeNs, 'automatic-styles')->item(0); $automaticStyles = ($automaticStyle0 === null) ? [] : $automaticStyle0->getElementsByTagNameNS($styleNs, 'style'); foreach ($automaticStyles as $automaticStyle) { $styleName = $automaticStyle->getAttributeNS($styleNs, 'name'); $styleFamily = $automaticStyle->getAttributeNS($styleNs, 'family'); if ($styleFamily === 'table-column') { $tcprops = $automaticStyle->getElementsByTagNameNS($styleNs, 'table-column-properties'); $tcprop = $tcprops->item(0); if ($tcprop !== null) { $columnWidth = $tcprop->getAttributeNs($styleNs, 'column-width'); $columnWidths[$styleName] = $columnWidth; } } if ($styleFamily === 'table-cell') { $fonts = $fills = $alignment1 = $alignment2 = $protection = $borders = []; foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'text-properties') as $textProperty) { $fonts = $this->getFontStyles($textProperty, $styleNs, $fontNs); } foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'table-cell-properties') as $tableCellProperty) { $fills = $this->getFillStyles($tableCellProperty, $fontNs); $borders = $this->getBorderStyles($tableCellProperty, $fontNs, $styleNs); $protection = $this->getProtectionStyles($tableCellProperty, $styleNs); } foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'table-cell-properties') as $tableCellProperty) { $alignment1 = $this->getAlignment1Styles($tableCellProperty, $styleNs, $fontNs); } foreach ($automaticStyle->getElementsByTagNameNS($styleNs, 'paragraph-properties') as $paragraphProperty) { $alignment2 = $this->getAlignment2Styles($paragraphProperty, $styleNs, $fontNs); } if ($styleName !== '') { if (!empty($fonts)) { $this->allStyles[$styleName]['font'] = $fonts; } if (!empty($fills)) { $this->allStyles[$styleName]['fill'] = $fills; } $alignment = array_merge($alignment1, $alignment2); if (!empty($alignment)) { $this->allStyles[$styleName]['alignment'] = $alignment; } if (!empty($protection)) { $this->allStyles[$styleName]['protection'] = $protection; } if (!empty($borders)) { $this->allStyles[$styleName]['borders'] = $borders; } } } } // Content $item0 = $dom->getElementsByTagNameNS($officeNs, 'body')->item(0); $spreadsheets = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($officeNs, 'spreadsheet'); foreach ($spreadsheets as $workbookData) { /** @var DOMElement $workbookData */ $tables = $workbookData->getElementsByTagNameNS($tableNs, 'table'); $worksheetID = 0; $sheetCreated = false; foreach ($tables as $worksheetDataSet) { /** @var DOMElement $worksheetDataSet */ $worksheetName = $worksheetDataSet->getAttributeNS($tableNs, 'name'); // Check loadSheetsOnly if ( $this->loadSheetsOnly !== null && $worksheetName && !in_array($worksheetName, $this->loadSheetsOnly) ) { continue; } $worksheetStyleName = $worksheetDataSet->getAttributeNS($tableNs, 'style-name'); // Create sheet $spreadsheet->createSheet(); $sheetCreated = true; $spreadsheet->setActiveSheetIndex($worksheetID); if ($worksheetName || is_numeric($worksheetName)) { // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in // formula cells... during the load, all formulae should be correct, and we're simply // bringing the worksheet name in line with the formula, not the reverse $spreadsheet->getActiveSheet() ->setTitle((string) $worksheetName, false, false); } // Go through every child of table element $rowID = 1; $tableColumnIndex = 1; $this->highestDataIndex = AddressRange::MAX_COLUMN_INT; foreach ($worksheetDataSet->childNodes as $childNode) { /** @var DOMElement $childNode */ // Filter elements which are not under the "table" ns if ($childNode->namespaceURI != $tableNs) { continue; } $key = self::extractNodeName($childNode->nodeName); switch ($key) { case 'table-header-rows': case 'table-rows': $this->processTableHeaderRows( $childNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; case 'table-row-group': $this->processTableRowGroup( $childNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; case 'table-row': $this->processTableRow( $childNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; case 'table-header-columns': case 'table-columns': $this->processTableColumnHeader( $childNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $this->readEmptyCells, true ); break; case 'table-column-group': $this->processTableColumnGroup( $childNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $this->readEmptyCells, true ); break; case 'table-column': $this->processTableColumn( $childNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $this->readEmptyCells, true ); break; } } $pageSettings->setVisibilityForWorksheet( $spreadsheet->getActiveSheet(), $worksheetStyleName ); $pageSettings->setPrintSettingsForWorksheet( $spreadsheet->getActiveSheet(), $worksheetStyleName ); ++$worksheetID; } if ($this->createBlankSheetIfNoneRead && !$sheetCreated) { $spreadsheet->createSheet(); } } foreach ($spreadsheets as $workbookData) { /** @var DOMElement $workbookData */ $tables = $workbookData->getElementsByTagNameNS($tableNs, 'table'); $worksheetID = 0; foreach ($tables as $worksheetDataSet) { /** @var DOMElement $worksheetDataSet */ $worksheetName = $worksheetDataSet->getAttributeNS($tableNs, 'name'); // Check loadSheetsOnly if ( $this->loadSheetsOnly !== null && $worksheetName && !in_array($worksheetName, $this->loadSheetsOnly) ) { continue; } // Create sheet $spreadsheet->setActiveSheetIndex($worksheetID); $highestDataColumn = $spreadsheet->getActiveSheet()->getHighestDataColumn(); $this->highestDataIndex = Coordinate::columnIndexFromString($highestDataColumn); // Go through every child of table element processing column widths $rowID = 1; $tableColumnIndex = 1; foreach ($worksheetDataSet->childNodes as $childNode) { /** @var DOMElement $childNode */ if (empty($columnWidths) || $this->readEmptyCells) { break; } // Filter elements which are not under the "table" ns if ($childNode->namespaceURI != $tableNs) { continue; } $key = self::extractNodeName($childNode->nodeName); switch ($key) { case 'table-header-columns': case 'table-columns': $this->processTableColumnHeader( $childNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, true, false ); break; case 'table-column-group': $this->processTableColumnGroup( $childNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, true, false ); break; case 'table-column': $this->processTableColumn( $childNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, true, false ); break; } } ++$worksheetID; } $autoFilterReader->read($workbookData); $definedNameReader->read($workbookData); } $spreadsheet->setActiveSheetIndex(0); if ($zip->locateName('settings.xml') !== false) { $this->processSettings($zip, $spreadsheet); } // Return return $spreadsheet; } private function processTableHeaderRows( DOMElement $childNode, string $tableNs, int &$rowID, string $worksheetName, string $officeNs, string $textNs, string $xlinkNs, Spreadsheet $spreadsheet ): void { foreach ($childNode->childNodes as $grandchildNode) { /** @var DOMElement $grandchildNode */ $grandkey = self::extractNodeName($grandchildNode->nodeName); switch ($grandkey) { case 'table-row': $this->processTableRow( $grandchildNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; } } } private function processTableRowGroup( DOMElement $childNode, string $tableNs, int &$rowID, string $worksheetName, string $officeNs, string $textNs, string $xlinkNs, Spreadsheet $spreadsheet ): void { foreach ($childNode->childNodes as $grandchildNode) { /** @var DOMElement $grandchildNode */ $grandkey = self::extractNodeName($grandchildNode->nodeName); switch ($grandkey) { case 'table-row': $this->processTableRow( $grandchildNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; case 'table-header-rows': case 'table-rows': $this->processTableHeaderRows( $grandchildNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; case 'table-row-group': $this->processTableRowGroup( $grandchildNode, $tableNs, $rowID, $worksheetName, $officeNs, $textNs, $xlinkNs, $spreadsheet ); break; } } } private function processTableRow( DOMElement $childNode, string $tableNs, int &$rowID, string $worksheetName, string $officeNs, string $textNs, string $xlinkNs, Spreadsheet $spreadsheet ): void { if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) { $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); } else { $rowRepeats = 1; } $worksheet = $spreadsheet->getSheetByName($worksheetName); $columnID = 'A'; /** @var DOMElement|DOMText $cellData */ foreach ($childNode->childNodes as $cellData) { if ($cellData instanceof DOMText) { continue; // should just be whitespace } if ($cellData->hasAttributeNS($tableNs, 'number-columns-repeated')) { $colRepeats = (int) $cellData->getAttributeNS($tableNs, 'number-columns-repeated'); } else { $colRepeats = 1; } $styleName = $cellData->getAttributeNS($tableNs, 'style-name'); // When a cell has number-columns-repeated, check if ANY column in the // repeated range passes the read filter. If not, skip the entire group. // If some columns pass, we need to fall through to the processing block // which will handle per-column filtering. if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { if ($colRepeats <= 1) { StringHelper::stringIncrement($columnID); continue; } // Check if any column within this repeated group passes the filter $anyColumnPasses = false; $tempCol = $columnID; for ($i = 0; $i < $colRepeats; ++$i) { if ($i > 0) { StringHelper::stringIncrement($tempCol); } if ($this->getReadFilter()->readCell($tempCol, $rowID, $worksheetName)) { $anyColumnPasses = true; break; } } if (!$anyColumnPasses) { for ($i = 0; $i < $colRepeats; ++$i) { StringHelper::stringIncrement($columnID); } continue; } // Fall through to process the cell, with per-column filter checks } if ($worksheet !== null && ($cellData->hasChildNodes() || ($cellData->nextSibling !== null)) && isset($this->allStyles[$styleName])) { $spannedRange = "$columnID$rowID"; // the following is sufficient for ods, // and does no harm for xlsx/xls. $worksheet->getStyle($spannedRange) ->applyFromArray($this->allStyles[$styleName]); // the rest of this block is needed for xlsx/xls, // and does no harm for ods. if (isset($this->allStyles[$styleName]['borders'])) { $spannedRows = $cellData->getAttributeNS($tableNs, 'number-columns-spanned'); $spannedColumns = $cellData->getAttributeNS($tableNs, 'number-rows-spanned'); $spannedRows = max((int) $spannedRows, 1); $spannedColumns = max((int) $spannedColumns, 1); if ($spannedRows > 1 || $spannedColumns > 1) { $endRow = $rowID + $spannedRows - 1; $endCol = $columnID; while ($spannedColumns > 1) { StringHelper::stringIncrement($endCol); --$spannedColumns; } $spannedRange .= ":$endCol$endRow"; $worksheet->getStyle($spannedRange) ->getBorders() ->applyFromArray( $this->allStyles[$styleName]['borders'] ); } } } // Initialize variables $formatting = $hyperlink = null; $hasCalculatedValue = false; $cellDataFormula = ''; $cellDataType = ''; $cellDataRef = ''; if ($cellData->hasAttributeNS($tableNs, 'formula')) { $cellDataFormula = $cellData->getAttributeNS($tableNs, 'formula'); $hasCalculatedValue = true; } if ($cellData->hasAttributeNS($tableNs, 'number-matrix-columns-spanned')) { if ($cellData->hasAttributeNS($tableNs, 'number-matrix-rows-spanned')) { $cellDataType = 'array'; $arrayRow = (int) $cellData->getAttributeNS($tableNs, 'number-matrix-rows-spanned'); $arrayCol = (int) $cellData->getAttributeNS($tableNs, 'number-matrix-columns-spanned'); $lastRow = $rowID + $arrayRow - 1; $lastCol = $columnID; while ($arrayCol > 1) { StringHelper::stringIncrement($lastCol); --$arrayCol; } $cellDataRef = "$columnID$rowID:$lastCol$lastRow"; } } // Annotations $annotation = $cellData->getElementsByTagNameNS($officeNs, 'annotation'); if ($annotation->length > 0 && $annotation->item(0) !== null) { $textNode = $annotation->item(0)->getElementsByTagNameNS($textNs, 'p'); $textNodeLength = $textNode->length; $newLineOwed = false; for ($textNodeIndex = 0; $textNodeIndex < $textNodeLength; ++$textNodeIndex) { $textNodeItem = $textNode->item($textNodeIndex); if ($textNodeItem !== null) { $text = $this->scanElementForText($textNodeItem); if ($newLineOwed) { $spreadsheet->getActiveSheet() ->getComment($columnID . $rowID) ->getText() ->createText("\n"); } $newLineOwed = true; $spreadsheet->getActiveSheet() ->getComment($columnID . $rowID) ->getText() ->createText( $this->parseRichText($text) ); } } } // Content /** @var DOMElement[] $paragraphs */ $paragraphs = []; foreach ($cellData->childNodes as $item) { /** @var DOMElement $item */ // Filter text:p elements if ($item->nodeName == 'text:p') { $paragraphs[] = $item; } } if (count($paragraphs) > 0) { $dataValue = null; // Consolidate if there are multiple p records (maybe with spans as well) $dataArray = []; // Text can have multiple text:p and within those, multiple text:span. // text:p newlines, but text:span does not. // Also, here we assume there is no text data is span fields are specified, since // we have no way of knowing proper positioning anyway. foreach ($paragraphs as $pData) { $dataArray[] = $this->scanElementForText($pData); } $allCellDataText = implode("\n", $dataArray); $type = $cellData->getAttributeNS($officeNs, 'value-type'); $symbol = ''; $leftHandCurrency = Preg::isMatch('/\$|£|¥/', $allCellDataText, $matches); if ($leftHandCurrency) { $type = str_replace('float', 'currency', $type); $symbol = (string) $matches[0]; } $customFormatting = ''; if ($this->formatCallback !== null) { $temp = ($this->formatCallback)($type, $allCellDataText); if ($temp !== '') { $customFormatting = $temp; } } switch ($type) { case 'string': $type = DataType::TYPE_STRING; $dataValue = $allCellDataText; foreach ($paragraphs as $paragraph) { $link = $paragraph->getElementsByTagNameNS($textNs, 'a'); if ($link->length > 0 && $link->item(0) !== null) { $hyperlink = $link->item(0)->getAttributeNS($xlinkNs, 'href'); } } break; case 'boolean': $type = DataType::TYPE_BOOL; $dataValue = ($cellData->getAttributeNS($officeNs, 'boolean-value') === 'true') ? true : false; break; case 'percentage': if (!str_contains($allCellDataText, '.')) { $formatting = NumberFormat::FORMAT_PERCENTAGE; } elseif (substr($allCellDataText, -3, 1) === '.') { $formatting = NumberFormat::FORMAT_PERCENTAGE_0; } else { $formatting = NumberFormat::FORMAT_PERCENTAGE_00; } $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); break; case 'currency': $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); $currency = $cellData->getAttributeNS($officeNs, 'currency'); if ($leftHandCurrency) { $typeValue = 'currency'; $formatting = str_contains($allCellDataText, '.') ? NumberFormat::FORMAT_CURRENCY_USD : NumberFormat::FORMAT_CURRENCY_USD_INTEGER; if ($symbol !== '$') { $formatting = str_replace('$', $symbol, $formatting); } } elseif (str_contains($allCellDataText, '€')) { $typeValue = 'currency'; $formatting = str_contains($allCellDataText, '.') ? NumberFormat::FORMAT_CURRENCY_EUR : NumberFormat::FORMAT_CURRENCY_EUR_INTEGER; } break; case 'float': $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); if ($dataValue !== floor($dataValue)) { // do nothing } elseif (substr($allCellDataText, -2, 1) === '.') { $formatting = NumberFormat::FORMAT_NUMBER_0; } elseif (substr($allCellDataText, -3, 1) === '.') { $formatting = NumberFormat::FORMAT_NUMBER_00; } if (floor($dataValue) == $dataValue) { if ($dataValue == (int) $dataValue) { $dataValue = (int) $dataValue; } } break; case 'date': $type = DataType::TYPE_NUMERIC; $value = $cellData->getAttributeNS($officeNs, 'date-value'); $dataValue = Date::convertIsoDate($value); if (Preg::isMatch('/^\d\d\d\d-\d\d-\d\d$/', $allCellDataText)) { $formatting = 'yyyy-mm-dd'; } elseif (Preg::isMatch('/^\d\d?-[a-zA-Z]+-\d\d\d\d$/', $allCellDataText)) { $formatting = 'd-mmm-yyyy'; } elseif ($dataValue != floor($dataValue)) { $formatting = NumberFormat::FORMAT_DATE_XLSX15 . ' ' . NumberFormat::FORMAT_DATE_TIME4; } else { $formatting = NumberFormat::FORMAT_DATE_XLSX15; } break; case 'time': $type = DataType::TYPE_NUMERIC; $timeValue = $cellData->getAttributeNS($officeNs, 'time-value'); $minus = ''; if (str_starts_with($timeValue, '-')) { $minus = '-'; $timeValue = substr($timeValue, 1); } $timeArray = sscanf($timeValue, 'PT%dH%dM%dS'); if (is_array($timeArray)) { /** @var array{int, int, int} $timeArray */ $days = intdiv($timeArray[0], 24); $hours = $timeArray[0] % 24; $dt = new DateTime("1899-12-30 $hours:{$timeArray[1]}:{$timeArray[2]}", new DateTimeZone('UTC')); $dt->modify("+$days days"); $dataValue = Date::PHPToExcel($dt); if ($minus === '-') { $dataValue *= -1; $formatting = '[hh]:mm:ss'; } else { $formatting = NumberFormat::FORMAT_DATE_TIME4; } } break; default: $dataValue = null; } if ($customFormatting !== '') { $formatting = $customFormatting; } } else { $type = DataType::TYPE_NULL; $dataValue = null; } if ($hasCalculatedValue) { $type = DataType::TYPE_FORMULA; $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1); $cellDataFormula = FormulaTranslator::convertToExcelFormulaValue($cellDataFormula); } for ($i = 0; $i < $colRepeats; ++$i) { if ($i > 0) { StringHelper::stringIncrement($columnID); } if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { continue; } if ($type !== DataType::TYPE_NULL) { for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) { $rID = $rowID + $rowAdjust; $cell = $spreadsheet->getActiveSheet() ->getCell($columnID . $rID); // Set value if ($hasCalculatedValue) { $cell->setValueExplicit($cellDataFormula, $type); if ($cellDataType === 'array') { $cell->setFormulaAttributes(['t' => 'array', 'ref' => $cellDataRef]); } } elseif ($type !== '' || $dataValue !== null) { $cell->setValueExplicit($dataValue, $type); } if ($hasCalculatedValue) { $cell->setCalculatedValue($dataValue, $type === DataType::TYPE_NUMERIC); } // Set other properties if ($formatting !== null) { $spreadsheet->getActiveSheet() ->getStyle($columnID . $rID) ->getNumberFormat() ->setFormatCode($formatting); } else { $spreadsheet->getActiveSheet() ->getStyle($columnID . $rID) ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_GENERAL); } if ($hyperlink !== null) { if ($hyperlink[0] === '#') { $hyperlink = 'sheet://' . substr($hyperlink, 1); } $cell->getHyperlink() ->setUrl($hyperlink); } } } } // Merged cells $this->processMergedCells($cellData, $tableNs, $type, $columnID, $rowID, $spreadsheet); StringHelper::stringIncrement($columnID); } $rowID += $rowRepeats; } private static function extractNodeName(string $key): string { // Remove ns from node name if (str_contains($key, ':')) { $keyChunks = explode(':', $key); $key = array_pop($keyChunks); } return $key; } /** * @param string[] $columnWidths */ private function processTableColumnHeader( DOMElement $childNode, string $tableNs, array $columnWidths, int &$tableColumnIndex, Spreadsheet $spreadsheet, bool $processWidths = true, bool $processStyles = true ): void { foreach ($childNode->childNodes as $grandchildNode) { /** @var DOMElement $grandchildNode */ $grandkey = self::extractNodeName($grandchildNode->nodeName); switch ($grandkey) { case 'table-column': $this->processTableColumn( $grandchildNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $processWidths, $processStyles ); break; } } } /** * @param string[] $columnWidths */ private function processTableColumnGroup( DOMElement $childNode, string $tableNs, array $columnWidths, int &$tableColumnIndex, Spreadsheet $spreadsheet, bool $processWidths = true, bool $processStyles = true ): void { foreach ($childNode->childNodes as $grandchildNode) { /** @var DOMElement $grandchildNode */ $grandkey = self::extractNodeName($grandchildNode->nodeName); switch ($grandkey) { case 'table-column': $this->processTableColumn( $grandchildNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $processWidths, $processStyles ); break; case 'table-header-columns': case 'table-columns': $this->processTableColumnHeader( $grandchildNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $processWidths, $processStyles ); break; case 'table-column-group': $this->processTableColumnGroup( $grandchildNode, $tableNs, $columnWidths, $tableColumnIndex, $spreadsheet, $processWidths, $processStyles ); break; } } } /** * @param string[] $columnWidths */ private function processTableColumn( DOMElement $childNode, string $tableNs, array $columnWidths, int &$tableColumnIndex, Spreadsheet $spreadsheet, bool $processWidths = true, bool $processStyles = true ): void { if ($childNode->hasAttributeNS($tableNs, 'number-columns-repeated')) { $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-columns-repeated'); } else { $rowRepeats = 1; } $tableStyleName = $childNode->getAttributeNS($tableNs, 'style-name'); if ($processWidths) { if (isset($columnWidths[$tableStyleName])) { $columnWidth = new HelperDimension($columnWidths[$tableStyleName]); $tableColumnIndex2 = $tableColumnIndex; $tableColumnString = Coordinate::stringFromColumnIndex($tableColumnIndex2); for ($rowRepeats2 = $rowRepeats; $rowRepeats2 > 0 && $tableColumnIndex2 <= AddressRange::MAX_COLUMN_INT; --$rowRepeats2) { if (!$this->readEmptyCells && $tableColumnIndex2 > $this->highestDataIndex) { break; } $spreadsheet->getActiveSheet() ->getColumnDimension($tableColumnString) ->setWidth($columnWidth->toUnit('cm'), 'cm'); StringHelper::stringIncrement( $tableColumnString ); ++$tableColumnIndex2; } } } if ($processStyles) { $defaultStyleName = $childNode->getAttributeNS($tableNs, 'default-cell-style-name'); if ($defaultStyleName !== 'Default' && isset($this->allStyles[$defaultStyleName])) { $tableColumnIndex2 = $tableColumnIndex; $tableColumnString = Coordinate::stringFromColumnIndex($tableColumnIndex2); for ($rowRepeats2 = $rowRepeats; $rowRepeats2 > 0 && $tableColumnIndex2 <= AddressRange::MAX_COLUMN_INT; --$rowRepeats2) { $spreadsheet->getActiveSheet() ->getStyle($tableColumnString) ->applyFromArray( $this->allStyles[$defaultStyleName] ); StringHelper::stringIncrement( $tableColumnString ); ++$tableColumnIndex2; } } } $tableColumnIndex += $rowRepeats; } private function processSettings(ZipArchive $zip, Spreadsheet $spreadsheet): void { $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( $this->getSecurityScannerOrThrow() ->scan($zip->getFromName('settings.xml')) ); $configNs = (string) $dom->lookupNamespaceUri('config'); $officeNs = (string) $dom->lookupNamespaceUri('office'); $settings = $dom->getElementsByTagNameNS($officeNs, 'settings') ->item(0); if ($settings !== null) { $this->lookForActiveSheet($settings, $spreadsheet, $configNs); $this->lookForSelectedCells($settings, $spreadsheet, $configNs); } } private function lookForActiveSheet(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void { /** @var DOMElement $t */ foreach ($settings->getElementsByTagNameNS($configNs, 'config-item') as $t) { if ($t->getAttributeNs($configNs, 'name') === 'ActiveTable') { try { $spreadsheet->setActiveSheetIndexByName($t->nodeValue ?? ''); } catch (Throwable) { // do nothing } break; } } } private function lookForSelectedCells(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void { /** @var DOMElement $t */ foreach ($settings->getElementsByTagNameNS($configNs, 'config-item-map-named') as $t) { if ($t->getAttributeNs($configNs, 'name') === 'Tables') { foreach ($t->getElementsByTagNameNS($configNs, 'config-item-map-entry') as $ws) { $setRow = $setCol = ''; $wsname = $ws->getAttributeNs($configNs, 'name'); foreach ($ws->getElementsByTagNameNS($configNs, 'config-item') as $configItem) { $attrName = $configItem->getAttributeNs($configNs, 'name'); if ($attrName === 'CursorPositionX') { $setCol = $configItem->nodeValue; } if ($attrName === 'CursorPositionY') { $setRow = $configItem->nodeValue; } } $this->setSelected($spreadsheet, $wsname, "$setCol", "$setRow"); } break; } } } private function setSelected(Spreadsheet $spreadsheet, string $wsname, string $setCol, string $setRow): void { if (is_numeric($setCol) && is_numeric($setRow)) { $sheet = $spreadsheet->getSheetByName($wsname); if ($sheet !== null) { $sheet->setSelectedCells([(int) $setCol + 1, (int) $setRow + 1]); } } } /** * Recursively scan element. */ protected function scanElementForText(DOMNode $element): string { $str = ''; foreach ($element->childNodes as $child) { /** @var DOMNode $child */ if ($child->nodeType == XML_TEXT_NODE) { $str .= $child->nodeValue; } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:line-break') { $str .= "\n"; } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:s') { // It's a space // Multiple spaces? $attributes = $child->attributes; /** @var ?DOMAttr $cAttr */ $cAttr = ($attributes === null) ? null : $attributes->getNamedItem('c'); $multiplier = self::getMultiplier($cAttr); $str .= str_repeat(' ', $multiplier); } if ($child->hasChildNodes()) { $str .= $this->scanElementForText($child); } } return $str; } private static function getMultiplier(?DOMAttr $cAttr): int { if ($cAttr) { $multiplier = (int) $cAttr->nodeValue; } else { $multiplier = 1; } return $multiplier; } private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } private function processMergedCells( DOMElement $cellData, string $tableNs, string $type, string $columnID, int $rowID, Spreadsheet $spreadsheet ): void { if ( $cellData->hasAttributeNS($tableNs, 'number-columns-spanned') || $cellData->hasAttributeNS($tableNs, 'number-rows-spanned') ) { if (($type !== DataType::TYPE_NULL) || ($this->readDataOnly === false)) { $columnTo = $columnID; if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')) { $columnIndex = Coordinate::columnIndexFromString($columnID); $columnIndex += (int) $cellData->getAttributeNS($tableNs, 'number-columns-spanned'); $columnIndex -= 2; $columnTo = Coordinate::stringFromColumnIndex($columnIndex + 1); } $rowTo = $rowID; if ($cellData->hasAttributeNS($tableNs, 'number-rows-spanned')) { $rowTo = $rowTo + (int) $cellData->getAttributeNS($tableNs, 'number-rows-spanned') - 1; } $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo; $spreadsheet->getActiveSheet()->mergeCells($cellRange, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } /** @var null|Closure(string, string):string */ private ?Closure $formatCallback = null; /** @param Closure(string, string):string $formatCallback */ public function setFormatCallback(Closure $formatCallback): void { $this->formatCallback = $formatCallback; } /** @return array{ * autoColor?: true, * bold?: true, * color?: array{rgb: string}, * italic?: true, * name?: non-empty-string, * size?: float|int, * strikethrough?: true, * underline?: 'double'|'single', * } */ protected function getFontStyles(DOMElement $textProperty, string $styleNs, string $fontNs): array { $fonts = []; $temp = $textProperty->getAttributeNs($styleNs, 'font-name') ?: $textProperty->getAttributeNs($fontNs, 'font-family'); if ($temp !== '') { $fonts['name'] = $temp; } $temp = $textProperty->getAttributeNs($fontNs, 'font-size'); if ($temp !== '' && str_ends_with($temp, 'pt')) { $fonts['size'] = (float) substr($temp, 0, -2); } $temp = $textProperty->getAttributeNs($fontNs, 'font-style'); if ($temp === 'italic') { $fonts['italic'] = true; } $temp = $textProperty->getAttributeNs($fontNs, 'font-weight'); if ($temp === 'bold') { $fonts['bold'] = true; } $temp = $textProperty->getAttributeNs($fontNs, 'color'); if (Preg::isMatch('/^#[a-f0-9]{6}$/i', $temp)) { $fonts['color'] = ['rgb' => substr($temp, 1)]; } $temp = $textProperty->getAttributeNs($styleNs, 'use-window-font-color'); if ($temp === 'true') { $fonts['autoColor'] = true; } $temp = $textProperty->getAttributeNs($styleNs, 'text-underline-type'); if ($temp === '') { $temp = $textProperty->getAttributeNs($styleNs, 'text-underline-style'); if ($temp !== '' && $temp !== 'none') { $temp = 'single'; } } if ($temp === 'single' || $temp === 'double') { $fonts['underline'] = $temp; } $temp = $textProperty->getAttributeNs($styleNs, 'text-line-through-type'); if ($temp !== '' && $temp !== 'none') { $fonts['strikethrough'] = true; } return $fonts; } /** @return array{ * fillType?: string, * startColor?: array{rgb: string}, * } */ protected function getFillStyles(DOMElement $tableCellProperties, string $fontNs): array { $fills = []; $temp = $tableCellProperties->getAttributeNs($fontNs, 'background-color'); if (Preg::isMatch('/^#[a-f0-9]{6}$/i', $temp)) { $fills['fillType'] = Fill::FILL_SOLID; $fills['startColor'] = ['rgb' => substr($temp, 1)]; } elseif ($temp === 'transparent') { $fills['fillType'] = Fill::FILL_NONE; } return $fills; } private const MAP_VERTICAL = [ 'top' => Alignment::VERTICAL_TOP, 'middle' => Alignment::VERTICAL_CENTER, 'automatic' => Alignment::VERTICAL_JUSTIFY, 'bottom' => Alignment::VERTICAL_BOTTOM, ]; private const MAP_HORIZONTAL = [ 'center' => Alignment::HORIZONTAL_CENTER, 'end' => Alignment::HORIZONTAL_RIGHT, 'justify' => Alignment::HORIZONTAL_FILL, 'start' => Alignment::HORIZONTAL_LEFT, ]; /** @return array{ * shrinkToFit?: bool, * textRotation?: int, * vertical?: string, * wrapText?: bool, * } */ protected function getAlignment1Styles(DOMElement $tableCellProperties, string $styleNs, string $fontNs): array { $alignment1 = []; $temp = $tableCellProperties->getAttributeNs($styleNs, 'rotation-angle'); if (is_numeric($temp)) { $temp2 = (int) $temp; if ($temp2 > 90) { $temp2 -= 360; } if ($temp2 >= -90 && $temp2 <= 90) { $alignment1['textRotation'] = (int) $temp2; } } $temp = $tableCellProperties->getAttributeNs($styleNs, 'vertical-align'); $temp2 = self::MAP_VERTICAL[$temp] ?? ''; if ($temp2 !== '') { $alignment1['vertical'] = $temp2; } $temp = $tableCellProperties->getAttributeNs($fontNs, 'wrap-option'); if ($temp === 'wrap') { $alignment1['wrapText'] = true; } elseif ($temp === 'no-wrap') { $alignment1['wrapText'] = false; } $temp = $tableCellProperties->getAttributeNs($styleNs, 'shrink-to-fit'); if ($temp === 'true' || $temp === 'false') { $alignment1['shrinkToFit'] = $temp === 'true'; } return $alignment1; } /** @return array{ * horizontal?: string, * readOrder?: int, * } */ protected function getAlignment2Styles(DOMElement $paragraphProperties, string $styleNs, string $fontNs): array { $alignment2 = []; $temp = $paragraphProperties->getAttributeNs($fontNs, 'text-align'); $temp2 = self::MAP_HORIZONTAL[$temp] ?? ''; if ($temp2 !== '') { $alignment2['horizontal'] = $temp2; } $temp = $paragraphProperties->getAttributeNs($fontNs, 'margin-left') ?: $paragraphProperties->getAttributeNs($fontNs, 'margin-right'); if (Preg::isMatch('/^\d+([.]\d+)?(cm|in|mm|pt)$/', $temp)) { $dimension = new HelperDimension($temp); $alignment2['indent'] = (int) round($dimension->toUnit('px') / Alignment::INDENT_UNITS_TO_PIXELS); } $temp = $paragraphProperties->getAttributeNs($styleNs, 'writing-mode'); if ($temp === 'rl-tb') { $alignment2['readOrder'] = Alignment::READORDER_RTL; } elseif ($temp === 'lr-tb') { $alignment2['readOrder'] = Alignment::READORDER_LTR; } return $alignment2; } /** @return array{ * locked?: string, * hidden?: string, * } */ protected function getProtectionStyles(DOMElement $tableCellProperties, string $styleNs): array { $protection = []; $temp = $tableCellProperties->getAttributeNs($styleNs, 'cell-protect'); switch ($temp) { case 'protected formula-hidden': $protection['locked'] = Protection::PROTECTION_PROTECTED; $protection['hidden'] = Protection::PROTECTION_PROTECTED; break; case 'formula-hidden': $protection['locked'] = Protection::PROTECTION_UNPROTECTED; $protection['hidden'] = Protection::PROTECTION_PROTECTED; break; case 'protected': $protection['locked'] = Protection::PROTECTION_PROTECTED; $protection['hidden'] = Protection::PROTECTION_UNPROTECTED; break; case 'none': $protection['locked'] = Protection::PROTECTION_UNPROTECTED; $protection['hidden'] = Protection::PROTECTION_UNPROTECTED; break; } return $protection; } private const MAP_BORDER_STYLE = [ // default BORDER_THIN 'none' => Border::BORDER_NONE, 'hidden' => Border::BORDER_NONE, 'dotted' => Border::BORDER_DOTTED, 'dash-dot' => Border::BORDER_DASHDOT, 'dash-dot-dot' => Border::BORDER_DASHDOTDOT, 'dashed' => Border::BORDER_DASHED, 'double' => Border::BORDER_DOUBLE, ]; private const MAP_BORDER_MEDIUM = [ Border::BORDER_THIN => Border::BORDER_MEDIUM, Border::BORDER_DASHDOT => Border::BORDER_MEDIUMDASHDOT, Border::BORDER_DASHDOTDOT => Border::BORDER_MEDIUMDASHDOTDOT, Border::BORDER_DASHED => Border::BORDER_MEDIUMDASHED, ]; private const MAP_BORDER_THICK = [ Border::BORDER_THIN => Border::BORDER_THICK, Border::BORDER_DASHDOT => Border::BORDER_MEDIUMDASHDOT, Border::BORDER_DASHDOTDOT => Border::BORDER_MEDIUMDASHDOTDOT, Border::BORDER_DASHED => Border::BORDER_MEDIUMDASHED, ]; /** @return array{ * bottom?: array{borderStyle:string, color:array{rgb: string}}, * top?: array{borderStyle:string, color:array{rgb: string}}, * left?: array{borderStyle:string, color:array{rgb: string}}, * right?: array{borderStyle:string, color:array{rgb: string}}, * diagonal?: array{borderStyle:string, color:array{rgb: string}}, * diagonalDirection?: int, * } */ protected function getBorderStyles(DOMElement $tableCellProperties, string $fontNs, string $styleNs): array { $borders = []; $temp = $tableCellProperties->getAttributeNs($fontNs, 'border'); $diagonalIndex = Borders::DIAGONAL_NONE; foreach (['bottom', 'left', 'right', 'top', 'diagonal-tl-br', 'diagonal-bl-tr'] as $direction) { if (str_starts_with($direction, 'diagonal')) { $directionIndex = 'diagonal'; $temp = $tableCellProperties->getAttributeNs($styleNs, $direction); } else { $directionIndex = $direction; $temp = $tableCellProperties->getAttributeNs($fontNs, "border-$direction"); } if (Preg::isMatch('/^(\d+(?:[.]\d+)?)pt\s+([-\w]+)\s+#([0-9a-fA-F]{6})$/', $temp, $matches)) { $style = self::MAP_BORDER_STYLE[$matches[2]] ?? Border::BORDER_THIN; $width = (float) $matches[1]; if ($width >= 2.5) { $style = self::MAP_BORDER_THICK[$style] ?? $style; } elseif ($width >= 1.75) { $style = self::MAP_BORDER_MEDIUM[$style] ?? $style; } $color = $matches[3]; $borders[$directionIndex] = ['borderStyle' => $style, 'color' => ['rgb' => $matches[3]]]; if ($direction === 'diagonal-tl-br') { $diagonalIndex = Borders::DIAGONAL_DOWN; } elseif ($direction === 'diagonal-bl-tr') { $diagonalIndex = ($diagonalIndex === Borders::DIAGONAL_NONE) ? Borders::DIAGONAL_UP : Borders::DIAGONAL_BOTH; } } } if ($diagonalIndex !== Borders::DIAGONAL_NONE) { $borders['diagonalDirection'] = $diagonalIndex; } return $borders; // @phpstan-ignore-line } } ================================================ FILE: src/PhpSpreadsheet/Reader/Security/XmlScanner.php ================================================ pattern = $pattern; } public static function getInstance(Reader\IReader $reader): self { $pattern = ($reader instanceof Reader\Html) ? 'callback = $callback; } private static function forceString(mixed $arg): string { return is_string($arg) ? $arg : ''; } private function toUtf8(string $xml): string { $charset = $this->findCharSet($xml); $foundUtf7 = $charset === 'UTF-7'; if ($charset !== 'UTF-8') { $testStart = '/^.{0,4}\s*pattern, 1, 'UTF-8')) . '\0*/'; $xml = "$xml"; if (preg_match($pattern, $xml)) { throw new Reader\Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); } $xml = $this->toUtf8($xml); if (preg_match($pattern, $xml)) { throw new Reader\Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); } if ($this->callback !== null) { $xml = call_user_func($this->callback, $xml); } /** @var string $xml */ return $xml; } /** * Scan the XML for use of scan(file_get_contents($filestream)); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Slk.php ================================================ openFile($filename); } catch (ReaderException) { return false; } // Read sample data (first 2 KB will do) $data = (string) fread($this->fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); $hasDelimiter = $delimiterCount > 0; // Analyze first line looking for ID; signature $lines = explode("\n", $data); $hasId = str_starts_with($lines[0], 'ID;P'); fclose($this->fileHandle); return $hasDelimiter && $hasId; } private function canReadOrBust(string $filename): void { if (!$this->canRead($filename)) { throw new ReaderException($filename . ' is an Invalid SYLK file.'); } $this->openFile($filename); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { // Open file $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); $worksheetInfo = [['worksheetName' => basename($filename, '.slk')]]; // loop through one row (line) at a time in the file $rowIndex = 0; $columnIndex = 0; while (($rowData = fgets($fileHandle)) !== false) { $columnIndex = 0; // convert SYLK encoded $rowData to UTF-8 $rowData = StringHelper::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); $dataType = array_shift($rowData); if ($dataType == 'B') { foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'X': $columnIndex = (int) substr($rowDatum, 1) - 1; break; case 'Y': $rowIndex = (int) substr($rowDatum, 1); break; } } break; } } $worksheetInfo[0]['lastColumnIndex'] = $columnIndex; $worksheetInfo[0]['totalRows'] = $rowIndex; $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1, true); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; $worksheetInfo[0]['sheetState'] = Worksheet::SHEETSTATE_VISIBLE; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads PhpSpreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } private const COLOR_ARRAY = [ 'FF00FFFF', // 0 - cyan 'FF000000', // 1 - black 'FFFFFFFF', // 2 - white 'FFFF0000', // 3 - red 'FF00FF00', // 4 - green 'FF0000FF', // 5 - blue 'FFFFFF00', // 6 - yellow 'FFFF00FF', // 7 - magenta ]; private const FONT_STYLE_MAPPINGS = [ 'B' => 'bold', 'I' => 'italic', 'U' => 'underline', ]; /** * @param-out true $hasCalculatedValue */ private function processFormula(string $rowDatum, bool &$hasCalculatedValue, string &$cellDataFormula, string $row, string $column): void { $cellDataFormula = '=' . substr($rowDatum, 1); // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"', $cellDataFormula); $key = false; foreach ($temp as &$value) { // Only count/replace in alternate array entries $key = $key === false; if ($key) { preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way // through the formula from left to right. Reversing means that we work right to left.through // the formula $cellReferences = array_reverse($cellReferences); // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, // then modify the formula to use that new reference foreach ($cellReferences as $cellReference) { $rowReference = $cellReference[2][0]; // Empty R reference is the current row if ($rowReference == '') { $rowReference = $row; } // Bracketed R references are relative to the current row if ($rowReference[0] == '[') { $rowReference = (int) $row + (int) trim($rowReference, '[]'); } $columnReference = $cellReference[4][0]; // Empty C reference is the current column if ($columnReference == '') { $columnReference = $column; } // Bracketed C references are relative to the current column if ($columnReference[0] == '[') { $columnReference = (int) $column + (int) trim($columnReference, '[]'); } $A1CellReference = Coordinate::stringFromColumnIndex((int) $columnReference) . $rowReference; $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string $cellDataFormula = implode('"', $temp); $hasCalculatedValue = true; } /** @param mixed[] $rowData */ private function processCRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void { // Read cell value data $hasCalculatedValue = false; $tryNumeric = false; $cellDataFormula = $cellData = ''; $sharedColumn = $sharedRow = -1; $sharedFormula = false; foreach ($rowData as $rowDatum) { /** @var string $rowDatum */ switch ($rowDatum[0]) { case 'X': $column = substr($rowDatum, 1); break; case 'Y': $row = substr($rowDatum, 1); break; case 'K': $cellData = substr($rowDatum, 1); $tryNumeric = is_numeric($cellData); break; case 'E': $this->processFormula($rowDatum, $hasCalculatedValue, $cellDataFormula, $row, $column); break; case 'A': $comment = substr($rowDatum, 1); $columnLetter = Coordinate::stringFromColumnIndex((int) $column); $spreadsheet->getActiveSheet() ->getComment("$columnLetter$row") ->getText() ->createText($comment); break; case 'C': $sharedColumn = (int) substr($rowDatum, 1); break; case 'R': $sharedRow = (int) substr($rowDatum, 1); break; case 'S': $sharedFormula = true; break; } } if ($sharedFormula === true && $sharedRow >= 0 && $sharedColumn >= 0) { $thisCoordinate = Coordinate::stringFromColumnIndex((int) $column) . $row; $sharedCoordinate = Coordinate::stringFromColumnIndex($sharedColumn) . $sharedRow; /** @var string */ $formula = $spreadsheet->getActiveSheet()->getCell($sharedCoordinate)->getValue(); $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setValue($formula); $referenceHelper = ReferenceHelper::getInstance(); $newFormula = $referenceHelper->updateFormulaReferences($formula, 'A1', (int) $column - $sharedColumn, (int) $row - $sharedRow, '', true, false); $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setValue($newFormula); //$calc = $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->getCalculatedValue(); //$spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setCalculatedValue($calc); $cellData = Calculation::unwrapResult($cellData); $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setCalculatedValue($cellData, $tryNumeric); return; } $columnLetter = Coordinate::stringFromColumnIndex((int) $column); /** @var string */ $cellData = Calculation::unwrapResult($cellData); // Set cell value $this->processCFinal($spreadsheet, $hasCalculatedValue, $cellDataFormula, $cellData, "$columnLetter$row", $tryNumeric); } private function processCFinal(Spreadsheet &$spreadsheet, bool $hasCalculatedValue, string $cellDataFormula, string $cellData, string $coordinate, bool $tryNumeric): void { // Set cell value $spreadsheet->getActiveSheet()->getCell($coordinate)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); if ($hasCalculatedValue) { $cellData = Calculation::unwrapResult($cellData); $spreadsheet->getActiveSheet()->getCell($coordinate)->setCalculatedValue($cellData, $tryNumeric); } } /** @param mixed[] $rowData */ private function processFRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void { // Read cell formatting $formatStyle = $columnWidth = ''; $startCol = $endCol = ''; $fontStyle = ''; $styleData = []; foreach ($rowData as $rowDatum) { /** @var string $rowDatum */ switch ($rowDatum[0]) { case 'C': case 'X': $column = substr($rowDatum, 1); break; case 'R': case 'Y': $row = substr($rowDatum, 1); break; case 'P': $formatStyle = $rowDatum; break; case 'W': [$startCol, $endCol, $columnWidth] = explode(' ', substr($rowDatum, 1)); break; case 'S': $this->styleSettings($rowDatum, $styleData, $fontStyle); break; } } /** @var string $formatStyle */ $this->addFormats($spreadsheet, $formatStyle, $row, $column); $this->addFonts($spreadsheet, $fontStyle, $row, $column); $this->addStyle($spreadsheet, $styleData, $row, $column); $this->addWidth($spreadsheet, $columnWidth, $startCol, $endCol); } private const STYLE_SETTINGS_FONT = ['D' => 'bold', 'I' => 'italic']; private const STYLE_SETTINGS_BORDER = [ 'B' => 'bottom', 'L' => 'left', 'R' => 'right', 'T' => 'top', ]; /** @param mixed[][] $styleData */ private function styleSettings(string $rowDatum, array &$styleData, string &$fontStyle): void { $styleSettings = substr($rowDatum, 1); $iMax = strlen($styleSettings); for ($i = 0; $i < $iMax; ++$i) { $char = $styleSettings[$i]; if (array_key_exists($char, self::STYLE_SETTINGS_FONT)) { $styleData['font'][self::STYLE_SETTINGS_FONT[$char]] = true; } elseif (array_key_exists($char, self::STYLE_SETTINGS_BORDER)) { $styleData['borders'][self::STYLE_SETTINGS_BORDER[$char]]['borderStyle'] = Border::BORDER_THIN; //* @phpstan-ignore-line } elseif ($char == 'S') { $styleData['fill']['fillType'] = Fill::FILL_PATTERN_GRAY125; } elseif ($char == 'M') { if (preg_match('/M([1-9]\d*)/', $styleSettings, $matches)) { $fontStyle = $matches[1]; } } } } private function addFormats(Spreadsheet &$spreadsheet, string $formatStyle, string $row, string $column): void { if ($formatStyle && $column > '' && $row > '') { $columnLetter = Coordinate::stringFromColumnIndex((int) $column); if (isset($this->formats[$formatStyle]) && is_array($this->formats[$formatStyle])) { $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]); } } } private function addFonts(Spreadsheet &$spreadsheet, string $fontStyle, string $row, string $column): void { if ($fontStyle && $column > '' && $row > '') { $columnLetter = Coordinate::stringFromColumnIndex((int) $column); if (isset($this->fonts[$fontStyle]) && is_array($this->fonts[$fontStyle])) { $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->fonts[$fontStyle]); } } } /** @param mixed[] $styleData */ private function addStyle(Spreadsheet &$spreadsheet, array $styleData, string $row, string $column): void { if ((!empty($styleData)) && $column > '' && $row > '') { $columnLetter = Coordinate::stringFromColumnIndex((int) $column); $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData); } } private function addWidth(Spreadsheet $spreadsheet, string $columnWidth, string $startCol, string $endCol): void { if ($columnWidth > '') { if ($startCol == $endCol) { $startCol = Coordinate::stringFromColumnIndex((int) $startCol); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); } else { $startCol = Coordinate::stringFromColumnIndex((int) $startCol); $endCol = Coordinate::stringFromColumnIndex((int) $endCol); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); do { /** @var string $startCol */ $spreadsheet->getActiveSheet() ->getColumnDimension( StringHelper::stringIncrement($startCol) ) ->setWidth((float) $columnWidth); } while ($startCol !== $endCol); } } } /** @param string[] $rowData */ private function processPRecord(array $rowData, Spreadsheet &$spreadsheet): void { // Read shared styles $formatArray = []; $fromFormats = ['\-', '\ ']; $toFormats = ['-', ' ']; foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'P': $formatArray['numberFormat']['formatCode'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1)); break; case 'E': case 'F': $formatArray['font']['name'] = substr($rowDatum, 1); break; case 'M': $formatArray['font']['size'] = ((float) substr($rowDatum, 1)) / 20; break; case 'L': /** @var mixed[][][] $formatArray */ $this->processPColors($rowDatum, $formatArray); break; case 'S': $this->processPFontStyles($rowDatum, $formatArray); break; } } $this->processPFinal($spreadsheet, $formatArray); } /** @param mixed[][][] $formatArray */ private function processPColors(string $rowDatum, array &$formatArray): void { if (preg_match('/L([1-9]\d*)/', $rowDatum, $matches)) { $fontColor = ((int) $matches[1]) % 8; $formatArray['font']['color']['argb'] = self::COLOR_ARRAY[$fontColor]; } } /** @param mixed[][] $formatArray */ private function processPFontStyles(string $rowDatum, array &$formatArray): void { $styleSettings = substr($rowDatum, 1); $iMax = strlen($styleSettings); for ($i = 0; $i < $iMax; ++$i) { if (array_key_exists($styleSettings[$i], self::FONT_STYLE_MAPPINGS)) { $formatArray['font'][self::FONT_STYLE_MAPPINGS[$styleSettings[$i]]] = true; } } } /** @param mixed[] $formatArray */ private function processPFinal(Spreadsheet &$spreadsheet, array $formatArray): void { if (array_key_exists('numberFormat', $formatArray)) { $this->formats['P' . $this->format] = $formatArray; ++$this->format; } elseif (array_key_exists('font', $formatArray)) { ++$this->fontcount; $this->fonts[$this->fontcount] = $formatArray; if ($this->fontcount === 1) { $spreadsheet->getDefaultStyle()->applyFromArray($formatArray); } } } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { // Open file $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); // Create new Worksheets while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); $spreadsheet->getActiveSheet()->setTitle(substr(basename($filename, '.slk'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH)); // Loop through file $column = $row = ''; // loop through one row (line) at a time in the file while (($rowDataTxt = fgets($fileHandle)) !== false) { // convert SYLK encoded $rowData to UTF-8 $rowDataTxt = StringHelper::SYLKtoUTF8($rowDataTxt); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowDataTxt))))); $dataType = array_shift($rowData); if ($dataType == 'P') { // Read shared styles $this->processPRecord($rowData, $spreadsheet); } elseif ($dataType == 'C') { // Read cell value data $this->processCRecord($rowData, $spreadsheet, $row, $column); } elseif ($dataType == 'F') { // Read cell formatting $this->processFRecord($rowData, $spreadsheet, $row, $column); } else { $this->columnRowFromRowData($rowData, $column, $row); } } // Close file fclose($fileHandle); // Return return $spreadsheet; } /** @param string[] $rowData */ private function columnRowFromRowData(array $rowData, string &$column, string &$row): void { foreach ($rowData as $rowDatum) { $char0 = $rowDatum[0]; if ($char0 === 'X' || $char0 == 'C') { $column = substr($rowDatum, 1); } elseif ($char0 === 'Y' || $char0 == 'R') { $row = substr($rowDatum, 1); } } } /** * Get sheet index. */ public function getSheetIndex(): int { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex(int $sheetIndex): static { $this->sheetIndex = $sheetIndex; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Biff5.php ================================================ $lr || $fc > $lc) { throw new ReaderException('Not a cell range address'); } // column index to letter $fc = Coordinate::stringFromColumnIndex($fc + 1); $lc = Coordinate::stringFromColumnIndex($lc + 1); if ($fr == $lr && $fc == $lc) { return "$fc$fr"; } return "$fc$fr:$lc$lr"; } /** * Read BIFF5 cell range address list * section 2.5.15. * * @return array{size: int, cellRangeAddresses: string[]} */ public static function readBIFF5CellRangeAddressList(string $subData): array { $cellRangeAddresses = []; // offset: 0; size: 2; number of the following cell range addresses $nm = self::getUInt2d($subData, 0); $offset = 2; // offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses for ($i = 0; $i < $nm; ++$i) { $cellRangeAddresses[] = self::readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6)); $offset += 6; } return [ 'size' => 2 + 6 * $nm, 'cellRangeAddresses' => $cellRangeAddresses, ]; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Biff8.php ================================================ '{1,2;3,4}', 'size' => 40] * section 2.5.8. * * @return array{value: string, size: int} */ protected static function readBIFF8ConstantArray(string $arrayData): array { // offset: 0; size: 1; number of columns decreased by 1 $nc = ord($arrayData[0]); // offset: 1; size: 2; number of rows decreased by 1 $nr = self::getUInt2d($arrayData, 1); $size = 3; // initialize $arrayData = substr($arrayData, 3); // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values $matrixChunks = []; for ($r = 1; $r <= $nr + 1; ++$r) { $items = []; for ($c = 1; $c <= $nc + 1; ++$c) { $constant = self::readBIFF8Constant($arrayData); $items[] = $constant['value']; $arrayData = substr($arrayData, $constant['size']); $size += $constant['size']; } $matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"' } $matrix = '{' . implode(';', $matrixChunks) . '}'; return [ 'value' => $matrix, 'size' => $size, ]; } /** * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value' * section 2.5.7 * returns e.g. ['value' => '5', 'size' => 9]. * * @return array{value: bool|float|int|string, size: int} */ private static function readBIFF8Constant(string $valueData): array { // offset: 0; size: 1; identifier for type of constant $identifier = ord($valueData[0]); switch ($identifier) { case 0x00: // empty constant (what is this?) $value = ''; $size = 9; break; case 0x01: // number // offset: 1; size: 8; IEEE 754 floating-point value $value = self::extractNumber(substr($valueData, 1, 8)); $size = 9; break; case 0x02: // string value // offset: 1; size: var; Unicode string, 16-bit string length $string = self::readUnicodeStringLong(substr($valueData, 1)); $value = '"' . $string['value'] . '"'; $size = 1 + $string['size']; break; case 0x04: // boolean // offset: 1; size: 1; 0 = FALSE, 1 = TRUE if (ord($valueData[1])) { $value = 'TRUE'; } else { $value = 'FALSE'; } $size = 9; break; case 0x10: // error code // offset: 1; size: 1; error code $value = ErrorCode::lookup(ord($valueData[1])); $size = 9; break; default: throw new ReaderException('Unsupported BIFF8 constant'); } return [ 'value' => $value, 'size' => $size, ]; } /** * Read BIFF8 cell range address list * section 2.5.15. * * @return array{size: int, cellRangeAddresses: mixed[]} */ public static function readBIFF8CellRangeAddressList(string $subData): array { $cellRangeAddresses = []; // offset: 0; size: 2; number of the following cell range addresses $nm = self::getUInt2d($subData, 0); $offset = 2; // offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses for ($i = 0; $i < $nm; ++$i) { $cellRangeAddresses[] = self::readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8)); $offset += 8; } return [ 'size' => 2 + 8 * $nm, 'cellRangeAddresses' => $cellRangeAddresses, ]; } /** * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2' * section 3.3.4. */ protected static function readBIFF8CellAddress(string $cellAddressStructure): string { // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) $row = self::getUInt2d($cellAddressStructure, 0) + 1; // offset: 2; size: 2; index to column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $column = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($cellAddressStructure, 2)) + 1); // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) { $column = '$' . $column; } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) { $row = '$' . $row; } return $column . $row; } /** * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column * to indicate offsets from a base cell * section 3.3.4. * * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas */ protected static function readBIFF8CellAddressB(string $cellAddressStructure, string $baseCell = 'A1'): string { [$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell); $baseCol = Coordinate::columnIndexFromString($baseCol) - 1; $baseRow = (int) $baseRow; // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) $rowIndex = self::getUInt2d($cellAddressStructure, 0); $row = self::getUInt2d($cellAddressStructure, 0) + 1; // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) { // offset: 2; size: 2; index to column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $colIndex = 0x00FF & self::getUInt2d($cellAddressStructure, 2); $column = Coordinate::stringFromColumnIndex($colIndex + 1); $column = '$' . $column; } else { // offset: 2; size: 2; index to column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $relativeColIndex = 0x00FF & self::getInt2d($cellAddressStructure, 2); $colIndex = $baseCol + $relativeColIndex; $colIndex = ($colIndex < 256) ? $colIndex : $colIndex - 256; $colIndex = ($colIndex >= 0) ? $colIndex : $colIndex + 256; $column = Coordinate::stringFromColumnIndex($colIndex + 1); } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) { $row = '$' . $row; } else { $rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536; $row = $baseRow + $rowIndex; } return $column . $row; } /** * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1' * always fixed range * section 2.5.14. */ protected static function readBIFF8CellRangeAddressFixed(string $subData): string { // offset: 0; size: 2; index to first row $fr = self::getUInt2d($subData, 0) + 1; // offset: 2; size: 2; index to last row $lr = self::getUInt2d($subData, 2) + 1; // offset: 4; size: 2; index to first column $fc = self::getUInt2d($subData, 4); // offset: 6; size: 2; index to last column $lc = self::getUInt2d($subData, 6); // check values if ($fr > $lr || $fc > $lc) { throw new ReaderException('Not a cell range address'); } // column index to letter $fc = Coordinate::stringFromColumnIndex($fc + 1); $lc = Coordinate::stringFromColumnIndex($lc + 1); if ($fr == $lr && $fc == $lc) { return "$fc$fr"; } return "$fc$fr:$lc$lr"; } /** * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6' * there are flags indicating whether column/row index is relative * section 3.3.4. */ protected static function readBIFF8CellRangeAddress(string $subData): string { // todo: if cell range is just a single cell, should this function // not just return e.g. 'A1' and not 'A1:A1' ? // offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767)) $fr = self::getUInt2d($subData, 0) + 1; // offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767)) $lr = self::getUInt2d($subData, 2) + 1; // offset: 4; size: 2; index to first column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $fc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 4)) + 1); // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 4))) { $fc = '$' . $fc; } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 4))) { $fr = '$' . $fr; } // offset: 6; size: 2; index to last column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $lc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 6)) + 1); // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 6))) { $lc = '$' . $lc; } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 6))) { $lr = '$' . $lr; } return "$fc$fr:$lc$lr"; } /** * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column * to indicate offsets from a base cell * section 3.3.4. * * @param string $baseCell Base cell * * @return string Cell range address */ protected static function readBIFF8CellRangeAddressB(string $subData, string $baseCell = 'A1'): string { [$baseCol, $baseRow] = Coordinate::indexesFromString($baseCell); $baseCol = $baseCol - 1; // TODO: if cell range is just a single cell, should this function // not just return e.g. 'A1' and not 'A1:A1' ? // offset: 0; size: 2; first row $frIndex = self::getUInt2d($subData, 0); // adjust below // offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767) $lrIndex = self::getUInt2d($subData, 2); // adjust below // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 4))) { // absolute column index // offset: 4; size: 2; first column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $fcIndex = 0x00FF & self::getUInt2d($subData, 4); $fc = Coordinate::stringFromColumnIndex($fcIndex + 1); $fc = '$' . $fc; } else { // column offset // offset: 4; size: 2; first column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $relativeFcIndex = 0x00FF & self::getInt2d($subData, 4); $fcIndex = $baseCol + $relativeFcIndex; $fcIndex = ($fcIndex < 256) ? $fcIndex : $fcIndex - 256; $fcIndex = ($fcIndex >= 0) ? $fcIndex : $fcIndex + 256; $fc = Coordinate::stringFromColumnIndex($fcIndex + 1); } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 4))) { // absolute row index $fr = $frIndex + 1; $fr = '$' . $fr; } else { // row offset $frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536; $fr = $baseRow + $frIndex; } // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 6))) { // absolute column index // offset: 6; size: 2; last column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $lcIndex = 0x00FF & self::getUInt2d($subData, 6); $lc = Coordinate::stringFromColumnIndex($lcIndex + 1); $lc = '$' . $lc; } else { // column offset // offset: 6; size: 2; last column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $relativeLcIndex = 0x00FF & self::getInt2d($subData, 6); $lcIndex = $baseCol + $relativeLcIndex; $lcIndex = ($lcIndex < 256) ? $lcIndex : $lcIndex - 256; $lcIndex = ($lcIndex >= 0) ? $lcIndex : $lcIndex + 256; $lc = Coordinate::stringFromColumnIndex($lcIndex + 1); } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 6))) { // absolute row index $lr = $lrIndex + 1; $lr = '$' . $lr; } else { // row offset $lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536; $lr = $baseRow + $lrIndex; } return "$fc$fr:$lc$lr"; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Color/BIFF5.php ================================================ '000000', 0x09 => 'FFFFFF', 0x0A => 'FF0000', 0x0B => '00FF00', 0x0C => '0000FF', 0x0D => 'FFFF00', 0x0E => 'FF00FF', 0x0F => '00FFFF', 0x10 => '800000', 0x11 => '008000', 0x12 => '000080', 0x13 => '808000', 0x14 => '800080', 0x15 => '008080', 0x16 => 'C0C0C0', 0x17 => '808080', 0x18 => '8080FF', 0x19 => '802060', 0x1A => 'FFFFC0', 0x1B => 'A0E0F0', 0x1C => '600080', 0x1D => 'FF8080', 0x1E => '0080C0', 0x1F => 'C0C0FF', 0x20 => '000080', 0x21 => 'FF00FF', 0x22 => 'FFFF00', 0x23 => '00FFFF', 0x24 => '800080', 0x25 => '800000', 0x26 => '008080', 0x27 => '0000FF', 0x28 => '00CFFF', 0x29 => '69FFFF', 0x2A => 'E0FFE0', 0x2B => 'FFFF80', 0x2C => 'A6CAF0', 0x2D => 'DD9CB3', 0x2E => 'B38FEE', 0x2F => 'E3E3E3', 0x30 => '2A6FF9', 0x31 => '3FB8CD', 0x32 => '488436', 0x33 => '958C41', 0x34 => '8E5E42', 0x35 => 'A0627A', 0x36 => '624FAC', 0x37 => '969696', 0x38 => '1D2FBE', 0x39 => '286676', 0x3A => '004500', 0x3B => '453E01', 0x3C => '6A2813', 0x3D => '85396A', 0x3E => '4A3285', 0x3F => '424242', ]; /** * Map color array from BIFF5 built-in color index. * * @return array{rgb: string} */ public static function lookup(int $color): array { return ['rgb' => self::BIFF5_COLOR_MAP[$color] ?? '000000']; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Color/BIFF8.php ================================================ '000000', 0x09 => 'FFFFFF', 0x0A => 'FF0000', 0x0B => '00FF00', 0x0C => '0000FF', 0x0D => 'FFFF00', 0x0E => 'FF00FF', 0x0F => '00FFFF', 0x10 => '800000', 0x11 => '008000', 0x12 => '000080', 0x13 => '808000', 0x14 => '800080', 0x15 => '008080', 0x16 => 'C0C0C0', 0x17 => '808080', 0x18 => '9999FF', 0x19 => '993366', 0x1A => 'FFFFCC', 0x1B => 'CCFFFF', 0x1C => '660066', 0x1D => 'FF8080', 0x1E => '0066CC', 0x1F => 'CCCCFF', 0x20 => '000080', 0x21 => 'FF00FF', 0x22 => 'FFFF00', 0x23 => '00FFFF', 0x24 => '800080', 0x25 => '800000', 0x26 => '008080', 0x27 => '0000FF', 0x28 => '00CCFF', 0x29 => 'CCFFFF', 0x2A => 'CCFFCC', 0x2B => 'FFFF99', 0x2C => '99CCFF', 0x2D => 'FF99CC', 0x2E => 'CC99FF', 0x2F => 'FFCC99', 0x30 => '3366FF', 0x31 => '33CCCC', 0x32 => '99CC00', 0x33 => 'FFCC00', 0x34 => 'FF9900', 0x35 => 'FF6600', 0x36 => '666699', 0x37 => '969696', 0x38 => '003366', 0x39 => '339966', 0x3A => '003300', 0x3B => '333300', 0x3C => '993300', 0x3D => '993366', 0x3E => '333399', 0x3F => '333333', ]; /** * Map color array from BIFF8 built-in color index. * * @return array{rgb: string} */ public static function lookup(int $color): array { return ['rgb' => self::BIFF8_COLOR_MAP[$color] ?? '000000']; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Color/BuiltIn.php ================================================ '000000', 0x01 => 'FFFFFF', 0x02 => 'FF0000', 0x03 => '00FF00', 0x04 => '0000FF', 0x05 => 'FFFF00', 0x06 => 'FF00FF', 0x07 => '00FFFF', 0x40 => '000000', // system window text color 0x41 => 'FFFFFF', // system window background color ]; /** * Map built-in color to RGB value. * * @param int $color Indexed color * * @return array{rgb: string} */ public static function lookup(int $color): array { return ['rgb' => self::BUILTIN_COLOR_MAP[$color] ?? '000000']; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Color.php ================================================ 'FF0000'] */ public static function map(int $color, array $palette, int $version): array { if ($color <= 0x07 || $color >= 0x40) { // special built-in color return Color\BuiltIn::lookup($color); } elseif (isset($palette[$color - 8])) { // palette color, color index 0x08 maps to pallete index 0 return $palette[$color - 8]; } return ($version === Xls::XLS_BIFF8) ? Color\BIFF8::lookup($color) : Color\BIFF5::lookup($color); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php ================================================ */ private static array $types = [ 0x01 => Conditional::CONDITION_CELLIS, 0x02 => Conditional::CONDITION_EXPRESSION, ]; /** * @var array */ private static array $operators = [ 0x00 => Conditional::OPERATOR_NONE, 0x01 => Conditional::OPERATOR_BETWEEN, 0x02 => Conditional::OPERATOR_NOTBETWEEN, 0x03 => Conditional::OPERATOR_EQUAL, 0x04 => Conditional::OPERATOR_NOTEQUAL, 0x05 => Conditional::OPERATOR_GREATERTHAN, 0x06 => Conditional::OPERATOR_LESSTHAN, 0x07 => Conditional::OPERATOR_GREATERTHANOREQUAL, 0x08 => Conditional::OPERATOR_LESSTHANOREQUAL, ]; public static function type(int $type): ?string { return self::$types[$type] ?? null; } public static function operator(int $operator): ?string { return self::$operators[$operator] ?? null; } /** * Parse conditional formatting blocks. * * @see https://www.openoffice.org/sc/excelfileformat.pdf Search for CFHEADER followed by CFRULE * * @return mixed[] */ protected function readCFHeader2(Xls $xls): array { $length = self::getUInt2d($xls->data, $xls->pos + 2); $recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length); // move stream pointer forward to next record $xls->pos += 4 + $length; if ($xls->readDataOnly) { return []; } // offset: 0; size: 2; Rule Count // $ruleCount = self::getUInt2d($recordData, 0); // offset: var; size: var; cell range address list with $cellRangeAddressList = ($xls->version == self::XLS_BIFF8) ? Biff8::readBIFF8CellRangeAddressList(substr($recordData, 12)) : Biff5::readBIFF5CellRangeAddressList(substr($recordData, 12)); $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; return $cellRangeAddresses; } /** @param string[] $cellRangeAddresses */ protected function readCFRule2(array $cellRangeAddresses, Xls $xls): void { $length = self::getUInt2d($xls->data, $xls->pos + 2); $recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length); // move stream pointer forward to next record $xls->pos += 4 + $length; if ($xls->readDataOnly) { return; } // offset: 0; size: 2; Options $cfRule = self::getUInt2d($recordData, 0); // bit: 8-15; mask: 0x00FF; type $type = (0x00FF & $cfRule) >> 0; $type = self::type($type); // bit: 0-7; mask: 0xFF00; type $operator = (0xFF00 & $cfRule) >> 8; $operator = self::operator($operator); if ($type === null || $operator === null) { return; } // offset: 2; size: 2; Size1 $size1 = self::getUInt2d($recordData, 2); // offset: 4; size: 2; Size2 $size2 = self::getUInt2d($recordData, 4); // offset: 6; size: 4; Options $options = self::getInt4d($recordData, 6); $style = new Style(false, true); // non-supervisor, conditional $noFormatSet = true; //$xls->getCFStyleOptions($options, $style); $hasFontRecord = (bool) ((0x04000000 & $options) >> 26); $hasAlignmentRecord = (bool) ((0x08000000 & $options) >> 27); $hasBorderRecord = (bool) ((0x10000000 & $options) >> 28); $hasFillRecord = (bool) ((0x20000000 & $options) >> 29); $hasProtectionRecord = (bool) ((0x40000000 & $options) >> 30); // note unexpected values for following 4 $hasBorderLeft = !(bool) (0x00000400 & $options); $hasBorderRight = !(bool) (0x00000800 & $options); $hasBorderTop = !(bool) (0x00001000 & $options); $hasBorderBottom = !(bool) (0x00002000 & $options); $offset = 12; if ($hasFontRecord === true) { $fontStyle = substr($recordData, $offset, 118); $this->getCFFontStyle($fontStyle, $style, $xls); $offset += 118; $noFormatSet = false; } if ($hasAlignmentRecord === true) { //$alignmentStyle = substr($recordData, $offset, 8); //$this->getCFAlignmentStyle($alignmentStyle, $style, $xls); $offset += 8; } if ($hasBorderRecord === true) { $borderStyle = substr($recordData, $offset, 8); $this->getCFBorderStyle($borderStyle, $style, $hasBorderLeft, $hasBorderRight, $hasBorderTop, $hasBorderBottom, $xls); $offset += 8; $noFormatSet = false; } if ($hasFillRecord === true) { $fillStyle = substr($recordData, $offset, 4); $this->getCFFillStyle($fillStyle, $style, $xls); $offset += 4; $noFormatSet = false; } if ($hasProtectionRecord === true) { //$protectionStyle = substr($recordData, $offset, 4); //$this->getCFProtectionStyle($protectionStyle, $style, $xls); $offset += 2; } $formula1 = $formula2 = null; if ($size1 > 0) { $formula1 = $this->readCFFormula($recordData, $offset, $size1, $xls); if ($formula1 === null) { return; } $offset += $size1; } if ($size2 > 0) { $formula2 = $this->readCFFormula($recordData, $offset, $size2, $xls); if ($formula2 === null) { return; } $offset += $size2; } $this->setCFRules($cellRangeAddresses, $type, $operator, $formula1, $formula2, $style, $noFormatSet, $xls); } /*private function getCFStyleOptions(int $options, Style $style, Xls $xls): void { }*/ private function getCFFontStyle(string $options, Style $style, Xls $xls): void { $fontSize = self::getInt4d($options, 64); if ($fontSize !== -1) { $style->getFont()->setSize($fontSize / 20); // Convert twips to points } $options68 = self::getInt4d($options, 68); $options88 = self::getInt4d($options, 88); if (($options88 & 2) === 0) { $bold = self::getUInt2d($options, 72); // 400 = normal, 700 = bold if ($bold !== 0) { $style->getFont()->setBold($bold >= 550); } if (($options68 & 2) !== 0) { $style->getFont()->setItalic(true); } } if (($options88 & 0x80) === 0) { if (($options68 & 0x80) !== 0) { $style->getFont()->setStrikethrough(true); } } $color = self::getInt4d($options, 80); if ($color !== -1) { $style->getFont() ->getColor() ->setRGB(Color::map($color, $xls->palette, $xls->version)['rgb']); } } /*private function getCFAlignmentStyle(string $options, Style $style, Xls $xls): void { }*/ private function getCFBorderStyle(string $options, Style $style, bool $hasBorderLeft, bool $hasBorderRight, bool $hasBorderTop, bool $hasBorderBottom, Xls $xls): void { /** @var false|int[] */ $valueArray = unpack('V', $options); $value = is_array($valueArray) ? $valueArray[1] : 0; $left = $value & 15; $right = ($value >> 4) & 15; $top = ($value >> 8) & 15; $bottom = ($value >> 12) & 15; $leftc = ($value >> 16) & 0x7F; $rightc = ($value >> 23) & 0x7F; /** @var false|int[] */ $valueArray = unpack('V', substr($options, 4)); $value = is_array($valueArray) ? $valueArray[1] : 0; $topc = $value & 0x7F; $bottomc = ($value & 0x3F80) >> 7; if ($hasBorderLeft) { $style->getBorders()->getLeft() ->setBorderStyle(self::BORDER_STYLE_MAP[$left]); $style->getBorders()->getLeft()->getColor() ->setRGB(Color::map($leftc, $xls->palette, $xls->version)['rgb']); } if ($hasBorderRight) { $style->getBorders()->getRight() ->setBorderStyle(self::BORDER_STYLE_MAP[$right]); $style->getBorders()->getRight()->getColor() ->setRGB(Color::map($rightc, $xls->palette, $xls->version)['rgb']); } if ($hasBorderTop) { $style->getBorders()->getTop() ->setBorderStyle(self::BORDER_STYLE_MAP[$top]); $style->getBorders()->getTop()->getColor() ->setRGB(Color::map($topc, $xls->palette, $xls->version)['rgb']); } if ($hasBorderBottom) { $style->getBorders()->getBottom() ->setBorderStyle(self::BORDER_STYLE_MAP[$bottom]); $style->getBorders()->getBottom()->getColor() ->setRGB(Color::map($bottomc, $xls->palette, $xls->version)['rgb']); } } private function getCFFillStyle(string $options, Style $style, Xls $xls): void { $fillPattern = self::getUInt2d($options, 0); // bit: 10-15; mask: 0xFC00; type $fillPattern = (0xFC00 & $fillPattern) >> 10; $fillPattern = FillPattern::lookup($fillPattern); $fillPattern = $fillPattern === Fill::FILL_NONE ? Fill::FILL_SOLID : $fillPattern; if ($fillPattern !== Fill::FILL_NONE) { $style->getFill()->setFillType($fillPattern); $fillColors = self::getUInt2d($options, 2); // bit: 0-6; mask: 0x007F; type $color1 = (0x007F & $fillColors) >> 0; // bit: 7-13; mask: 0x3F80; type $color2 = (0x3F80 & $fillColors) >> 7; if ($fillPattern === Fill::FILL_SOLID) { $style->getFill()->getStartColor()->setRGB(Color::map($color2, $xls->palette, $xls->version)['rgb']); } else { $style->getFill()->getStartColor()->setRGB(Color::map($color1, $xls->palette, $xls->version)['rgb']); $style->getFill()->getEndColor()->setRGB(Color::map($color2, $xls->palette, $xls->version)['rgb']); } } } /*private function getCFProtectionStyle(string $options, Style $style, Xls $xls): void { }*/ private function readCFFormula(string $recordData, int $offset, int $size, Xls $xls): float|int|string|null { try { $formula = substr($recordData, $offset, $size); $formula = pack('v', $size) . $formula; // prepend the length $formula = $xls->getFormulaFromStructure($formula); if (is_numeric($formula)) { return (str_contains($formula, '.')) ? (float) $formula : (int) $formula; } return $formula; } catch (PhpSpreadsheetException) { return null; } } /** @param string[] $cellRanges */ private function setCFRules(array $cellRanges, string $type, string $operator, null|float|int|string $formula1, null|float|int|string $formula2, Style $style, bool $noFormatSet, Xls $xls): void { foreach ($cellRanges as $cellRange) { $conditional = new Conditional(); $conditional->setNoFormatSet($noFormatSet); $conditional->setConditionType($type); $conditional->setOperatorType($operator); $conditional->setStopIfTrue(true); if ($formula1 !== null) { $conditional->addCondition($formula1); } if ($formula2 !== null) { $conditional->addCondition($formula2); } $conditional->setStyle($style); $conditionalStyles = $xls->phpSheet ->getStyle($cellRange) ->getConditionalStyles(); $conditionalStyles[] = $conditional; $xls->phpSheet ->getStyle($cellRange) ->setConditionalStyles($conditionalStyles); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/DataValidationHelper.php ================================================ */ private static array $types = [ 0x00 => DataValidation::TYPE_NONE, 0x01 => DataValidation::TYPE_WHOLE, 0x02 => DataValidation::TYPE_DECIMAL, 0x03 => DataValidation::TYPE_LIST, 0x04 => DataValidation::TYPE_DATE, 0x05 => DataValidation::TYPE_TIME, 0x06 => DataValidation::TYPE_TEXTLENGTH, 0x07 => DataValidation::TYPE_CUSTOM, ]; /** * @var array */ private static array $errorStyles = [ 0x00 => DataValidation::STYLE_STOP, 0x01 => DataValidation::STYLE_WARNING, 0x02 => DataValidation::STYLE_INFORMATION, ]; /** * @var array */ private static array $operators = [ 0x00 => DataValidation::OPERATOR_BETWEEN, 0x01 => DataValidation::OPERATOR_NOTBETWEEN, 0x02 => DataValidation::OPERATOR_EQUAL, 0x03 => DataValidation::OPERATOR_NOTEQUAL, 0x04 => DataValidation::OPERATOR_GREATERTHAN, 0x05 => DataValidation::OPERATOR_LESSTHAN, 0x06 => DataValidation::OPERATOR_GREATERTHANOREQUAL, 0x07 => DataValidation::OPERATOR_LESSTHANOREQUAL, ]; public static function type(int $type): ?string { return self::$types[$type] ?? null; } public static function errorStyle(int $errorStyle): ?string { return self::$errorStyles[$errorStyle] ?? null; } public static function operator(int $operator): ?string { return self::$operators[$operator] ?? null; } /** * Read DATAVALIDATION record. */ protected function readDataValidation2(Xls $xls): void { $length = self::getUInt2d($xls->data, $xls->pos + 2); $recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length); // move stream pointer forward to next record $xls->pos += 4 + $length; if ($xls->readDataOnly) { return; } // offset: 0; size: 4; Options $options = self::getInt4d($recordData, 0); // bit: 0-3; mask: 0x0000000F; type $type = (0x0000000F & $options) >> 0; $type = self::type($type); // bit: 4-6; mask: 0x00000070; error type $errorStyle = (0x00000070 & $options) >> 4; $errorStyle = self::errorStyle($errorStyle); // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list) // I have only seen cases where this is 1 //$explicitFormula = (0x00000080 & $options) >> 7; // bit: 8; mask: 0x00000100; 1= empty cells allowed $allowBlank = (0x00000100 & $options) >> 8; // bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity $suppressDropDown = (0x00000200 & $options) >> 9; // bit: 18; mask: 0x00040000; 1= show prompt box if cell selected $showInputMessage = (0x00040000 & $options) >> 18; // bit: 19; mask: 0x00080000; 1= show error box if invalid values entered $showErrorMessage = (0x00080000 & $options) >> 19; // bit: 20-23; mask: 0x00F00000; condition operator $operator = (0x00F00000 & $options) >> 20; $operator = self::operator($operator); if ($type === null || $errorStyle === null || $operator === null) { return; } // offset: 4; size: var; title of the prompt box $offset = 4; $string = self::readUnicodeStringLong(substr($recordData, $offset)); $promptTitle = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: var; title of the error box $string = self::readUnicodeStringLong(substr($recordData, $offset)); $errorTitle = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: var; text of the prompt box $string = self::readUnicodeStringLong(substr($recordData, $offset)); $prompt = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: var; text of the error box $string = self::readUnicodeStringLong(substr($recordData, $offset)); $error = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: 2; size of the formula data for the first condition $sz1 = self::getUInt2d($recordData, $offset); $offset += 2; // offset: var; size: 2; not used $offset += 2; // offset: var; size: $sz1; formula data for first condition (without size field) $formula1 = substr($recordData, $offset, $sz1); $formula1 = pack('v', $sz1) . $formula1; // prepend the length try { $formula1 = $xls->getFormulaFromStructure($formula1); // in list type validity, null characters are used as item separators if ($type == DataValidation::TYPE_LIST) { $formula1 = str_replace(chr(0), ',', $formula1); } } catch (PhpSpreadsheetException $e) { return; } $offset += $sz1; // offset: var; size: 2; size of the formula data for the first condition $sz2 = self::getUInt2d($recordData, $offset); $offset += 2; // offset: var; size: 2; not used $offset += 2; // offset: var; size: $sz2; formula data for second condition (without size field) $formula2 = substr($recordData, $offset, $sz2); $formula2 = pack('v', $sz2) . $formula2; // prepend the length try { $formula2 = $xls->getFormulaFromStructure($formula2); } catch (PhpSpreadsheetException) { return; } $offset += $sz2; // offset: var; size: var; cell range address list with $cellRangeAddressList = Biff8::readBIFF8CellRangeAddressList(substr($recordData, $offset)); /** @var string[] */ $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; $maxRow = (string) AddressRange::MAX_ROW; $maxCol = AddressRange::MAX_COLUMN; $maxXlsRow = (string) AddressRange::MAX_ROW_XLS; $maxXlsColumnString = AddressRange::MAX_COLUMN_XLS; foreach ($cellRangeAddresses as $cellRange) { $cellRange = preg_replace( [ "/([a-z]+)1:([a-z]+)$maxXlsRow/i", "/([a-z]+\\d+):([a-z]+)$maxXlsRow/i", "/A(\\d+):$maxXlsColumnString(\\d+)/i", "/([a-z]+\\d+):$maxXlsColumnString(\\d+)/i", ], [ '$1:$2', '$1:${2}' . $maxRow, '$1:$2', '$1:' . $maxCol . '$2', ], $cellRange ) ?? $cellRange; $objValidation = new DataValidation(); $objValidation->setType($type); $objValidation->setErrorStyle($errorStyle); $objValidation->setAllowBlank((bool) $allowBlank); $objValidation->setShowInputMessage((bool) $showInputMessage); $objValidation->setShowErrorMessage((bool) $showErrorMessage); $objValidation->setShowDropDown(!$suppressDropDown); $objValidation->setOperator($operator); $objValidation->setErrorTitle($errorTitle); $objValidation->setError($error); $objValidation->setPromptTitle($promptTitle); $objValidation->setPrompt($prompt); $objValidation->setFormula1($formula1); $objValidation->setFormula2($formula2); $xls->phpSheet->setDataValidation($cellRange, $objValidation); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/ErrorCode.php ================================================ '#NULL!', 0x07 => '#DIV/0!', 0x0F => '#VALUE!', 0x17 => '#REF!', 0x1D => '#NAME?', 0x24 => '#NUM!', 0x2A => '#N/A', ]; /** * Map error code, e.g. '#N/A'. */ public static function lookup(int $code): string|bool { return self::ERROR_CODE_MAP[$code] ?? false; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Escher.php ================================================ object = $object; } private const WHICH_ROUTINE = [ self::DGGCONTAINER => 'readDggContainer', self::DGG => 'readDgg', self::BSTORECONTAINER => 'readBstoreContainer', self::BSE => 'readBSE', self::BLIPJPEG => 'readBlipJPEG', self::BLIPPNG => 'readBlipPNG', self::OPT => 'readOPT', self::TERTIARYOPT => 'readTertiaryOPT', self::SPLITMENUCOLORS => 'readSplitMenuColors', self::DGCONTAINER => 'readDgContainer', self::DG => 'readDg', self::SPGRCONTAINER => 'readSpgrContainer', self::SPCONTAINER => 'readSpContainer', self::SPGR => 'readSpgr', self::SP => 'readSp', self::CLIENTTEXTBOX => 'readClientTextbox', self::CLIENTANCHOR => 'readClientAnchor', self::CLIENTDATA => 'readClientData', ]; /** * Load Escher stream data. May be a partial Escher stream. * * @return T */ public function load(string $data): BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer { $this->data = $data; // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); $this->pos = 0; // Parse Escher stream while ($this->pos < $this->dataSize) { // offset: 2; size: 2: Record Type $fbt = Xls::getUInt2d($this->data, $this->pos + 2); $routine = self::WHICH_ROUTINE[$fbt] ?? 'readDefault'; if (method_exists($this, $routine)) { $this->$routine(); } } return $this->object; } /** * Read a generic record. */ private function readDefault(): void { // offset 0; size: 2; recVer and recInstance //$verInstance = Xls::getUInt2d($this->data, $this->pos); // offset: 2; size: 2: Record Type //$fbt = Xls::getUInt2d($this->data, $this->pos + 2); // bit: 0-3; mask: 0x000F; recVer //$recVer = (0x000F & $verInstance) >> 0; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read DggContainer record (Drawing Group Container). */ private function readDggContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $dggContainer = new DggContainer(); $this->applyAttribute('setDggContainer', $dggContainer); $reader = new self($dggContainer); $reader->load($recordData); } /** * Read Dgg record (Drawing Group). */ private function readDgg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read BstoreContainer record (Blip Store Container). */ private function readBstoreContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $bstoreContainer = new BstoreContainer(); $this->applyAttribute('setBstoreContainer', $bstoreContainer); $reader = new self($bstoreContainer); $reader->load($recordData); } /** * Read BSE record. */ private function readBSE(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // add BSE to BstoreContainer $BSE = new BSE(); $this->applyAttribute('addBSE', $BSE); $BSE->setBLIPType($recInstance); // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) //$btWin32 = ord($recordData[0]); // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) //$btMacOS = ord($recordData[1]); // offset: 2; size: 16; MD4 digest //$rgbUid = substr($recordData, 2, 16); // offset: 18; size: 2; tag //$tag = Xls::getUInt2d($recordData, 18); // offset: 20; size: 4; size of BLIP in bytes //$size = Xls::getInt4d($recordData, 20); // offset: 24; size: 4; number of references to this BLIP //$cRef = Xls::getInt4d($recordData, 24); // offset: 28; size: 4; MSOFO file offset //$foDelay = Xls::getInt4d($recordData, 28); // offset: 32; size: 1; unused1 //$unused1 = ord($recordData[32]); // offset: 33; size: 1; size of nameData in bytes (including null terminator) $cbName = ord($recordData[33]); // offset: 34; size: 1; unused2 //$unused2 = ord($recordData[34]); // offset: 35; size: 1; unused3 //$unused3 = ord($recordData[35]); // offset: 36; size: $cbName; nameData //$nameData = substr($recordData, 36, $cbName); // offset: 36 + $cbName, size: var; the BLIP data $blipData = substr($recordData, 36 + $cbName); // record is a container, read contents $reader = new self($BSE); $reader->load($blipData); } /** * Read BlipJPEG record. Holds raw JPEG image data. */ private function readBlipJPEG(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if (in_array($recInstance, [0x046B, 0x06E3])) { //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); $blip = new Blip(); $blip->setData($data); $this->applyAttribute('setBlip', $blip); } /** * Read BlipPNG record. Holds raw PNG image data. */ private function readBlipPNG(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if ($recInstance == 0x06E1) { //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); $blip = new Blip(); $blip->setData($data); $this->applyAttribute('setBlip', $blip); } /** * Read OPT record. This record may occur within DggContainer record or SpContainer. */ private function readOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $this->readOfficeArtRGFOPTE($recordData, $recInstance); } /** * Read TertiaryOPT record. */ private function readTertiaryOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read SplitMenuColors record. */ private function readSplitMenuColors(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read DgContainer record (Drawing Container). */ private function readDgContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $dgContainer = new DgContainer(); $this->applyAttribute('setDgContainer', $dgContainer); $reader = new self($dgContainer); $reader->load($recordData); } /** * Read Dg record (Drawing). */ private function readDg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read SpgrContainer record (Shape Group Container). */ private function readSpgrContainer(): void { // context is either context DgContainer or SpgrContainer $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $spgrContainer = new SpgrContainer(); if ($this->object instanceof DgContainer) { // DgContainer $this->object->setSpgrContainer($spgrContainer); } elseif ($this->object instanceof SpgrContainer) { // SpgrContainer $this->object->addChild($spgrContainer); } $reader = new self($spgrContainer); $reader->load($recordData); } /** * Read SpContainer record (Shape Container). */ private function readSpContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // add spContainer to spgrContainer $spContainer = new SpContainer(); $this->applyAttribute('addChild', $spContainer); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $reader = new self($spContainer); $reader->load($recordData); } /** * Read Spgr record (Shape Group). */ private function readSpgr(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read Sp record (Shape). */ private function readSp(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read ClientTextbox record. */ private function readClientTextbox(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet. */ private function readClientAnchor(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // offset: 2; size: 2; upper-left corner column index (0-based) $c1 = Xls::getUInt2d($recordData, 2); // offset: 4; size: 2; upper-left corner horizontal offset in 1/1024 of column width $startOffsetX = Xls::getUInt2d($recordData, 4); // offset: 6; size: 2; upper-left corner row index (0-based) $r1 = Xls::getUInt2d($recordData, 6); // offset: 8; size: 2; upper-left corner vertical offset in 1/256 of row height $startOffsetY = Xls::getUInt2d($recordData, 8); // offset: 10; size: 2; bottom-right corner column index (0-based) $c2 = Xls::getUInt2d($recordData, 10); // offset: 12; size: 2; bottom-right corner horizontal offset in 1/1024 of column width $endOffsetX = Xls::getUInt2d($recordData, 12); // offset: 14; size: 2; bottom-right corner row index (0-based) $r2 = Xls::getUInt2d($recordData, 14); // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height $endOffsetY = Xls::getUInt2d($recordData, 16); $this->applyAttribute('setStartCoordinates', Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); $this->applyAttribute('setStartOffsetX', $startOffsetX); $this->applyAttribute('setStartOffsetY', $startOffsetY); $this->applyAttribute('setEndCoordinates', Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); $this->applyAttribute('setEndOffsetX', $endOffsetX); $this->applyAttribute('setEndOffsetY', $endOffsetY); } private function applyAttribute(string $name, mixed $value): void { if (method_exists($this->object, $name)) { $this->object->$name($value); } } /** * Read ClientData record. */ private function readClientData(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read OfficeArtRGFOPTE table of property-value pairs. * * @param string $data Binary data * @param int $n Number of properties */ private function readOfficeArtRGFOPTE(string $data, int $n): void { $splicedComplexData = substr($data, 6 * $n); // loop through property-value pairs for ($i = 0; $i < $n; ++$i) { // read 6 bytes at a time $fopte = substr($data, 6 * $i, 6); // offset: 0; size: 2; opid $opid = Xls::getUInt2d($fopte, 0); // bit: 0-13; mask: 0x3FFF; opid.opid $opidOpid = (0x3FFF & $opid) >> 0; // bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier //$opidFBid = (0x4000 & $opid) >> 14; // bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data $opidFComplex = (0x8000 & $opid) >> 15; // offset: 2; size: 4; the value for this property $op = Xls::getInt4d($fopte, 2); if ($opidFComplex) { $complexData = substr($splicedComplexData, 0, $op); $splicedComplexData = substr($splicedComplexData, $op); // we store string value with complex data $value = $complexData; } else { // we store integer value $value = $op; } if (method_exists($this->object, 'setOPT')) { $this->object->setOPT($opidOpid, $value); } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/ListFunctions.php ================================================ loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $xls->dataSize = strlen($xls->data); $xls->pos = 0; $xls->sheets = []; // Parse Workbook Global Substream while ($xls->pos < $xls->dataSize) { $code = self::getUInt2d($xls->data, $xls->pos); match ($code) { self::XLS_TYPE_BOF => $xls->readBof(), self::XLS_TYPE_SHEET => $xls->readSheet(), self::XLS_TYPE_EOF => $xls->readDefault(), self::XLS_TYPE_CODEPAGE => $xls->readCodepage(), default => $xls->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } foreach ($xls->sheets as $sheet) { if ($sheet['sheetType'] === 0x00) { // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module $worksheetNames[] = $sheet['name']; } } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ protected function listWorksheetInfo2(string $filename, Xls $xls): array { File::assertFile($filename); $worksheetInfo = []; // Read the OLE file $xls->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $xls->dataSize = strlen($xls->data); // initialize $xls->pos = 0; $xls->sheets = []; // Parse Workbook Global Substream while ($xls->pos < $xls->dataSize) { $code = self::getUInt2d($xls->data, $xls->pos); match ($code) { self::XLS_TYPE_BOF => $xls->readBof(), self::XLS_TYPE_SHEET => $xls->readSheet(), self::XLS_TYPE_EOF => $xls->readDefault(), self::XLS_TYPE_CODEPAGE => $xls->readCodepage(), default => $xls->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } // Parse the individual sheets foreach ($xls->sheets as $sheet) { if ($sheet['sheetType'] !== 0x00) { // 0x00: Worksheet // 0x02: Chart // 0x06: Visual Basic module continue; } $tmpInfo = []; $tmpInfo['worksheetName'] = StringHelper::convertToString($sheet['name']); $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; $tmpInfo['totalColumns'] = 0; $tmpInfo['sheetState'] = StringHelper::convertToString($sheet['sheetState']); $xls->pos = $sheet['offset']; while ($xls->pos <= $xls->dataSize - 4) { $code = self::getUInt2d($xls->data, $xls->pos); switch ($code) { case self::XLS_TYPE_RK: case self::XLS_TYPE_LABELSST: case self::XLS_TYPE_NUMBER: case self::XLS_TYPE_FORMULA: case self::XLS_TYPE_BOOLERR: case self::XLS_TYPE_LABEL: case self::XLS_TYPE_MULRK: $length = self::getUInt2d($xls->data, $xls->pos + 2); $recordData = $xls->readRecordData($xls->data, $xls->pos + 4, $length); // move stream pointer to next record $xls->pos += 4 + $length; $rowIndex = self::getUInt2d($recordData, 0) + 1; if ($code === self::XLS_TYPE_MULRK) { $columnIndex = self::getUInt2d($recordData, $length - 2); } else { $columnIndex = self::getUInt2d($recordData, 2); } $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); break; case self::XLS_TYPE_BOF: $xls->readBof(); break; case self::XLS_TYPE_EOF: $xls->readDefault(); break 2; default: $xls->readDefault(); break; } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1, true); $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; $worksheetInfo[] = $tmpInfo; } return $worksheetInfo; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ protected function listWorksheetDimensions2(string $filename, Xls $xls): array { File::assertFile($filename); $worksheetInfo = []; // Read the OLE file $xls->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $xls->dataSize = strlen($xls->data); // initialize $xls->pos = 0; $xls->sheets = []; // Parse Workbook Global Substream while ($xls->pos < $xls->dataSize) { $code = self::getUInt2d($xls->data, $xls->pos); match ($code) { self::XLS_TYPE_BOF => $xls->readBof(), self::XLS_TYPE_SHEET => $xls->readSheet(), self::XLS_TYPE_EOF => $xls->readDefault(), self::XLS_TYPE_CODEPAGE => $xls->readCodepage(), default => $xls->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } // Parse the individual sheets foreach ($xls->sheets as $sheet) { if ($sheet['sheetType'] !== 0x00) { // 0x00: Worksheet // 0x02: Chart // 0x06: Visual Basic module continue; } $tmpInfo = []; $tmpInfo['worksheetName'] = StringHelper::convertToString($sheet['name']); $tmpInfo['dimensionsMinR'] = -1; $tmpInfo['dimensionsMaxR'] = -1; $tmpInfo['dimensionsMinC'] = -1; $tmpInfo['dimensionsMaxC'] = -1; $tmpInfo['lastColumnLetter'] = ''; $xls->pos = $sheet['offset']; while ($xls->pos <= $xls->dataSize - 4) { $code = self::getUInt2d($xls->data, $xls->pos); switch ($code) { case self::XLS_TYPE_BOF: $xls->readBof(); break; case self::XLS_TYPE_EOF: $xls->readDefault(); break 2; case self::XLS_TYPE_DIMENSION: $length = self::getUInt2d($xls->data, $xls->pos + 2); if ($length === 14) { $dimensionsData = substr($xls->data, $xls->pos + 4, $length); $data = unpack('VrwMic/VrwMac/vcolMic/vcolMac/vreserved', $dimensionsData); if (is_array($data)) { /** @var int[] $data */ $tmpInfo['dimensionsMinR'] = $data['rwMic']; $tmpInfo['dimensionsMaxR'] = $data['rwMac']; $tmpInfo['dimensionsMinC'] = $data['colMic']; $tmpInfo['dimensionsMaxC'] = $data['colMac']; $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['dimensionsMaxC'], true); } } $xls->readDefault(); break; default: $xls->readDefault(); break; } } $worksheetInfo[] = $tmpInfo; } return $worksheetInfo; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/LoadSpreadsheet.php ================================================ loadOLE($filename); // Initialisations $xls->spreadsheet = $this->newSpreadsheet(); $xls->spreadsheet->setValueBinder($xls->valueBinder); $xls->spreadsheet->removeSheetByIndex(0); // remove 1st sheet if (!$xls->readDataOnly) { $xls->spreadsheet->removeCellStyleXfByIndex(0); // remove the default style $xls->spreadsheet->removeCellXfByIndex(0); // remove the default style } // Read the summary information stream (containing metadata) $xls->readSummaryInformation(); // Read the Additional document summary information stream (containing application-specific metadata) $xls->readDocumentSummaryInformation(); // total byte size of Excel data (workbook global substream + sheet substreams) $xls->dataSize = strlen($xls->data); // initialize $xls->pos = 0; $xls->codepage = $xls->codepage ?: CodePage::DEFAULT_CODE_PAGE; $xls->formats = []; $xls->objFonts = []; $xls->palette = []; $xls->sheets = []; $xls->externalBooks = []; $xls->ref = []; $xls->definedname = []; //* @phpstan-ignore-line $xls->sst = []; $xls->drawingGroupData = ''; $xls->xfIndex = 0; $xls->mapCellXfIndex = []; $xls->mapCellStyleXfIndex = []; // Parse Workbook Global Substream while ($xls->pos < $xls->dataSize) { $code = self::getUInt2d($xls->data, $xls->pos); match ($code) { self::XLS_TYPE_BOF => $xls->readBof(), self::XLS_TYPE_FILEPASS => $xls->readFilepass(), self::XLS_TYPE_CODEPAGE => $xls->readCodepage(), self::XLS_TYPE_DATEMODE => $xls->readDateMode(), self::XLS_TYPE_FONT => $xls->readFont(), self::XLS_TYPE_FORMAT => $xls->readFormat(), self::XLS_TYPE_XF => $xls->readXf(), self::XLS_TYPE_XFEXT => $xls->readXfExt(), self::XLS_TYPE_STYLE => $xls->readStyle(), self::XLS_TYPE_PALETTE => $xls->readPalette(), self::XLS_TYPE_SHEET => $xls->readSheet(), self::XLS_TYPE_EXTERNALBOOK => $xls->readExternalBook(), self::XLS_TYPE_EXTERNNAME => $xls->readExternName(), self::XLS_TYPE_EXTERNSHEET => $xls->readExternSheet(), self::XLS_TYPE_DEFINEDNAME => $xls->readDefinedName(), self::XLS_TYPE_MSODRAWINGGROUP => $xls->readMsoDrawingGroup(), self::XLS_TYPE_SST => $xls->readSst(), self::XLS_TYPE_EOF => $xls->readDefault(), default => $xls->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } // Resolve indexed colors for font, fill, and border colors // Cannot be resolved already in XF record, because PALETTE record comes afterwards if (!$xls->readDataOnly) { foreach ($xls->objFonts as $objFont) { if (isset($objFont->colorIndex)) { $color = Color::map($objFont->colorIndex, $xls->palette, $xls->version); $objFont->getColor()->setRGB($color['rgb']); } } foreach ($xls->spreadsheet->getCellXfCollection() as $objStyle) { // fill start and end color $fill = $objStyle->getFill(); if (isset($fill->startcolorIndex)) { $startColor = Color::map($fill->startcolorIndex, $xls->palette, $xls->version); $fill->getStartColor()->setRGB($startColor['rgb']); } if (isset($fill->endcolorIndex)) { $endColor = Color::map($fill->endcolorIndex, $xls->palette, $xls->version); $fill->getEndColor()->setRGB($endColor['rgb']); } // border colors $top = $objStyle->getBorders()->getTop(); $right = $objStyle->getBorders()->getRight(); $bottom = $objStyle->getBorders()->getBottom(); $left = $objStyle->getBorders()->getLeft(); $diagonal = $objStyle->getBorders()->getDiagonal(); if (isset($top->colorIndex)) { $borderTopColor = Color::map($top->colorIndex, $xls->palette, $xls->version); $top->getColor()->setRGB($borderTopColor['rgb']); } if (isset($right->colorIndex)) { $borderRightColor = Color::map($right->colorIndex, $xls->palette, $xls->version); $right->getColor()->setRGB($borderRightColor['rgb']); } if (isset($bottom->colorIndex)) { $borderBottomColor = Color::map($bottom->colorIndex, $xls->palette, $xls->version); $bottom->getColor()->setRGB($borderBottomColor['rgb']); } if (isset($left->colorIndex)) { $borderLeftColor = Color::map($left->colorIndex, $xls->palette, $xls->version); $left->getColor()->setRGB($borderLeftColor['rgb']); } if (isset($diagonal->colorIndex)) { $borderDiagonalColor = Color::map($diagonal->colorIndex, $xls->palette, $xls->version); $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']); } } } // treat MSODRAWINGGROUP records, workbook-level Escher $escherWorkbook = null; if (!$xls->readDataOnly && $xls->drawingGroupData) { $escher = new SharedEscher(); $reader = new Escher($escher); $escherWorkbook = $reader->load($xls->drawingGroupData); } // Parse the individual sheets $xls->activeSheetSet = false; $sheetCreated = false; foreach ($xls->sheets as $sheet) { $selectedCells = ''; if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module continue; } // check if sheet should be skipped if (isset($xls->loadSheetsOnly) && !in_array($sheet['name'], $xls->loadSheetsOnly)) { continue; } // add sheet to PhpSpreadsheet object $xls->phpSheet = $xls->spreadsheet->createSheet(); $sheetCreated = true; // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet // name in line with the formula, not the reverse $xls->phpSheet->setTitle($sheet['name'], false, false); $xls->phpSheet->setSheetState($sheet['sheetState']); $xls->pos = $sheet['offset']; // Initialize isFitToPages. May change after reading SHEETPR record. $xls->isFitToPages = false; // Initialize drawingData $xls->drawingData = ''; // Initialize objs $xls->objs = []; // Initialize shared formula parts $xls->sharedFormulaParts = []; // Initialize shared formulas $xls->sharedFormulas = []; // Initialize text objs $xls->textObjects = []; // Initialize cell annotations $xls->cellNotes = []; $xls->textObjRef = -1; while ($xls->pos <= $xls->dataSize - 4) { $code = self::getUInt2d($xls->data, $xls->pos); switch ($code) { case self::XLS_TYPE_BOF: $xls->readBof(); break; case self::XLS_TYPE_PRINTGRIDLINES: $xls->readPrintGridlines(); break; case self::XLS_TYPE_DEFAULTROWHEIGHT: $xls->readDefaultRowHeight(); break; case self::XLS_TYPE_SHEETPR: $xls->readSheetPr(); break; case self::XLS_TYPE_HORIZONTALPAGEBREAKS: $xls->readHorizontalPageBreaks(); break; case self::XLS_TYPE_VERTICALPAGEBREAKS: $xls->readVerticalPageBreaks(); break; case self::XLS_TYPE_HEADER: $xls->readHeader(); break; case self::XLS_TYPE_FOOTER: $xls->readFooter(); break; case self::XLS_TYPE_HCENTER: $xls->readHcenter(); break; case self::XLS_TYPE_VCENTER: $xls->readVcenter(); break; case self::XLS_TYPE_LEFTMARGIN: $xls->readLeftMargin(); break; case self::XLS_TYPE_RIGHTMARGIN: $xls->readRightMargin(); break; case self::XLS_TYPE_TOPMARGIN: $xls->readTopMargin(); break; case self::XLS_TYPE_BOTTOMMARGIN: $xls->readBottomMargin(); break; case self::XLS_TYPE_PAGESETUP: $xls->readPageSetup(); break; case self::XLS_TYPE_PROTECT: $xls->readProtect(); break; case self::XLS_TYPE_SCENPROTECT: $xls->readScenProtect(); break; case self::XLS_TYPE_OBJECTPROTECT: $xls->readObjectProtect(); break; case self::XLS_TYPE_PASSWORD: $xls->readPassword(); break; case self::XLS_TYPE_DEFCOLWIDTH: $xls->readDefColWidth(); break; case self::XLS_TYPE_COLINFO: $xls->readColInfo(); break; case self::XLS_TYPE_DIMENSION: $xls->readDefault(); break; case self::XLS_TYPE_ROW: $xls->readRow(); break; case self::XLS_TYPE_DBCELL: $xls->readDefault(); break; case self::XLS_TYPE_RK: $xls->readRk(); break; case self::XLS_TYPE_LABELSST: $xls->readLabelSst(); break; case self::XLS_TYPE_MULRK: $xls->readMulRk(); break; case self::XLS_TYPE_NUMBER: $xls->readNumber(); break; case self::XLS_TYPE_FORMULA: $xls->readFormula(); break; case self::XLS_TYPE_SHAREDFMLA: $xls->readSharedFmla(); break; case self::XLS_TYPE_BOOLERR: $xls->readBoolErr(); break; case self::XLS_TYPE_MULBLANK: $xls->readMulBlank(); break; case self::XLS_TYPE_LABEL: $xls->readLabel(); break; case self::XLS_TYPE_BLANK: $xls->readBlank(); break; case self::XLS_TYPE_MSODRAWING: $xls->readMsoDrawing(); break; case self::XLS_TYPE_OBJ: $xls->readObj(); break; case self::XLS_TYPE_WINDOW2: $xls->readWindow2(); break; case self::XLS_TYPE_PAGELAYOUTVIEW: $xls->readPageLayoutView(); break; case self::XLS_TYPE_SCL: $xls->readScl(); break; case self::XLS_TYPE_PANE: $xls->readPane(); break; case self::XLS_TYPE_SELECTION: $selectedCells = $xls->readSelection(); break; case self::XLS_TYPE_MERGEDCELLS: $xls->readMergedCells(); break; case self::XLS_TYPE_HYPERLINK: $xls->readHyperLink(); break; case self::XLS_TYPE_DATAVALIDATIONS: $xls->readDataValidations(); break; case self::XLS_TYPE_DATAVALIDATION: $xls->readDataValidation(); break; case self::XLS_TYPE_CFHEADER: /** @var string[] */ $cellRangeAddresses = $xls->readCFHeader(); break; case self::XLS_TYPE_CFRULE: $xls->readCFRule($cellRangeAddresses ?? []); break; case self::XLS_TYPE_SHEETLAYOUT: $xls->readSheetLayout(); break; case self::XLS_TYPE_SHEETPROTECTION: $xls->readSheetProtection(); break; case self::XLS_TYPE_RANGEPROTECTION: $xls->readRangeProtection(); break; case self::XLS_TYPE_NOTE: $xls->readNote(); break; case self::XLS_TYPE_TXO: $xls->readTextObject(); break; case self::XLS_TYPE_CONTINUE: $xls->readContinue(); break; case self::XLS_TYPE_EOF: $xls->readDefault(); break 2; default: $xls->readDefault(); break; } } // treat MSODRAWING records, sheet-level Escher if (!$xls->readDataOnly && $xls->drawingData) { $escherWorksheet = new SharedEscher(); $reader = new Escher($escherWorksheet); $escherWorksheet = $reader->load($xls->drawingData); // get all spContainers in one long array, so they can be mapped to OBJ records /** @var SpContainer[] $allSpContainers */ $allSpContainers = $escherWorksheet->getDgContainerOrThrow()->getSpgrContainerOrThrow()->getAllSpContainers(); } // treat OBJ records foreach ($xls->objs as $n => $obj) { // the first shape container never has a corresponding OBJ record, hence $n + 1 if (isset($allSpContainers[$n + 1])) { $spContainer = $allSpContainers[$n + 1]; // we skip all spContainers that are a part of a group shape since we cannot yet handle those if ($spContainer->getNestingLevel() > 1) { continue; } // calculate the width and height of the shape /** @var int $startRow */ [$startColumn, $startRow] = Coordinate::coordinateFromString($spContainer->getStartCoordinates()); /** @var int $endRow */ [$endColumn, $endRow] = Coordinate::coordinateFromString($spContainer->getEndCoordinates()); $startOffsetX = $spContainer->getStartOffsetX(); $startOffsetY = $spContainer->getStartOffsetY(); $endOffsetX = $spContainer->getEndOffsetX(); $endOffsetY = $spContainer->getEndOffsetY(); $width = SharedXls::getDistanceX($xls->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); $height = SharedXls::getDistanceY($xls->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); // calculate offsetX and offsetY of the shape $offsetX = (int) ($startOffsetX * SharedXls::sizeCol($xls->phpSheet, $startColumn) / 1024); $offsetY = (int) ($startOffsetY * SharedXls::sizeRow($xls->phpSheet, $startRow) / 256); /** @var int[] $obj */ switch ($obj['otObjType']) { case 0x19: // Note if (isset($xls->cellNotes[$obj['idObjID']])) { //$cellNote = $xls->cellNotes[$obj['idObjID']]; if (isset($xls->textObjects[$obj['idObjID']])) { $textObject = $xls->textObjects[$obj['idObjID']]; $xls->cellNotes[$obj['idObjID']]['objTextData'] = $textObject; //* @phpstan-ignore-line } } break; case 0x08: // picture // get index to BSE entry (1-based) /** @var int */ $BSEindex = $spContainer->getOPT(0x0104); // If there is no BSE Index, we will fail here and other fields are not read. // Fix by checking here. // TODO: Why is there no BSE Index? Is this a new Office Version? Password protected field? // More likely: an incompatible picture if (!$BSEindex) { continue 2; } if ($escherWorkbook) { /** @var BSE[] */ $BSECollection = $escherWorkbook->getDggContainerOrThrow()->getBstoreContainerOrThrow()->getBSECollection(); $BSE = $BSECollection[$BSEindex - 1]; $blipType = $BSE->getBlipType(); // need check because some blip types are not supported by Escher reader such as EMF if ($blip = $BSE->getBlip()) { $ih = imagecreatefromstring($blip->getData()); if ($ih !== false) { $drawing = new MemoryDrawing(); $drawing->setImageResource($ih); // width, height, offsetX, offsetY $drawing->setResizeProportional(false); $drawing->setWidth($width); $drawing->setHeight($height); $drawing->setOffsetX($offsetX); $drawing->setOffsetY($offsetY); switch ($blipType) { case BSE::BLIPTYPE_JPEG: $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG); break; case BSE::BLIPTYPE_PNG: imagealphablending($ih, false); imagesavealpha($ih, true); $drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG); break; } $drawing->setWorksheet($xls->phpSheet); $drawing->setCoordinates($spContainer->getStartCoordinates()); } } } break; default: // other object type break; } } } // treat SHAREDFMLA records if ($xls->version == self::XLS_BIFF8) { foreach ($xls->sharedFormulaParts as $cell => $baseCell) { /** @var int $row */ [$column, $row] = Coordinate::coordinateFromString($cell); /** @var string $baseCell */ if ($xls->getReadFilter()->readCell($column, $row, $xls->phpSheet->getTitle())) { /** @var string */ $temp = $xls->sharedFormulas[$baseCell]; $formula = $xls->getFormulaFromStructure($temp, $cell); $xls->phpSheet->getCell($cell)->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA); } } } if (!empty($xls->cellNotes)) { foreach ($xls->cellNotes as $note => $noteDetails) { /** @var array{author: string, cellRef: string, objTextData?: mixed[]} $noteDetails */ if (!isset($noteDetails['objTextData'])) { if (isset($xls->textObjects[$note])) { $textObject = $xls->textObjects[$note]; $noteDetails['objTextData'] = $textObject; } else { $noteDetails['objTextData']['text'] = ''; } } $cellAddress = str_replace('$', '', $noteDetails['cellRef']); /** @var string */ $tempDetails = $noteDetails['objTextData']['text']; $xls->phpSheet ->getComment($cellAddress) ->setAuthor($noteDetails['author']) ->setText( $xls->parseRichText($tempDetails) ); } } if ($selectedCells !== '') { $xls->phpSheet->setSelectedCells($selectedCells); } } if ($xls->createBlankSheetIfNoneRead && !$sheetCreated) { $xls->spreadsheet->createSheet(); } if ($xls->activeSheetSet === false) { $xls->spreadsheet->setActiveSheetIndex(0); } // add the named ranges (defined names) foreach ($xls->definedname as $definedName) { /** @var array{isBuiltInName: int, name: string, formula: string, scope: int} $definedName */ if ($definedName['isBuiltInName']) { switch ($definedName['name']) { case pack('C', 0x06): // print area // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2 $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? $extractedRanges = []; $sheetName = ''; /** @var non-empty-string $range */ foreach ($ranges as $range) { // $range should look like one of these // Foo!$C$7:$J$66 // Bar!$A$1:$IV$2 $explodes = Worksheet::extractSheetTitle($range, true, true); $sheetName = (string) $explodes[0]; if (!str_contains($explodes[1], ':')) { $explodes[1] = $explodes[1] . ':' . $explodes[1]; } $extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66 } if ($docSheet = $xls->spreadsheet->getSheetByName($sheetName)) { $docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2 } break; case pack('C', 0x07): // print titles (repeating rows) // Assuming BIFF8, there are 3 cases // 1. repeating rows // formula looks like this: Sheet!$A$1:$IV$2 // rows 1-2 repeat // 2. repeating columns // formula looks like this: Sheet!$A$1:$B$65536 // columns A-B repeat // 3. both repeating rows and repeating columns // formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2 $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? foreach ($ranges as $range) { // $range should look like this one of these // Sheet!$A$1:$B$65536 // Sheet!$A$1:$IV$2 if (str_contains($range, '!')) { $explodes = Worksheet::extractSheetTitle($range, true, true); $docSheet = $xls->spreadsheet->getSheetByName($explodes[0]); if ($docSheet) { $extractedRange = $explodes[1]; $extractedRange = str_replace('$', '', $extractedRange); $coordinateStrings = explode(':', $extractedRange); if (count($coordinateStrings) == 2) { [$firstColumn, $firstRow] = Coordinate::coordinateFromString($coordinateStrings[0]); [$lastColumn, $lastRow] = Coordinate::coordinateFromString($coordinateStrings[1]); $firstRow = (int) $firstRow; $lastRow = (int) $lastRow; if ($firstColumn == 'A' && $lastColumn == 'IV') { // then we have repeating rows $docSheet->getPageSetup()->setRowsToRepeatAtTop([$firstRow, $lastRow]); } elseif ($firstRow === 1 && $lastRow === AddressRange::MAX_ROW_XLS) { // then we have repeating columns $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$firstColumn, $lastColumn]); } } } } } break; } } else { // Extract range $formula = $definedName['formula']; if (str_contains($formula, '!')) { $explodes = Worksheet::extractSheetTitle($formula, true, true); $docSheet = $xls->spreadsheet->getSheetByName($explodes[0]); if ($docSheet) { $extractedRange = $explodes[1]; $localOnly = ($definedName['scope'] === 0) ? false : true; $scope = ($definedName['scope'] === 0) ? null : $xls->spreadsheet->getSheetByName($xls->sheets[$definedName['scope'] - 1]['name']); $xls->spreadsheet->addNamedRange(new NamedRange((string) $definedName['name'], $docSheet, $extractedRange, $localOnly, $scope)); } } // Named Value // TODO Provide support for named values } } $xls->data = ''; return $xls->spreadsheet; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/MD5.php ================================================ reset(); } /** * Reset the MD5 stream context. */ public function reset(): void { $this->a = 0x67452301; $this->b = self::signedInt(0xEFCDAB89); $this->c = self::signedInt(0x98BADCFE); $this->d = 0x10325476; } /** * Get MD5 stream context. */ public function getContext(): string { $s = ''; foreach (['a', 'b', 'c', 'd'] as $i) { $v = $this->{$i}; $s .= chr($v & 0xFF); $s .= chr(($v >> 8) & 0xFF); $s .= chr(($v >> 16) & 0xFF); $s .= chr(($v >> 24) & 0xFF); } return $s; } /** * Add data to context. * * @param string $data Data to add */ public function add(string $data): void { $unpacked = unpack('V16', $data) ?: throw new ReaderException('unable to unpack data'); /** @var int[] */ $words = array_values($unpacked); $A = $this->a; $B = $this->b; $C = $this->c; $D = $this->d; $F = [self::class, 'f']; $G = [self::class, 'g']; $H = [self::class, 'h']; $I = [self::class, 'i']; // ROUND 1 self::step($F, $A, $B, $C, $D, $words[0], 7, 0xD76AA478); self::step($F, $D, $A, $B, $C, $words[1], 12, 0xE8C7B756); self::step($F, $C, $D, $A, $B, $words[2], 17, 0x242070DB); self::step($F, $B, $C, $D, $A, $words[3], 22, 0xC1BDCEEE); self::step($F, $A, $B, $C, $D, $words[4], 7, 0xF57C0FAF); self::step($F, $D, $A, $B, $C, $words[5], 12, 0x4787C62A); self::step($F, $C, $D, $A, $B, $words[6], 17, 0xA8304613); self::step($F, $B, $C, $D, $A, $words[7], 22, 0xFD469501); self::step($F, $A, $B, $C, $D, $words[8], 7, 0x698098D8); self::step($F, $D, $A, $B, $C, $words[9], 12, 0x8B44F7AF); self::step($F, $C, $D, $A, $B, $words[10], 17, 0xFFFF5BB1); self::step($F, $B, $C, $D, $A, $words[11], 22, 0x895CD7BE); self::step($F, $A, $B, $C, $D, $words[12], 7, 0x6B901122); self::step($F, $D, $A, $B, $C, $words[13], 12, 0xFD987193); self::step($F, $C, $D, $A, $B, $words[14], 17, 0xA679438E); self::step($F, $B, $C, $D, $A, $words[15], 22, 0x49B40821); // ROUND 2 self::step($G, $A, $B, $C, $D, $words[1], 5, 0xF61E2562); self::step($G, $D, $A, $B, $C, $words[6], 9, 0xC040B340); self::step($G, $C, $D, $A, $B, $words[11], 14, 0x265E5A51); self::step($G, $B, $C, $D, $A, $words[0], 20, 0xE9B6C7AA); self::step($G, $A, $B, $C, $D, $words[5], 5, 0xD62F105D); self::step($G, $D, $A, $B, $C, $words[10], 9, 0x02441453); self::step($G, $C, $D, $A, $B, $words[15], 14, 0xD8A1E681); self::step($G, $B, $C, $D, $A, $words[4], 20, 0xE7D3FBC8); self::step($G, $A, $B, $C, $D, $words[9], 5, 0x21E1CDE6); self::step($G, $D, $A, $B, $C, $words[14], 9, 0xC33707D6); self::step($G, $C, $D, $A, $B, $words[3], 14, 0xF4D50D87); self::step($G, $B, $C, $D, $A, $words[8], 20, 0x455A14ED); self::step($G, $A, $B, $C, $D, $words[13], 5, 0xA9E3E905); self::step($G, $D, $A, $B, $C, $words[2], 9, 0xFCEFA3F8); self::step($G, $C, $D, $A, $B, $words[7], 14, 0x676F02D9); self::step($G, $B, $C, $D, $A, $words[12], 20, 0x8D2A4C8A); // ROUND 3 self::step($H, $A, $B, $C, $D, $words[5], 4, 0xFFFA3942); self::step($H, $D, $A, $B, $C, $words[8], 11, 0x8771F681); self::step($H, $C, $D, $A, $B, $words[11], 16, 0x6D9D6122); self::step($H, $B, $C, $D, $A, $words[14], 23, 0xFDE5380C); self::step($H, $A, $B, $C, $D, $words[1], 4, 0xA4BEEA44); self::step($H, $D, $A, $B, $C, $words[4], 11, 0x4BDECFA9); self::step($H, $C, $D, $A, $B, $words[7], 16, 0xF6BB4B60); self::step($H, $B, $C, $D, $A, $words[10], 23, 0xBEBFBC70); self::step($H, $A, $B, $C, $D, $words[13], 4, 0x289B7EC6); self::step($H, $D, $A, $B, $C, $words[0], 11, 0xEAA127FA); self::step($H, $C, $D, $A, $B, $words[3], 16, 0xD4EF3085); self::step($H, $B, $C, $D, $A, $words[6], 23, 0x04881D05); self::step($H, $A, $B, $C, $D, $words[9], 4, 0xD9D4D039); self::step($H, $D, $A, $B, $C, $words[12], 11, 0xE6DB99E5); self::step($H, $C, $D, $A, $B, $words[15], 16, 0x1FA27CF8); self::step($H, $B, $C, $D, $A, $words[2], 23, 0xC4AC5665); // ROUND 4 self::step($I, $A, $B, $C, $D, $words[0], 6, 0xF4292244); self::step($I, $D, $A, $B, $C, $words[7], 10, 0x432AFF97); self::step($I, $C, $D, $A, $B, $words[14], 15, 0xAB9423A7); self::step($I, $B, $C, $D, $A, $words[5], 21, 0xFC93A039); self::step($I, $A, $B, $C, $D, $words[12], 6, 0x655B59C3); self::step($I, $D, $A, $B, $C, $words[3], 10, 0x8F0CCC92); self::step($I, $C, $D, $A, $B, $words[10], 15, 0xFFEFF47D); self::step($I, $B, $C, $D, $A, $words[1], 21, 0x85845DD1); self::step($I, $A, $B, $C, $D, $words[8], 6, 0x6FA87E4F); self::step($I, $D, $A, $B, $C, $words[15], 10, 0xFE2CE6E0); self::step($I, $C, $D, $A, $B, $words[6], 15, 0xA3014314); self::step($I, $B, $C, $D, $A, $words[13], 21, 0x4E0811A1); self::step($I, $A, $B, $C, $D, $words[4], 6, 0xF7537E82); self::step($I, $D, $A, $B, $C, $words[11], 10, 0xBD3AF235); self::step($I, $C, $D, $A, $B, $words[2], 15, 0x2AD7D2BB); self::step($I, $B, $C, $D, $A, $words[9], 21, 0xEB86D391); $this->a = ($this->a + $A) & self::$allOneBits; $this->b = ($this->b + $B) & self::$allOneBits; $this->c = ($this->c + $C) & self::$allOneBits; $this->d = ($this->d + $D) & self::$allOneBits; } private static function f(int $X, int $Y, int $Z): int { return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z } private static function g(int $X, int $Y, int $Z): int { return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z } private static function h(int $X, int $Y, int $Z): int { return $X ^ $Y ^ $Z; // X XOR Y XOR Z } private static function i(int $X, int $Y, int $Z): int { return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z) } /** @param float|int $t may be float on 32-bit system */ private static function step(callable $func, int &$A, int $B, int $C, int $D, int $M, int $s, $t): void { $t = self::signedInt($t); /** @var int */ $temp = call_user_func($func, $B, $C, $D); $A = (int) ($A + $temp + $M + $t) & self::$allOneBits; $A = self::rotate($A, $s); $A = (int) ($B + $A) & self::$allOneBits; } /** @param float|int $result may be float on 32-bit system */ private static function signedInt($result): int { return is_int($result) ? $result : (int) (PHP_INT_MIN + $result - 1 - PHP_INT_MAX); } private static function rotate(int $decimal, int $bits): int { $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT); return self::signedInt(bindec(substr($binary, $bits) . substr($binary, 0, $bits))); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Mappings.php ================================================ ['ISNA', 1], 3 => ['ISERROR', 1], 10 => ['NA', 0], 15 => ['SIN', 1], 16 => ['COS', 1], 17 => ['TAN', 1], 18 => ['ATAN', 1], 19 => ['PI', 0], 20 => ['SQRT', 1], 21 => ['EXP', 1], 22 => ['LN', 1], 23 => ['LOG10', 1], 24 => ['ABS', 1], 25 => ['INT', 1], 26 => ['SIGN', 1], 27 => ['ROUND', 2], 30 => ['REPT', 2], 31 => ['MID', 3], 32 => ['LEN', 1], 33 => ['VALUE', 1], 34 => ['TRUE', 0], 35 => ['FALSE', 0], 38 => ['NOT', 1], 39 => ['MOD', 2], 40 => ['DCOUNT', 3], 41 => ['DSUM', 3], 42 => ['DAVERAGE', 3], 43 => ['DMIN', 3], 44 => ['DMAX', 3], 45 => ['DSTDEV', 3], 48 => ['TEXT', 2], 61 => ['MIRR', 3], 63 => ['RAND', 0], 65 => ['DATE', 3], 66 => ['TIME', 3], 67 => ['DAY', 1], 68 => ['MONTH', 1], 69 => ['YEAR', 1], 71 => ['HOUR', 1], 72 => ['MINUTE', 1], 73 => ['SECOND', 1], 74 => ['NOW', 0], 75 => ['AREAS', 1], 76 => ['ROWS', 1], 77 => ['COLUMNS', 1], 83 => ['TRANSPOSE', 1], 86 => ['TYPE', 1], 97 => ['ATAN2', 2], 98 => ['ASIN', 1], 99 => ['ACOS', 1], 105 => ['ISREF', 1], 111 => ['CHAR', 1], 112 => ['LOWER', 1], 113 => ['UPPER', 1], 114 => ['PROPER', 1], 117 => ['EXACT', 2], 118 => ['TRIM', 1], 119 => ['REPLACE', 4], 121 => ['CODE', 1], 126 => ['ISERR', 1], 127 => ['ISTEXT', 1], 128 => ['ISNUMBER', 1], 129 => ['ISBLANK', 1], 130 => ['T', 1], 131 => ['N', 1], 140 => ['DATEVALUE', 1], 141 => ['TIMEVALUE', 1], 142 => ['SLN', 3], 143 => ['SYD', 4], 162 => ['CLEAN', 1], 163 => ['MDETERM', 1], 164 => ['MINVERSE', 1], 165 => ['MMULT', 2], 184 => ['FACT', 1], 189 => ['DPRODUCT', 3], 190 => ['ISNONTEXT', 1], 195 => ['DSTDEVP', 3], 196 => ['DVARP', 3], 198 => ['ISLOGICAL', 1], 199 => ['DCOUNTA', 3], 207 => ['REPLACEB', 4], 210 => ['MIDB', 3], 211 => ['LENB', 1], 212 => ['ROUNDUP', 2], 213 => ['ROUNDDOWN', 2], 214 => ['ASC', 1], 215 => ['DBCS', 1], 221 => ['TODAY', 0], 229 => ['SINH', 1], 230 => ['COSH', 1], 231 => ['TANH', 1], 232 => ['ASINH', 1], 233 => ['ACOSH', 1], 234 => ['ATANH', 1], 235 => ['DGET', 3], 244 => ['INFO', 1], 252 => ['FREQUENCY', 2], 261 => ['ERROR.TYPE', 1], 271 => ['GAMMALN', 1], 273 => ['BINOMDIST', 4], 274 => ['CHIDIST', 2], 275 => ['CHIINV', 2], 276 => ['COMBIN', 2], 277 => ['CONFIDENCE', 3], 278 => ['CRITBINOM', 3], 279 => ['EVEN', 1], 280 => ['EXPONDIST', 3], 281 => ['FDIST', 3], 282 => ['FINV', 3], 283 => ['FISHER', 1], 284 => ['FISHERINV', 1], 285 => ['FLOOR', 2], 286 => ['GAMMADIST', 4], 287 => ['GAMMAINV', 3], 288 => ['CEILING', 2], 289 => ['HYPGEOMDIST', 4], 290 => ['LOGNORMDIST', 3], 291 => ['LOGINV', 3], 292 => ['NEGBINOMDIST', 3], 293 => ['NORMDIST', 4], 294 => ['NORMSDIST', 1], 295 => ['NORMINV', 3], 296 => ['NORMSINV', 1], 297 => ['STANDARDIZE', 3], 298 => ['ODD', 1], 299 => ['PERMUT', 2], 300 => ['POISSON', 3], 301 => ['TDIST', 3], 302 => ['WEIBULL', 4], 303 => ['SUMXMY2', 2], 304 => ['SUMX2MY2', 2], 305 => ['SUMX2PY2', 2], 306 => ['CHITEST', 2], 307 => ['CORREL', 2], 308 => ['COVAR', 2], 309 => ['FORECAST', 3], 310 => ['FTEST', 2], 311 => ['INTERCEPT', 2], 312 => ['PEARSON', 2], 313 => ['RSQ', 2], 314 => ['STEYX', 2], 315 => ['SLOPE', 2], 316 => ['TTEST', 4], 325 => ['LARGE', 2], 326 => ['SMALL', 2], 327 => ['QUARTILE', 2], 328 => ['PERCENTILE', 2], 331 => ['TRIMMEAN', 2], 332 => ['TINV', 2], 337 => ['POWER', 2], 342 => ['RADIANS', 1], 343 => ['DEGREES', 1], 346 => ['COUNTIF', 2], 347 => ['COUNTBLANK', 1], 350 => ['ISPMT', 4], 351 => ['DATEDIF', 3], 352 => ['DATESTRING', 1], 353 => ['NUMBERSTRING', 2], 360 => ['PHONETIC', 1], 368 => ['BAHTTEXT', 1], ]; /** * Map tFuncV values (functions with variable number of arguments). * Key is tFuncV value. * Value is Excel function name. */ const TFUNCV_MAPPINGS = [ 0 => 'COUNT', 1 => 'IF', 4 => 'SUM', 5 => 'AVERAGE', 6 => 'MIN', 7 => 'MAX', 8 => 'ROW', 9 => 'COLUMN', 11 => 'NPV', 12 => 'STDEV', 13 => 'DOLLAR', 14 => 'FIXED', 28 => 'LOOKUP', 29 => 'INDEX', 36 => 'AND', 37 => 'OR', 46 => 'VAR', 49 => 'LINEST', 50 => 'TREND', 51 => 'LOGEST', 52 => 'GROWTH', 56 => 'PV', 57 => 'FV', 58 => 'NPER', 59 => 'PMT', 60 => 'RATE', 62 => 'IRR', 64 => 'MATCH', 70 => 'WEEKDAY', 78 => 'OFFSET', 82 => 'SEARCH', 100 => 'CHOOSE', 101 => 'HLOOKUP', 102 => 'VLOOKUP', 109 => 'LOG', 115 => 'LEFT', 116 => 'RIGHT', 120 => 'SUBSTITUTE', 124 => 'FIND', 125 => 'CELL', 144 => 'DDB', 148 => 'INDIRECT', 167 => 'IPMT', 168 => 'PPMT', 169 => 'COUNTA', 183 => 'PRODUCT', 193 => 'STDEVP', 194 => 'VARP', 197 => 'TRUNC', 204 => 'USDOLLAR', 205 => 'FINDB', 206 => 'SEARCHB', 208 => 'LEFTB', 209 => 'RIGHTB', 216 => 'RANK', 219 => 'ADDRESS', 220 => 'DAYS360', 222 => 'VDB', 227 => 'MEDIAN', 228 => 'SUMPRODUCT', 247 => 'DB', 255 => '', 269 => 'AVEDEV', 270 => 'BETADIST', 272 => 'BETAINV', 317 => 'PROB', 318 => 'DEVSQ', 319 => 'GEOMEAN', 320 => 'HARMEAN', 321 => 'SUMSQ', 322 => 'KURT', 323 => 'SKEW', 324 => 'ZTEST', 329 => 'PERCENTRANK', 330 => 'MODE', 336 => 'CONCATENATE', 344 => 'SUBTOTAL', 345 => 'SUMIF', 354 => 'ROMAN', 358 => 'GETPIVOTDATA', 359 => 'HYPERLINK', 361 => 'AVERAGEA', 362 => 'MAXA', 363 => 'MINA', 364 => 'STDEVPA', 365 => 'VARPA', 366 => 'STDEVA', 367 => 'VARA', ]; } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/RC4.php ================================================ i = 0; $this->i < 256; ++$this->i) { $this->s[$this->i] = $this->i; } $this->j = 0; for ($this->i = 0; $this->i < 256; ++$this->i) { $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256; $t = $this->s[$this->i]; $this->s[$this->i] = $this->s[$this->j]; $this->s[$this->j] = $t; } $this->i = $this->j = 0; } /** * Symmetric decryption/encryption function. * * @param string $data Data to encrypt/decrypt */ public function RC4(string $data): string { $len = strlen($data); for ($c = 0; $c < $len; ++$c) { $this->i = ($this->i + 1) % 256; $this->j = ($this->j + $this->s[$this->i]) % 256; $t = $this->s[$this->i]; $this->s[$this->i] = $this->s[$this->j]; $this->s[$this->j] = $t; $t = ($this->s[$this->i] + $this->s[$this->j]) % 256; $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]); } return $data; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Style/Border.php ================================================ */ protected static array $borderStyleMap = [ 0x00 => StyleBorder::BORDER_NONE, 0x01 => StyleBorder::BORDER_THIN, 0x02 => StyleBorder::BORDER_MEDIUM, 0x03 => StyleBorder::BORDER_DASHED, 0x04 => StyleBorder::BORDER_DOTTED, 0x05 => StyleBorder::BORDER_THICK, 0x06 => StyleBorder::BORDER_DOUBLE, 0x07 => StyleBorder::BORDER_HAIR, 0x08 => StyleBorder::BORDER_MEDIUMDASHED, 0x09 => StyleBorder::BORDER_DASHDOT, 0x0A => StyleBorder::BORDER_MEDIUMDASHDOT, 0x0B => StyleBorder::BORDER_DASHDOTDOT, 0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT, 0x0D => StyleBorder::BORDER_SLANTDASHDOT, ]; public static function lookup(int $index): string { return self::$borderStyleMap[$index] ?? StyleBorder::BORDER_NONE; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php ================================================ */ protected static array $horizontalAlignmentMap = [ 0 => Alignment::HORIZONTAL_GENERAL, 1 => Alignment::HORIZONTAL_LEFT, 2 => Alignment::HORIZONTAL_CENTER, 3 => Alignment::HORIZONTAL_RIGHT, 4 => Alignment::HORIZONTAL_FILL, 5 => Alignment::HORIZONTAL_JUSTIFY, 6 => Alignment::HORIZONTAL_CENTER_CONTINUOUS, ]; /** * @var array */ protected static array $verticalAlignmentMap = [ 0 => Alignment::VERTICAL_TOP, 1 => Alignment::VERTICAL_CENTER, 2 => Alignment::VERTICAL_BOTTOM, 3 => Alignment::VERTICAL_JUSTIFY, ]; public static function horizontal(Alignment $alignment, int $horizontal): void { if (array_key_exists($horizontal, self::$horizontalAlignmentMap)) { $alignment->setHorizontal(self::$horizontalAlignmentMap[$horizontal]); } } public static function vertical(Alignment $alignment, int $vertical): void { if (array_key_exists($vertical, self::$verticalAlignmentMap)) { $alignment->setVertical(self::$verticalAlignmentMap[$vertical]); } } public static function wrap(Alignment $alignment, int $wrap): void { $alignment->setWrapText((bool) $wrap); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php ================================================ setSuperscript(true); break; case 0x0002: $font->setSubscript(true); break; } } /** * @var array */ protected static array $underlineMap = [ 0x01 => Font::UNDERLINE_SINGLE, 0x02 => Font::UNDERLINE_DOUBLE, 0x21 => Font::UNDERLINE_SINGLEACCOUNTING, 0x22 => Font::UNDERLINE_DOUBLEACCOUNTING, ]; public static function underline(Font $font, int $underline): void { if (array_key_exists($underline, self::$underlineMap)) { $font->setUnderline(self::$underlineMap[$underline]); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php ================================================ */ protected static array $fillPatternMap = [ 0x00 => Fill::FILL_NONE, 0x01 => Fill::FILL_SOLID, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, 0x03 => Fill::FILL_PATTERN_DARKGRAY, 0x04 => Fill::FILL_PATTERN_LIGHTGRAY, 0x05 => Fill::FILL_PATTERN_DARKHORIZONTAL, 0x06 => Fill::FILL_PATTERN_DARKVERTICAL, 0x07 => Fill::FILL_PATTERN_DARKDOWN, 0x08 => Fill::FILL_PATTERN_DARKUP, 0x09 => Fill::FILL_PATTERN_DARKGRID, 0x0A => Fill::FILL_PATTERN_DARKTRELLIS, 0x0B => Fill::FILL_PATTERN_LIGHTHORIZONTAL, 0x0C => Fill::FILL_PATTERN_LIGHTVERTICAL, 0x0D => Fill::FILL_PATTERN_LIGHTDOWN, 0x0E => Fill::FILL_PATTERN_LIGHTUP, 0x0F => Fill::FILL_PATTERN_LIGHTGRID, 0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS, 0x11 => Fill::FILL_PATTERN_GRAY125, 0x12 => Fill::FILL_PATTERN_GRAY0625, ]; /** * Get fill pattern from index * OpenOffice documentation: 2.5.12. */ public static function lookup(int $index): string { return self::$fillPatternMap[$index] ?? Fill::FILL_NONE; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xls.php ================================================ data. */ protected int $dataSize; /** * Current position in stream. */ protected int $pos; /** * Workbook to be returned by the reader. */ protected Spreadsheet $spreadsheet; /** * Worksheet that is currently being built by the reader. */ protected Worksheet $phpSheet; /** * BIFF version. */ protected int $version = 0; /** * Shared formats. * * @var mixed[] */ protected array $formats; /** * Shared fonts. * * @var Font[] */ protected array $objFonts; /** * Color palette. * * @var string[][] */ protected array $palette; /** * Worksheets. * * @var array */ protected array $sheets; /** * External books. * * @var mixed[][] */ protected array $externalBooks; /** * REF structures. Only applies to BIFF8. * * @var array */ protected array $ref; /** * External names. * * @var array|string> */ protected array $externalNames; /** * Defined names. * * @var array{isBuiltInName: int, name: string, formula: string, scope: int} */ protected array $definedname; /** * Shared strings. Only applies to BIFF8. * * @var array */ protected array $sst; /** * Panes are frozen? (in sheet currently being read). See WINDOW2 record. */ protected bool $frozen; /** * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record. */ protected bool $isFitToPages; /** * Objects. One OBJ record contributes with one entry. * * @var mixed[] */ protected array $objs; /** * Text Objects. One TXO record corresponds with one entry. * * @var array */ protected array $textObjects; /** * Cell Annotations (BIFF8). * * @var mixed[] */ protected array $cellNotes; /** * The combined MSODRAWINGGROUP data. */ protected string $drawingGroupData; /** * The combined MSODRAWING data (per sheet). */ protected string $drawingData; /** * Keep track of XF index. */ protected int $xfIndex; /** * Mapping of XF index (that is a cell XF) to final index in cellXf collection. * * @var int[] */ protected array $mapCellXfIndex; /** * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection. * * @var int[] */ protected array $mapCellStyleXfIndex; /** * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value. * * @var mixed[] */ protected array $sharedFormulas; /** * The shared formula parts in a sheet. One FORMULA record contributes with one value if it * refers to a shared formula. * * @var mixed[] */ protected array $sharedFormulaParts; /** * The type of encryption in use. */ protected int $encryption = 0; /** * The position in the stream after which contents are encrypted. */ protected int $encryptionStartPos = 0; protected string $encryptionPassword = 'VelvetSweatshop'; /** * The current RC4 decryption object. */ protected ?Xls\RC4 $rc4Key = null; /** * The position in the stream that the RC4 decryption object was left at. */ protected int $rc4Pos = 0; /** * The current MD5 context state. * It is set via call-by-reference to verifyPassword. */ private string $md5Ctxt = ''; protected int $textObjRef; protected string $baseCell; protected bool $activeSheetSet = false; /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. * * @return string[] */ public function listWorksheetNames(string $filename): array { return (new Xls\ListFunctions())->listWorksheetNames2($filename, $this); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { return (new Xls\ListFunctions())->listWorksheetInfo2($filename, $this); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetDimensions(string $filename): array { return (new Xls\ListFunctions())->listWorksheetDimensions2($filename, $this); } /** * Loads PhpSpreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { return (new Xls\LoadSpreadsheet())->loadSpreadsheetFromFile2($filename, $this); } /** * Read record data from stream, decrypting as required. * * @param string $data Data stream to read from * @param int $pos Position to start reading from * @param int $len Record data length * * @return string Record data */ protected function readRecordData(string $data, int $pos, int $len): string { $data = substr($data, $pos, $len); // File not encrypted, or record before encryption start point if ($this->encryption == self::MS_BIFF_CRYPTO_NONE || $pos < $this->encryptionStartPos) { return $data; } $recordData = ''; if ($this->encryption == self::MS_BIFF_CRYPTO_RC4) { $oldBlock = floor($this->rc4Pos / self::REKEY_BLOCK); $block = (int) floor($pos / self::REKEY_BLOCK); $endBlock = (int) floor(($pos + $len) / self::REKEY_BLOCK); // Spin an RC4 decryptor to the right spot. If we have a decryptor sitting // at a point earlier in the current block, re-use it as we can save some time. if ($block != $oldBlock || $pos < $this->rc4Pos || !$this->rc4Key) { $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); $step = $pos % self::REKEY_BLOCK; } else { $step = $pos - $this->rc4Pos; } $this->rc4Key->RC4(str_repeat("\0", $step)); // Decrypt record data (re-keying at the end of every block) while ($block != $endBlock) { $step = self::REKEY_BLOCK - ($pos % self::REKEY_BLOCK); $recordData .= $this->rc4Key->RC4(substr($data, 0, $step)); $data = substr($data, $step); $pos += $step; $len -= $step; ++$block; $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); } $recordData .= $this->rc4Key->RC4(substr($data, 0, $len)); // Keep track of the position of this decryptor. // We'll try and re-use it later if we can to speed things up $this->rc4Pos = $pos + $len; } elseif ($this->encryption == self::MS_BIFF_CRYPTO_XOR) { throw new Exception('XOr encryption not supported'); } return $recordData; } /** * Use OLE reader to extract the relevant data streams from the OLE file. */ protected function loadOLE(string $filename): void { // OLE reader $ole = new OLERead(); // get excel data, $ole->read($filename); // Get workbook data: workbook stream + sheet streams $this->data = $ole->getStream($ole->wrkbook); // @phpstan-ignore-line // Get summary information data $this->summaryInformation = $ole->getStream($ole->summaryInformation); // Get additional document summary information data $this->documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation); } /** * Read summary information. */ protected function readSummaryInformation(): void { if (!isset($this->summaryInformation)) { return; } // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) // offset: 2; size: 2; // offset: 4; size: 2; OS version // offset: 6; size: 2; OS indicator // offset: 8; size: 16 // offset: 24; size: 4; section count //$secCount = self::getInt4d($this->summaryInformation, 24); // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 // offset: 44; size: 4 $secOffset = self::getInt4d($this->summaryInformation, 44); // section header // offset: $secOffset; size: 4; section length //$secLength = self::getInt4d($this->summaryInformation, $secOffset); // offset: $secOffset+4; size: 4; property count $countProperties = self::getInt4d($this->summaryInformation, $secOffset + 4); // initialize code page (used to resolve string values) $codePage = 'CP1252'; // offset: ($secOffset+8); size: var // loop through property decarations and properties for ($i = 0; $i < $countProperties; ++$i) { // offset: ($secOffset+8) + (8 * $i); size: 4; property ID $id = self::getInt4d($this->summaryInformation, ($secOffset + 8) + (8 * $i)); // Use value of property id as appropriate // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48) $offset = self::getInt4d($this->summaryInformation, ($secOffset + 12) + (8 * $i)); $type = self::getInt4d($this->summaryInformation, $secOffset + $offset); // initialize property value $value = null; // extract property value based on property type switch ($type) { case 0x02: // 2 byte signed integer $value = self::getUInt2d($this->summaryInformation, $secOffset + 4 + $offset); break; case 0x03: // 4 byte signed integer $value = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset); break; case 0x13: // 4 byte unsigned integer // not needed yet, fix later if necessary break; case 0x1E: // null-terminated string prepended by dword string length $byteLength = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset); $value = substr($this->summaryInformation, $secOffset + 8 + $offset, $byteLength); $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage); $value = rtrim($value); break; case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) // PHP-time $value = OLE::OLE2LocalDate(substr($this->summaryInformation, $secOffset + 4 + $offset, 8)); break; case 0x47: // Clipboard format // not needed yet, fix later if necessary break; } switch ($id) { case 0x01: // Code Page $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Title $this->spreadsheet->getProperties()->setTitle("$value"); break; case 0x03: // Subject $this->spreadsheet->getProperties()->setSubject("$value"); break; case 0x04: // Author (Creator) $this->spreadsheet->getProperties()->setCreator("$value"); break; case 0x05: // Keywords $this->spreadsheet->getProperties()->setKeywords("$value"); break; case 0x06: // Comments (Description) $this->spreadsheet->getProperties()->setDescription("$value"); break; case 0x07: // Template // Not supported by PhpSpreadsheet break; case 0x08: // Last Saved By (LastModifiedBy) $this->spreadsheet->getProperties()->setLastModifiedBy("$value"); break; case 0x09: // Revision // Not supported by PhpSpreadsheet break; case 0x0A: // Total Editing Time // Not supported by PhpSpreadsheet break; case 0x0B: // Last Printed // Not supported by PhpSpreadsheet break; case 0x0C: // Created Date/Time $this->spreadsheet->getProperties()->setCreated($value); break; case 0x0D: // Modified Date/Time $this->spreadsheet->getProperties()->setModified($value); break; case 0x0E: // Number of Pages // Not supported by PhpSpreadsheet break; case 0x0F: // Number of Words // Not supported by PhpSpreadsheet break; case 0x10: // Number of Characters // Not supported by PhpSpreadsheet break; case 0x11: // Thumbnail // Not supported by PhpSpreadsheet break; case 0x12: // Name of creating application // Not supported by PhpSpreadsheet break; case 0x13: // Security // Not supported by PhpSpreadsheet break; } } } /** * Read additional document summary information. */ protected function readDocumentSummaryInformation(): void { if (!isset($this->documentSummaryInformation)) { return; } // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) // offset: 2; size: 2; // offset: 4; size: 2; OS version // offset: 6; size: 2; OS indicator // offset: 8; size: 16 // offset: 24; size: 4; section count //$secCount = self::getInt4d($this->documentSummaryInformation, 24); // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae // offset: 44; size: 4; first section offset $secOffset = self::getInt4d($this->documentSummaryInformation, 44); // section header // offset: $secOffset; size: 4; section length //$secLength = self::getInt4d($this->documentSummaryInformation, $secOffset); // offset: $secOffset+4; size: 4; property count $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset + 4); // initialize code page (used to resolve string values) $codePage = 'CP1252'; // offset: ($secOffset+8); size: var // loop through property decarations and properties for ($i = 0; $i < $countProperties; ++$i) { // offset: ($secOffset+8) + (8 * $i); size: 4; property ID $id = self::getInt4d($this->documentSummaryInformation, ($secOffset + 8) + (8 * $i)); // Use value of property id as appropriate // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48) $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset + 12) + (8 * $i)); $type = self::getInt4d($this->documentSummaryInformation, $secOffset + $offset); // initialize property value $value = null; // extract property value based on property type switch ($type) { case 0x02: // 2 byte signed integer $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset); break; case 0x03: // 4 byte signed integer $value = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset); break; case 0x0B: // Boolean $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset); $value = ($value == 0 ? false : true); break; case 0x13: // 4 byte unsigned integer // not needed yet, fix later if necessary break; case 0x1E: // null-terminated string prepended by dword string length $byteLength = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset); $value = substr($this->documentSummaryInformation, $secOffset + 8 + $offset, $byteLength); $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage); $value = rtrim($value); break; case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) // PHP-Time $value = OLE::OLE2LocalDate(substr($this->documentSummaryInformation, $secOffset + 4 + $offset, 8)); break; case 0x47: // Clipboard format // not needed yet, fix later if necessary break; } switch ($id) { case 0x01: // Code Page $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Category $this->spreadsheet->getProperties()->setCategory("$value"); break; case 0x03: // Presentation Target // Not supported by PhpSpreadsheet break; case 0x04: // Bytes // Not supported by PhpSpreadsheet break; case 0x05: // Lines // Not supported by PhpSpreadsheet break; case 0x06: // Paragraphs // Not supported by PhpSpreadsheet break; case 0x07: // Slides // Not supported by PhpSpreadsheet break; case 0x08: // Notes // Not supported by PhpSpreadsheet break; case 0x09: // Hidden Slides // Not supported by PhpSpreadsheet break; case 0x0A: // MM Clips // Not supported by PhpSpreadsheet break; case 0x0B: // Scale Crop // Not supported by PhpSpreadsheet break; case 0x0C: // Heading Pairs // Not supported by PhpSpreadsheet break; case 0x0D: // Titles of Parts // Not supported by PhpSpreadsheet break; case 0x0E: // Manager $this->spreadsheet->getProperties()->setManager("$value"); break; case 0x0F: // Company $this->spreadsheet->getProperties()->setCompany("$value"); break; case 0x10: // Links up-to-date // Not supported by PhpSpreadsheet break; } } } /** * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record. */ protected function readDefault(): void { $length = self::getUInt2d($this->data, $this->pos + 2); // move stream pointer to next record $this->pos += 4 + $length; } /** * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions, * this record stores a note (cell note). This feature was significantly enhanced in Excel 97. */ protected function readNote(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } $cellAddress = Xls\Biff8::readBIFF8CellAddress(substr($recordData, 0, 4)); if ($this->version == self::XLS_BIFF8) { $noteObjID = self::getUInt2d($recordData, 6); $noteAuthor = self::readUnicodeStringLong(substr($recordData, 8)); $noteAuthor = $noteAuthor['value']; $this->cellNotes[$noteObjID] = [ 'cellRef' => $cellAddress, 'objectID' => $noteObjID, 'author' => $noteAuthor, ]; } else { $extension = false; if ($cellAddress === '$B$' . AddressRange::MAX_ROW_XLS) { // If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation // note from the previous cell annotation. We're not yet handling this, so annotations longer than the // max 2048 bytes will probably throw a wobbly. //$row = self::getUInt2d($recordData, 0); $extension = true; $arrayKeys = array_keys($this->phpSheet->getComments()); $cellAddress = array_pop($arrayKeys); } $cellAddress = str_replace('$', '', (string) $cellAddress); //$noteLength = self::getUInt2d($recordData, 4); $noteText = trim(substr($recordData, 6)); if ($extension) { // Concatenate this extension with the currently set comment for the cell $comment = $this->phpSheet->getComment($cellAddress); $commentText = $comment->getText()->getPlainText(); $comment->setText($this->parseRichText($commentText . $noteText)); } else { // Set comment for the cell $this->phpSheet->getComment($cellAddress)->setText($this->parseRichText($noteText)); // ->setAuthor($author) } } } /** * The TEXT Object record contains the text associated with a cell annotation. */ protected function readTextObject(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // recordData consists of an array of subrecords looking like this: // grbit: 2 bytes; Option Flags // rot: 2 bytes; rotation // cchText: 2 bytes; length of the text (in the first continue record) // cbRuns: 2 bytes; length of the formatting (in the second continue record) // followed by the continuation records containing the actual text and formatting $grbitOpts = self::getUInt2d($recordData, 0); $rot = self::getUInt2d($recordData, 2); //$cchText = self::getUInt2d($recordData, 10); $cbRuns = self::getUInt2d($recordData, 12); $text = $this->getSplicedRecordData(); /** @var int[] */ $tempSplice = $text['spliceOffsets']; /** @var int */ $temp = $tempSplice[0]; /** @var int */ $temp1 = $tempSplice[1]; $textByte = $temp1 - $temp - 1; /** @var string */ $textRecordData = $text['recordData']; $textStr = substr($textRecordData, $temp + 1, $textByte); // get 1 byte $is16Bit = ord($textRecordData[0]); // it is possible to use a compressed format, // which omits the high bytes of all characters, if they are all zero if (($is16Bit & 0x01) === 0) { $textStr = StringHelper::ConvertEncoding($textStr, 'UTF-8', 'ISO-8859-1'); } else { $textStr = $this->decodeCodepage($textStr); } $this->textObjects[$this->textObjRef] = [ 'text' => $textStr, 'format' => substr($textRecordData, $tempSplice[1], $cbRuns), 'alignment' => $grbitOpts, 'rotation' => $rot, ]; } /** * Read BOF. */ protected function readBof(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = substr($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 2; size: 2; type of the following data $substreamType = self::getUInt2d($recordData, 2); switch ($substreamType) { case self::XLS_WORKBOOKGLOBALS: $version = self::getUInt2d($recordData, 0); if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) { throw new Exception('Cannot read this Excel file. Version is too old.'); } $this->version = $version; break; case self::XLS_WORKSHEET: // do not use this version information for anything // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream break; default: // substream, e.g. chart // just skip the entire substream do { $code = self::getUInt2d($this->data, $this->pos); $this->readDefault(); } while ($code != self::XLS_TYPE_EOF && $this->pos < $this->dataSize); break; } } public function setEncryptionPassword(string $encryptionPassword): self { $this->encryptionPassword = $encryptionPassword; return $this; } /** * FILEPASS. * * This record is part of the File Protection Block. It * contains information about the read/write password of the * file. All record contents following this record will be * encrypted. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" * * The decryption functions and objects used from here on in * are based on the source of Spreadsheet-ParseExcel: * https://metacpan.org/release/Spreadsheet-ParseExcel */ protected function readFilepass(): void { $length = self::getUInt2d($this->data, $this->pos + 2); if ($length < 54) { throw new Exception('Unexpected file pass record length'); } $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (substr($recordData, 0, 2) !== "\x01\x00" || substr($recordData, 4, 2) !== "\x01\x00") { throw new Exception('Unsupported encryption algorithm'); } if (!$this->verifyPassword($this->encryptionPassword, substr($recordData, 6, 16), substr($recordData, 22, 16), substr($recordData, 38, 16), $this->md5Ctxt)) { throw new Exception('Decryption password incorrect'); } $this->encryption = self::MS_BIFF_CRYPTO_RC4; // Decryption required from the record after next onwards $this->encryptionStartPos = $this->pos + self::getUInt2d($this->data, $this->pos + 2); } /** * Make an RC4 decryptor for the given block. * * @param int $block Block for which to create decrypto * @param string $valContext MD5 context state */ private function makeKey(int $block, string $valContext): Xls\RC4 { $pwarray = str_repeat("\0", 64); for ($i = 0; $i < 5; ++$i) { $pwarray[$i] = $valContext[$i]; } $pwarray[5] = chr($block & 0xFF); $pwarray[6] = chr(($block >> 8) & 0xFF); $pwarray[7] = chr(($block >> 16) & 0xFF); $pwarray[8] = chr(($block >> 24) & 0xFF); $pwarray[9] = "\x80"; $pwarray[56] = "\x48"; $md5 = new Xls\MD5(); $md5->add($pwarray); $s = $md5->getContext(); return new Xls\RC4($s); } /** * Verify RC4 file password. * * @param string $password Password to check * @param string $docid Document id * @param string $salt_data Salt data * @param string $hashedsalt_data Hashed salt data * @param string $valContext Set to the MD5 context of the value * * @return bool Success */ private function verifyPassword(string $password, string $docid, string $salt_data, string $hashedsalt_data, string &$valContext): bool { $pwarray = str_repeat("\0", 64); $iMax = strlen($password); for ($i = 0; $i < $iMax; ++$i) { $o = ord(substr($password, $i, 1)); $pwarray[2 * $i] = chr($o & 0xFF); $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xFF); } $pwarray[2 * $i] = chr(0x80); $pwarray[56] = chr(($i << 4) & 0xFF); $md5 = new Xls\MD5(); $md5->add($pwarray); $mdContext1 = $md5->getContext(); $offset = 0; $keyoffset = 0; $tocopy = 5; $md5->reset(); while ($offset != 16) { if ((64 - $offset) < 5) { $tocopy = 64 - $offset; } for ($i = 0; $i <= $tocopy; ++$i) { $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i]; } $offset += $tocopy; if ($offset == 64) { $md5->add($pwarray); $keyoffset = $tocopy; $tocopy = 5 - $tocopy; $offset = 0; continue; } $keyoffset = 0; $tocopy = 5; for ($i = 0; $i < 16; ++$i) { $pwarray[$offset + $i] = $docid[$i]; } $offset += 16; } $pwarray[16] = "\x80"; for ($i = 0; $i < 47; ++$i) { $pwarray[17 + $i] = "\0"; } $pwarray[56] = "\x80"; $pwarray[57] = "\x0a"; $md5->add($pwarray); $valContext = $md5->getContext(); $key = $this->makeKey(0, $valContext); $salt = $key->RC4($salt_data); $hashedsalt = $key->RC4($hashedsalt_data); $salt .= "\x80" . str_repeat("\0", 47); $salt[56] = "\x80"; $md5->reset(); $md5->add($salt); $mdContext2 = $md5->getContext(); return $mdContext2 == $hashedsalt; } /** * CODEPAGE. * * This record stores the text encoding used to write byte * strings, stored as MS Windows code page identifier. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readCodepage(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; code page identifier $codepage = self::getUInt2d($recordData, 0); $this->codepage = CodePage::numberToName($codepage); } /** * DATEMODE. * * This record specifies the base date for displaying date * values. All dates are stored as count of days past this * base date. In BIFF2-BIFF4 this record is part of the * Calculation Settings Block. In BIFF5-BIFF8 it is * stored in the Workbook Globals Substream. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readDateMode(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; 0 = base 1900, 1 = base 1904 Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); $this->spreadsheet->setExcelCalendar(Date::CALENDAR_WINDOWS_1900); if (ord($recordData[0]) == 1) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); $this->spreadsheet->setExcelCalendar(Date::CALENDAR_MAC_1904); } } /** * Read a FONT record. */ protected function readFont(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { $objFont = new Font(); // offset: 0; size: 2; height of the font (in twips = 1/20 of a point) $size = self::getUInt2d($recordData, 0); $objFont->setSize($size / 20); // offset: 2; size: 2; option flags // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8) // bit: 1; mask 0x0002; italic $isItalic = (0x0002 & self::getUInt2d($recordData, 2)) >> 1; if ($isItalic) { $objFont->setItalic(true); } // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8) // bit: 3; mask 0x0008; strikethrough $isStrike = (0x0008 & self::getUInt2d($recordData, 2)) >> 3; if ($isStrike) { $objFont->setStrikethrough(true); } // offset: 4; size: 2; colour index $colorIndex = self::getUInt2d($recordData, 4); $objFont->colorIndex = $colorIndex; // offset: 6; size: 2; font weight $weight = self::getUInt2d($recordData, 6); // regular=400 bold=700 if ($weight >= 550) { $objFont->setBold(true); } // offset: 8; size: 2; escapement type $escapement = self::getUInt2d($recordData, 8); CellFont::escapement($objFont, $escapement); // offset: 10; size: 1; underline type $underlineType = ord($recordData[10]); CellFont::underline($objFont, $underlineType); // offset: 11; size: 1; font family // offset: 12; size: 1; character set // offset: 13; size: 1; not used // offset: 14; size: var; font name if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringShort(substr($recordData, 14)); } else { $string = $this->readByteStringShort(substr($recordData, 14)); } /** @var string[] $string */ $objFont->setName($string['value']); $this->objFonts[] = $objFont; } } /** * FORMAT. * * This record contains information about a number format. * All FORMAT records occur together in a sequential list. * * In BIFF2-BIFF4 other records referencing a FORMAT record * contain a zero-based index into this list. From BIFF5 on * the FORMAT record contains the index itself that will be * used by other records. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readFormat(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { $indexCode = self::getUInt2d($recordData, 0); if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong(substr($recordData, 2)); } else { // BIFF7 $string = $this->readByteStringShort(substr($recordData, 2)); } $formatString = $string['value']; // Apache Open Office sets wrong case writing to xls - issue 2239 if ($formatString === 'GENERAL') { $formatString = NumberFormat::FORMAT_GENERAL; } $this->formats[$indexCode] = $formatString; } } /** * XF - Extended Format. * * This record contains formatting information for cells, rows, columns or styles. * According to https://support.microsoft.com/en-us/help/147732 there are always at least 15 cell style XF * and 1 cell XF. * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF * and XF record 15 is a cell XF * We only read the first cell style XF and skip the remaining cell style XF records * We read all cell XF records. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readXf(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; $objStyle = new Style(); if (!$this->readDataOnly) { // offset: 0; size: 2; Index to FONT record if (self::getUInt2d($recordData, 0) < 4) { $fontIndex = self::getUInt2d($recordData, 0); } else { // this has to do with that index 4 is omitted in all BIFF versions for some strange reason // check the OpenOffice documentation of the FONT record $fontIndex = self::getUInt2d($recordData, 0) - 1; } if (isset($this->objFonts[$fontIndex])) { $objStyle->setFont($this->objFonts[$fontIndex]); } // offset: 2; size: 2; Index to FORMAT record $numberFormatIndex = self::getUInt2d($recordData, 2); if (isset($this->formats[$numberFormatIndex])) { // then we have user-defined format code $numberFormat = ['formatCode' => $this->formats[$numberFormatIndex]]; } elseif (($code = NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') { // then we have built-in format code $numberFormat = ['formatCode' => $code]; } else { // we set the general format code $numberFormat = ['formatCode' => NumberFormat::FORMAT_GENERAL]; } /** @var string[] $numberFormat */ $objStyle->getNumberFormat() ->setFormatCode($numberFormat['formatCode']); // offset: 4; size: 2; XF type, cell protection, and parent style XF // bit 2-0; mask 0x0007; XF_TYPE_PROT $xfTypeProt = self::getUInt2d($recordData, 4); // bit 0; mask 0x01; 1 = cell is locked $isLocked = (0x01 & $xfTypeProt) >> 0; $objStyle->getProtection()->setLocked($isLocked ? Protection::PROTECTION_INHERIT : Protection::PROTECTION_UNPROTECTED); // bit 1; mask 0x02; 1 = Formula is hidden $isHidden = (0x02 & $xfTypeProt) >> 1; $objStyle->getProtection()->setHidden($isHidden ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED); // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF $isCellStyleXf = (0x04 & $xfTypeProt) >> 2; // offset: 6; size: 1; Alignment and text break // bit 2-0, mask 0x07; horizontal alignment $horAlign = (0x07 & ord($recordData[6])) >> 0; Xls\Style\CellAlignment::horizontal($objStyle->getAlignment(), $horAlign); // bit 3, mask 0x08; wrap text $wrapText = (0x08 & ord($recordData[6])) >> 3; Xls\Style\CellAlignment::wrap($objStyle->getAlignment(), $wrapText); // bit 6-4, mask 0x70; vertical alignment $vertAlign = (0x70 & ord($recordData[6])) >> 4; Xls\Style\CellAlignment::vertical($objStyle->getAlignment(), $vertAlign); if ($this->version == self::XLS_BIFF8) { // offset: 7; size: 1; XF_ROTATION: Text rotation angle $angle = ord($recordData[7]); $rotation = 0; if ($angle <= 90) { $rotation = $angle; } elseif ($angle <= 180) { $rotation = 90 - $angle; } elseif ($angle == Alignment::TEXTROTATION_STACK_EXCEL) { $rotation = Alignment::TEXTROTATION_STACK_PHPSPREADSHEET; } $objStyle->getAlignment()->setTextRotation($rotation); // offset: 8; size: 1; Indentation, shrink to cell size, and text direction // bit: 3-0; mask: 0x0F; indent level $indent = (0x0F & ord($recordData[8])) >> 0; $objStyle->getAlignment()->setIndent($indent); // bit: 4; mask: 0x10; 1 = shrink content to fit into cell $shrinkToFit = (0x10 & ord($recordData[8])) >> 4; switch ($shrinkToFit) { case 0: $objStyle->getAlignment()->setShrinkToFit(false); break; case 1: $objStyle->getAlignment()->setShrinkToFit(true); break; } $readOrder = (0xC0 & ord($recordData[8])) >> 6; $objStyle->getAlignment()->setReadOrder($readOrder); // offset: 9; size: 1; Flags used for attribute groups // offset: 10; size: 4; Cell border lines and background area // bit: 3-0; mask: 0x0000000F; left style if ($bordersLeftStyle = Xls\Style\Border::lookup((0x0000000F & self::getInt4d($recordData, 10)) >> 0)) { $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle); } // bit: 7-4; mask: 0x000000F0; right style if ($bordersRightStyle = Xls\Style\Border::lookup((0x000000F0 & self::getInt4d($recordData, 10)) >> 4)) { $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle); } // bit: 11-8; mask: 0x00000F00; top style if ($bordersTopStyle = Xls\Style\Border::lookup((0x00000F00 & self::getInt4d($recordData, 10)) >> 8)) { $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle); } // bit: 15-12; mask: 0x0000F000; bottom style if ($bordersBottomStyle = Xls\Style\Border::lookup((0x0000F000 & self::getInt4d($recordData, 10)) >> 12)) { $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle); } // bit: 22-16; mask: 0x007F0000; left color $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::getInt4d($recordData, 10)) >> 16; // bit: 29-23; mask: 0x3F800000; right color $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::getInt4d($recordData, 10)) >> 23; // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom $diagonalDown = (0x40000000 & self::getInt4d($recordData, 10)) >> 30 ? true : false; // bit: 31; mask: 0x800000; 1 = diagonal line from bottom left to top right $diagonalUp = (self::HIGH_ORDER_BIT & self::getInt4d($recordData, 10)) >> 31 ? true : false; if ($diagonalUp === false) { if ($diagonalDown === false) { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE); } else { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN); } } elseif ($diagonalDown === false) { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP); } else { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH); } // offset: 14; size: 4; // bit: 6-0; mask: 0x0000007F; top color $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::getInt4d($recordData, 14)) >> 0; // bit: 13-7; mask: 0x00003F80; bottom color $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::getInt4d($recordData, 14)) >> 7; // bit: 20-14; mask: 0x001FC000; diagonal color $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::getInt4d($recordData, 14)) >> 14; // bit: 24-21; mask: 0x01E00000; diagonal style if ($bordersDiagonalStyle = Xls\Style\Border::lookup((0x01E00000 & self::getInt4d($recordData, 14)) >> 21)) { $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle); } // bit: 31-26; mask: 0xFC000000 fill pattern if ($fillType = FillPattern::lookup((self::FC000000 & self::getInt4d($recordData, 14)) >> 26)) { $objStyle->getFill()->setFillType($fillType); } // offset: 18; size: 2; pattern and background colour // bit: 6-0; mask: 0x007F; color index for pattern color $objStyle->getFill()->startcolorIndex = (0x007F & self::getUInt2d($recordData, 18)) >> 0; // bit: 13-7; mask: 0x3F80; color index for pattern background $objStyle->getFill()->endcolorIndex = (0x3F80 & self::getUInt2d($recordData, 18)) >> 7; } else { // BIFF5 // offset: 7; size: 1; Text orientation and flags $orientationAndFlags = ord($recordData[7]); // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation $xfOrientation = (0x03 & $orientationAndFlags) >> 0; switch ($xfOrientation) { case 0: $objStyle->getAlignment()->setTextRotation(0); break; case 1: $objStyle->getAlignment()->setTextRotation(Alignment::TEXTROTATION_STACK_PHPSPREADSHEET); break; case 2: $objStyle->getAlignment()->setTextRotation(90); break; case 3: $objStyle->getAlignment()->setTextRotation(-90); break; } // offset: 8; size: 4; cell border lines and background area $borderAndBackground = self::getInt4d($recordData, 8); // bit: 6-0; mask: 0x0000007F; color index for pattern color $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0; // bit: 13-7; mask: 0x00003F80; color index for pattern background $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7; // bit: 21-16; mask: 0x003F0000; fill pattern $objStyle->getFill()->setFillType(FillPattern::lookup((0x003F0000 & $borderAndBackground) >> 16)); // bit: 24-22; mask: 0x01C00000; bottom line style $objStyle->getBorders()->getBottom()->setBorderStyle(Xls\Style\Border::lookup((0x01C00000 & $borderAndBackground) >> 22)); // bit: 31-25; mask: 0xFE000000; bottom line color $objStyle->getBorders()->getBottom()->colorIndex = (self::FE000000 & $borderAndBackground) >> 25; // offset: 12; size: 4; cell border lines $borderLines = self::getInt4d($recordData, 12); // bit: 2-0; mask: 0x00000007; top line style $objStyle->getBorders()->getTop()->setBorderStyle(Xls\Style\Border::lookup((0x00000007 & $borderLines) >> 0)); // bit: 5-3; mask: 0x00000038; left line style $objStyle->getBorders()->getLeft()->setBorderStyle(Xls\Style\Border::lookup((0x00000038 & $borderLines) >> 3)); // bit: 8-6; mask: 0x000001C0; right line style $objStyle->getBorders()->getRight()->setBorderStyle(Xls\Style\Border::lookup((0x000001C0 & $borderLines) >> 6)); // bit: 15-9; mask: 0x0000FE00; top line color index $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9; // bit: 22-16; mask: 0x007F0000; left line color index $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16; // bit: 29-23; mask: 0x3F800000; right line color index $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23; } // add cellStyleXf or cellXf and update mapping if ($isCellStyleXf) { // we only read one style XF record which is always the first if ($this->xfIndex == 0) { $this->spreadsheet->addCellStyleXf($objStyle); $this->mapCellStyleXfIndex[$this->xfIndex] = 0; } } else { // we read all cell XF records $this->spreadsheet->addCellXf($objStyle); $this->mapCellXfIndex[$this->xfIndex] = count($this->spreadsheet->getCellXfCollection()) - 1; } // update XF index for when we read next record ++$this->xfIndex; } } protected function readXfExt(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 0x087D = repeated header // offset: 2; size: 2 // offset: 4; size: 8; not used // offset: 12; size: 2; record version // offset: 14; size: 2; index to XF record which this record modifies $ixfe = self::getUInt2d($recordData, 14); // offset: 16; size: 2; not used // offset: 18; size: 2; number of extension properties that follow //$cexts = self::getUInt2d($recordData, 18); // start reading the actual extension data $offset = 20; while ($offset < $length) { // extension type $extType = self::getUInt2d($recordData, $offset); // extension length $cb = self::getUInt2d($recordData, $offset + 2); // extension data $extData = substr($recordData, $offset + 4, $cb); switch ($extType) { case 4: // fill start color $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); $fill->getStartColor()->setRGB($rgb); $fill->startcolorIndex = null; // normal color index does not apply, discard } } break; case 5: // fill end color $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); $fill->getEndColor()->setRGB($rgb); $fill->endcolorIndex = null; // normal color index does not apply, discard } } break; case 7: // border color top $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $top = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getTop(); $top->getColor()->setRGB($rgb); $top->colorIndex = null; // normal color index does not apply, discard } } break; case 8: // border color bottom $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $bottom = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getBottom(); $bottom->getColor()->setRGB($rgb); $bottom->colorIndex = null; // normal color index does not apply, discard } } break; case 9: // border color left $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $left = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getLeft(); $left->getColor()->setRGB($rgb); $left->colorIndex = null; // normal color index does not apply, discard } } break; case 10: // border color right $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $right = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getRight(); $right->getColor()->setRGB($rgb); $right->colorIndex = null; // normal color index does not apply, discard } } break; case 11: // border color diagonal $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $diagonal = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getDiagonal(); $diagonal->getColor()->setRGB($rgb); $diagonal->colorIndex = null; // normal color index does not apply, discard } } break; case 13: // font color $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $font = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFont(); $font->getColor()->setRGB($rgb); $font->colorIndex = null; // normal color index does not apply, discard } } break; } $offset += $cb; } } } /** * Read STYLE record. */ protected function readStyle(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; index to XF record and flag for built-in style $ixfe = self::getUInt2d($recordData, 0); // bit: 11-0; mask 0x0FFF; index to XF record //$xfIndex = (0x0FFF & $ixfe) >> 0; // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15); if ($isBuiltIn) { // offset: 2; size: 1; identifier for built-in style $builtInId = ord($recordData[2]); switch ($builtInId) { case 0x00: // currently, we are not using this for anything break; default: break; } } // user-defined; not supported by PhpSpreadsheet } } /** * Read PALETTE record. */ protected function readPalette(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; number of following colors $nm = self::getUInt2d($recordData, 0); // list of RGB colors for ($i = 0; $i < $nm; ++$i) { $rgb = substr($recordData, 2 + 4 * $i, 4); $this->palette[] = self::readRGB($rgb); } } } /** * SHEET. * * This record is located in the Workbook Globals * Substream and represents a sheet inside the workbook. * One SHEET record is written for each sheet. It stores the * sheet name and a stream offset to the BOF record of the * respective Sheet Substream within the Workbook Stream. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readSheet(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // offset: 0; size: 4; absolute stream position of the BOF record of the sheet // NOTE: not encrypted $rec_offset = self::getInt4d($this->data, $this->pos + 4); // move stream pointer to next record $this->pos += 4 + $length; // offset: 4; size: 1; sheet state $sheetState = match (ord($recordData[4])) { 0x00 => Worksheet::SHEETSTATE_VISIBLE, 0x01 => Worksheet::SHEETSTATE_HIDDEN, 0x02 => Worksheet::SHEETSTATE_VERYHIDDEN, default => Worksheet::SHEETSTATE_VISIBLE, }; // offset: 5; size: 1; sheet type $sheetType = ord($recordData[5]); // offset: 6; size: var; sheet name $rec_name = null; if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringShort(substr($recordData, 6)); $rec_name = $string['value']; } elseif ($this->version == self::XLS_BIFF7) { $string = $this->readByteStringShort(substr($recordData, 6)); $rec_name = $string['value']; } /** @var string $rec_name */ $this->sheets[] = [ 'name' => $rec_name, 'offset' => $rec_offset, 'sheetState' => $sheetState, 'sheetType' => $sheetType, ]; } /** * Read EXTERNALBOOK record. */ protected function readExternalBook(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset within record data $offset = 0; // there are 4 types of records if (strlen($recordData) > 4) { // external reference // offset: 0; size: 2; number of sheet names ($nm) $nm = self::getUInt2d($recordData, 0); $offset += 2; // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length) $encodedUrlString = self::readUnicodeStringLong(substr($recordData, 2)); $offset += $encodedUrlString['size']; // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length) $externalSheetNames = []; for ($i = 0; $i < $nm; ++$i) { $externalSheetNameString = self::readUnicodeStringLong(substr($recordData, $offset)); $externalSheetNames[] = $externalSheetNameString['value']; $offset += $externalSheetNameString['size']; } // store the record data $this->externalBooks[] = [ 'type' => 'external', 'encodedUrl' => $encodedUrlString['value'], 'externalSheetNames' => $externalSheetNames, ]; } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) { // internal reference // offset: 0; size: 2; number of sheet in this document // offset: 2; size: 2; 0x01 0x04 $this->externalBooks[] = [ 'type' => 'internal', ]; } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) { // add-in function // offset: 0; size: 2; 0x0001 $this->externalBooks[] = [ 'type' => 'addInFunction', ]; } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) { // DDE links, OLE links // offset: 0; size: 2; 0x0000 // offset: 2; size: var; encoded source document name $this->externalBooks[] = [ 'type' => 'DDEorOLE', ]; } } /** * Read EXTERNNAME record. */ protected function readExternName(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // external sheet references provided for named cells if ($this->version == self::XLS_BIFF8) { // offset: 0; size: 2; options //$options = self::getUInt2d($recordData, 0); // offset: 2; size: 2; // offset: 4; size: 2; not used // offset: 6; size: var $nameString = self::readUnicodeStringShort(substr($recordData, 6)); // offset: var; size: var; formula data $offset = 6 + $nameString['size']; $formula = $this->getFormulaFromStructure(substr($recordData, $offset)); $this->externalNames[] = [ 'name' => $nameString['value'], 'formula' => $formula, ]; } } /** * Read EXTERNSHEET record. */ protected function readExternSheet(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // external sheet references provided for named cells if ($this->version == self::XLS_BIFF8) { // offset: 0; size: 2; number of following ref structures $nm = self::getUInt2d($recordData, 0); for ($i = 0; $i < $nm; ++$i) { $this->ref[] = [ // offset: 2 + 6 * $i; index to EXTERNALBOOK record 'externalBookIndex' => self::getUInt2d($recordData, 2 + 6 * $i), // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record 'firstSheetIndex' => self::getUInt2d($recordData, 4 + 6 * $i), // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record 'lastSheetIndex' => self::getUInt2d($recordData, 6 + 6 * $i), ]; } } } /** * DEFINEDNAME. * * This record is part of a Link Table. It contains the name * and the token array of an internal defined name. Token * arrays of defined names contain tokens with aberrant * token classes. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readDefinedName(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8) { // retrieves named cells // offset: 0; size: 2; option flags $opts = self::getUInt2d($recordData, 0); // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name $isBuiltInName = (0x0020 & $opts) >> 5; // offset: 2; size: 1; keyboard shortcut // offset: 3; size: 1; length of the name (character count) $nlen = ord($recordData[3]); // offset: 4; size: 2; size of the formula data (it can happen that this is zero) // note: there can also be additional data, this is not included in $flen $flen = self::getUInt2d($recordData, 4); // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based) $scope = self::getUInt2d($recordData, 8); // offset: 14; size: var; Name (Unicode string without length field) $string = self::readUnicodeString(substr($recordData, 14), $nlen); // offset: var; size: $flen; formula data $offset = 14 + $string['size']; $formulaStructure = pack('v', $flen) . substr($recordData, $offset); try { $formula = $this->getFormulaFromStructure($formulaStructure); } catch (PhpSpreadsheetException) { $formula = ''; $isBuiltInName = 0; } $this->definedname[] = [ 'isBuiltInName' => $isBuiltInName, 'name' => $string['value'], 'formula' => $formula, 'scope' => $scope, ]; } } /** * Read MSODRAWINGGROUP record. */ protected function readMsoDrawingGroup(): void { //$length = self::getUInt2d($this->data, $this->pos + 2); // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); /** @var string */ $recordData = $splicedRecordData['recordData']; $this->drawingGroupData .= $recordData; } /** * SST - Shared String Table. * * This record contains a list of all strings used anywhere * in the workbook. Each string occurs only once. The * workbook uses indexes into the list to reference the * strings. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readSst(): void { // offset within (spliced) record data $pos = 0; // Limit global SST position, further control for bad SST Length in BIFF8 data $limitposSST = 0; // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); $recordData = $splicedRecordData['recordData']; /** @var mixed[] */ $spliceOffsets = $splicedRecordData['spliceOffsets']; // offset: 0; size: 4; total number of strings in the workbook $pos += 4; // offset: 4; size: 4; number of following strings ($nm) /** @var string $recordData */ $nm = self::getInt4d($recordData, 4); $pos += 4; // look up limit position foreach ($spliceOffsets as $spliceOffset) { // it can happen that the string is empty, therefore we need // <= and not just < if ($pos <= $spliceOffset) { $limitposSST = $spliceOffset; } } // loop through the Unicode strings (16-bit length) for ($i = 0; $i < $nm && $pos < $limitposSST; ++$i) { // number of characters in the Unicode string /** @var int $pos */ $numChars = self::getUInt2d($recordData, $pos); /** @var int $pos */ $pos += 2; // option flags /** @var string $recordData */ $optionFlags = ord($recordData[$pos]); ++$pos; // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed $isCompressed = (($optionFlags & 0x01) == 0); // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic $hasAsian = (($optionFlags & 0x04) != 0); // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text $hasRichText = (($optionFlags & 0x08) != 0); $formattingRuns = 0; if ($hasRichText) { // number of Rich-Text formatting runs $formattingRuns = self::getUInt2d($recordData, $pos); $pos += 2; } $extendedRunLength = 0; if ($hasAsian) { // size of Asian phonetic setting $extendedRunLength = self::getInt4d($recordData, $pos); $pos += 4; } // expected byte length of character array if not split $len = ($isCompressed) ? $numChars : $numChars * 2; // look up limit position - Check it again to be sure that no error occurs when parsing SST structure $limitpos = null; foreach ($spliceOffsets as $spliceOffset) { // it can happen that the string is empty, therefore we need // <= and not just < if ($pos <= $spliceOffset) { $limitpos = $spliceOffset; break; } } /** @var int $limitpos */ if ($pos + $len <= $limitpos) { // character array is not split between records $retstr = substr($recordData, $pos, $len); $pos += $len; } else { // character array is split between records // first part of character array $retstr = substr($recordData, $pos, $limitpos - $pos); $bytesRead = $limitpos - $pos; // remaining characters in Unicode string $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2)); $pos = $limitpos; // keep reading the characters while ($charsLeft > 0) { // look up next limit position, in case the string span more than one continue record foreach ($spliceOffsets as $spliceOffset) { if ($pos < $spliceOffset) { $limitpos = $spliceOffset; break; } } // repeated option flags // OpenOffice.org documentation 5.21 /** @var int $pos */ $option = ord($recordData[$pos]); ++$pos; /** @var int $limitpos */ if ($isCompressed && ($option == 0)) { // 1st fragment compressed // this fragment compressed /** @var int */ $len = min($charsLeft, $limitpos - $pos); $retstr .= substr($recordData, $pos, $len); $charsLeft -= $len; $isCompressed = true; } elseif (!$isCompressed && ($option != 0)) { // 1st fragment uncompressed // this fragment uncompressed /** @var int */ $len = min($charsLeft * 2, $limitpos - $pos); $retstr .= substr($recordData, $pos, $len); $charsLeft -= $len / 2; $isCompressed = false; } elseif (!$isCompressed && ($option == 0)) { // 1st fragment uncompressed // this fragment compressed $len = min($charsLeft, $limitpos - $pos); for ($j = 0; $j < $len; ++$j) { $retstr .= $recordData[$pos + $j] . chr(0); } $charsLeft -= $len; $isCompressed = false; } else { // 1st fragment compressed // this fragment uncompressed $newstr = ''; $jMax = strlen($retstr); for ($j = 0; $j < $jMax; ++$j) { $newstr .= $retstr[$j] . chr(0); } $retstr = $newstr; /** @var int */ $len = min($charsLeft * 2, $limitpos - $pos); $retstr .= substr($recordData, $pos, $len); $charsLeft -= $len / 2; $isCompressed = false; } $pos += $len; } } // convert to UTF-8 $retstr = self::encodeUTF16($retstr, $isCompressed); // read additional Rich-Text information, if any $fmtRuns = []; if ($hasRichText) { // list of formatting runs for ($j = 0; $j < $formattingRuns; ++$j) { // first formatted character; zero-based /** @var int $pos */ $charPos = self::getUInt2d($recordData, $pos + $j * 4); // index to font record $fontIndex = self::getUInt2d($recordData, $pos + 2 + $j * 4); $fmtRuns[] = [ 'charPos' => $charPos, 'fontIndex' => $fontIndex, ]; } $pos += 4 * $formattingRuns; } // read additional Asian phonetics information, if any if ($hasAsian) { // For Asian phonetic settings, we skip the extended string data $pos += $extendedRunLength; } // store the shared sting $this->sst[] = [ 'value' => $retstr, 'fmtRuns' => $fmtRuns, ]; } // getSplicedRecordData() takes care of moving current position in data stream } /** * Read PRINTGRIDLINES record. */ protected function readPrintGridlines(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines $printGridlines = (bool) self::getUInt2d($recordData, 0); $this->phpSheet->setPrintGridlines($printGridlines); } } /** * Read DEFAULTROWHEIGHT record. */ protected function readDefaultRowHeight(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; option flags // offset: 2; size: 2; default height for unused rows, (twips 1/20 point) $height = self::getUInt2d($recordData, 2); $this->phpSheet->getDefaultRowDimension()->setRowHeight($height / 20); } /** * Read SHEETPR record. */ protected function readSheetPr(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2 // bit: 6; mask: 0x0040; 0 = outline buttons above outline group $isSummaryBelow = (0x0040 & self::getUInt2d($recordData, 0)) >> 6; $this->phpSheet->setShowSummaryBelow((bool) $isSummaryBelow); // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group $isSummaryRight = (0x0080 & self::getUInt2d($recordData, 0)) >> 7; $this->phpSheet->setShowSummaryRight((bool) $isSummaryRight); // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages // this corresponds to radio button setting in page setup dialog in Excel $this->isFitToPages = (bool) ((0x0100 & self::getUInt2d($recordData, 0)) >> 8); } /** * Read HORIZONTALPAGEBREAKS record. */ protected function readHorizontalPageBreaks(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { // offset: 0; size: 2; number of the following row index structures $nm = self::getUInt2d($recordData, 0); // offset: 2; size: 6 * $nm; list of $nm row index structures for ($i = 0; $i < $nm; ++$i) { $r = self::getUInt2d($recordData, 2 + 6 * $i); $cf = self::getUInt2d($recordData, 2 + 6 * $i + 2); //$cl = self::getUInt2d($recordData, 2 + 6 * $i + 4); // not sure why two column indexes are necessary? $this->phpSheet->setBreak([$cf + 1, $r], Worksheet::BREAK_ROW); } } } /** * Read VERTICALPAGEBREAKS record. */ protected function readVerticalPageBreaks(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { // offset: 0; size: 2; number of the following column index structures $nm = self::getUInt2d($recordData, 0); // offset: 2; size: 6 * $nm; list of $nm row index structures for ($i = 0; $i < $nm; ++$i) { $c = self::getUInt2d($recordData, 2 + 6 * $i); $rf = self::getUInt2d($recordData, 2 + 6 * $i + 2); //$rl = self::getUInt2d($recordData, 2 + 6 * $i + 4); // not sure why two row indexes are necessary? $this->phpSheet->setBreak([$c + 1, ($rf > 0) ? $rf : 1], Worksheet::BREAK_COLUMN); } } } /** * Read HEADER record. */ protected function readHeader(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: var // realized that $recordData can be empty even when record exists if ($recordData) { if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong($recordData); } else { $string = $this->readByteStringShort($recordData); } /** @var string[] $string */ $this->phpSheet ->getHeaderFooter() ->setOddHeader($string['value']); $this->phpSheet ->getHeaderFooter() ->setEvenHeader($string['value']); } } } /** * Read FOOTER record. */ protected function readFooter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: var // realized that $recordData can be empty even when record exists if ($recordData) { if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong($recordData); } else { $string = $this->readByteStringShort($recordData); } /** @var string */ $temp = $string['value']; $this->phpSheet ->getHeaderFooter() ->setOddFooter($temp); $this->phpSheet ->getHeaderFooter() ->setEvenFooter($temp); } } } /** * Read HCENTER record. */ protected function readHcenter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally $isHorizontalCentered = (bool) self::getUInt2d($recordData, 0); $this->phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered); } } /** * Read VCENTER record. */ protected function readVcenter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered $isVerticalCentered = (bool) self::getUInt2d($recordData, 0); $this->phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered); } } /** * Read LEFTMARGIN record. */ protected function readLeftMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setLeft(self::extractNumber($recordData)); } } /** * Read RIGHTMARGIN record. */ protected function readRightMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setRight(self::extractNumber($recordData)); } } /** * Read TOPMARGIN record. */ protected function readTopMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setTop(self::extractNumber($recordData)); } } /** * Read BOTTOMMARGIN record. */ protected function readBottomMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setBottom(self::extractNumber($recordData)); } } /** * Read PAGESETUP record. */ protected function readPageSetup(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; paper size $paperSize = self::getUInt2d($recordData, 0); // offset: 2; size: 2; scaling factor $scale = self::getUInt2d($recordData, 2); // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed $fitToWidth = self::getUInt2d($recordData, 6); // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed $fitToHeight = self::getUInt2d($recordData, 8); // offset: 10; size: 2; option flags // bit: 0; mask: 0x0001; 0=down then over, 1=over then down $isOverThenDown = (0x0001 & self::getUInt2d($recordData, 10)); // bit: 1; mask: 0x0002; 0=landscape, 1=portrait $isPortrait = (0x0002 & self::getUInt2d($recordData, 10)) >> 1; // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init // when this bit is set, do not use flags for those properties $isNotInit = (0x0004 & self::getUInt2d($recordData, 10)) >> 2; if (!$isNotInit) { $this->phpSheet->getPageSetup()->setPaperSize($paperSize); $this->phpSheet->getPageSetup()->setPageOrder(((bool) $isOverThenDown) ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER); $this->phpSheet->getPageSetup()->setOrientation(((bool) $isPortrait) ? PageSetup::ORIENTATION_PORTRAIT : PageSetup::ORIENTATION_LANDSCAPE); $this->phpSheet->getPageSetup()->setScale($scale, false); $this->phpSheet->getPageSetup()->setFitToPage((bool) $this->isFitToPages); $this->phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false); $this->phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false); } // offset: 16; size: 8; header margin (IEEE 754 floating-point value) $marginHeader = self::extractNumber(substr($recordData, 16, 8)); $this->phpSheet->getPageMargins()->setHeader($marginHeader); // offset: 24; size: 8; footer margin (IEEE 754 floating-point value) $marginFooter = self::extractNumber(substr($recordData, 24, 8)); $this->phpSheet->getPageMargins()->setFooter($marginFooter); } } /** * PROTECT - Sheet protection (BIFF2 through BIFF8) * if this record is omitted, then it also means no sheet protection. */ protected function readProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; // bit 0, mask 0x01; 1 = sheet is protected $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0; $this->phpSheet->getProtection()->setSheet((bool) $bool); } /** * SCENPROTECT. */ protected function readScenProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; // bit: 0, mask 0x01; 1 = scenarios are protected $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0; $this->phpSheet->getProtection()->setScenarios((bool) $bool); } /** * OBJECTPROTECT. */ protected function readObjectProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; // bit: 0, mask 0x01; 1 = objects are protected $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0; $this->phpSheet->getProtection()->setObjects((bool) $bool); } /** * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8). */ protected function readPassword(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 16-bit hash value of password $password = strtoupper(dechex(self::getUInt2d($recordData, 0))); // the hashed password $this->phpSheet->getProtection()->setPassword($password, true); } } /** * Read DEFCOLWIDTH record. */ protected function readDefColWidth(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; default column width $width = self::getUInt2d($recordData, 0); if ($width != 8) { $this->phpSheet->getDefaultColumnDimension()->setWidth($width); } } /** * Read COLINFO record. */ protected function readColInfo(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; index to first column in range $firstColumnIndex = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to last column in range $lastColumnIndex = self::getUInt2d($recordData, 2); // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character $width = self::getUInt2d($recordData, 4); // offset: 6; size: 2; index to XF record for default column formatting $xfIndex = self::getUInt2d($recordData, 6); // offset: 8; size: 2; option flags // bit: 0; mask: 0x0001; 1= columns are hidden $isHidden = (0x0001 & self::getUInt2d($recordData, 8)) >> 0; // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline) $level = (0x0700 & self::getUInt2d($recordData, 8)) >> 8; // bit: 12; mask: 0x1000; 1 = collapsed $isCollapsed = (bool) ((0x1000 & self::getUInt2d($recordData, 8)) >> 12); // offset: 10; size: 2; not used for ($i = $firstColumnIndex + 1; $i <= $lastColumnIndex + 1; ++$i) { if ($lastColumnIndex == AddressRange::MAX_COLUMN_INT_XLS - 1 || $lastColumnIndex == AddressRange::MAX_COLUMN_INT) { $this->phpSheet->getDefaultColumnDimension()->setWidth($width / 256); break; } $this->phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256); $this->phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden); $this->phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level); $this->phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed); if (isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } } /** * ROW. * * This record contains the properties of a single row in a * sheet. Rows and cells in a sheet are divided into blocks * of 32 rows. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readRow(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; index of this row $r = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column of the first cell which is described by a cell record // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1 // offset: 6; size: 2; // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point $height = (0x7FFF & self::getUInt2d($recordData, 6)) >> 0; // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height $useDefaultHeight = (0x8000 & self::getUInt2d($recordData, 6)) >> 15; if (!$useDefaultHeight) { if ( $this->phpSheet->getDefaultRowDimension()->getRowHeight() > 0 ) { $this->phpSheet->getRowDimension($r + 1) ->setCustomFormat(true, ($height === 255) ? -1 : ($height / 20)); } else { $this->phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20); } } // offset: 8; size: 2; not used // offset: 10; size: 2; not used in BIFF5-BIFF8 // offset: 12; size: 4; option flags and default row formatting // bit: 2-0: mask: 0x00000007; outline level of the row $level = (0x00000007 & self::getInt4d($recordData, 12)) >> 0; $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level); // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed $isCollapsed = (bool) ((0x00000010 & self::getInt4d($recordData, 12)) >> 4); $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed); // bit: 5; mask: 0x00000020; 1 = row is hidden $isHidden = (0x00000020 & self::getInt4d($recordData, 12)) >> 5; $this->phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden); // bit: 7; mask: 0x00000080; 1 = row has explicit format $hasExplicitFormat = (0x00000080 & self::getInt4d($recordData, 12)) >> 7; // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record $xfIndex = (0x0FFF0000 & self::getInt4d($recordData, 12)) >> 16; if ($hasExplicitFormat && isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getRowDimension($r + 1)->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read RK record * This record represents a cell that contains an RK value * (encoded integer or floating-point value). If a * floating-point value cannot be encoded to an RK value, * a NUMBER record will be written. This record replaces the * record INTEGER written in BIFF2. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readRk(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 4; RK value $rknum = self::getInt4d($recordData, 6); $numValue = self::getIEEE754($rknum); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add style information $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // add cell $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC); } } /** * Read LABELSST record * This record represents a cell that contains a string. It * replaces the LABEL record and RSTRING record used in * BIFF2-BIFF5. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readLabelSst(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); $cell = null; // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 4; index to SST record $index = self::getInt4d($recordData, 6); // add cell if (($fmtRuns = $this->sst[$index]['fmtRuns']) && !$this->readDataOnly) { // then we should treat as rich text $richText = new RichText(); $charPos = 0; $sstCount = count($this->sst[$index]['fmtRuns']); for ($i = 0; $i <= $sstCount; ++$i) { /** @var mixed[][] $fmtRuns */ if (isset($fmtRuns[$i])) { /** @var int[] */ $temp = $fmtRuns[$i]; $temp = $temp['charPos']; /** @var int $charPos */ $text = StringHelper::substring($this->sst[$index]['value'], $charPos, $temp - $charPos); $charPos = $temp; } else { $text = StringHelper::substring($this->sst[$index]['value'], $charPos, StringHelper::countCharacters($this->sst[$index]['value'])); } if (StringHelper::countCharacters($text) > 0) { if ($i == 0) { // first text run, no style $richText->createText($text); } else { $textRun = $richText->createTextRun($text); /** @var int[][] $fmtRuns */ if (isset($fmtRuns[$i - 1])) { if ($fmtRuns[$i - 1]['fontIndex'] < 4) { $fontIndex = $fmtRuns[$i - 1]['fontIndex']; } else { // this has to do with that index 4 is omitted in all BIFF versions for some stra nge reason // check the OpenOffice documentation of the FONT record /** @var int */ $temp = $fmtRuns[$i - 1]['fontIndex']; $fontIndex = $temp - 1; } if (array_key_exists($fontIndex, $this->objFonts) === false) { $fontIndex = count($this->objFonts) - 1; } $textRun->setFont(clone $this->objFonts[$fontIndex]); } } } } if ($this->readEmptyCells || trim($richText->getPlainText()) !== '') { $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($richText, DataType::TYPE_STRING); } } else { if ($this->readEmptyCells || trim($this->sst[$index]['value']) !== '') { $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($this->sst[$index]['value'], DataType::TYPE_STRING); } } if (!$this->readDataOnly && $cell !== null && isset($this->mapCellXfIndex[$xfIndex])) { // add style information $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read MULRK record * This record represents a cell range containing RK value * cells. All cells are located in the same row. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readMulRk(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to first column $colFirst = self::getUInt2d($recordData, 2); // offset: var; size: 2; index to last column $colLast = self::getUInt2d($recordData, $length - 2); $columns = $colLast - $colFirst + 1; // offset within record data $offset = 4; for ($i = 1; $i <= $columns; ++$i) { $columnString = Coordinate::stringFromColumnIndex($colFirst + $i); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: var; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, $offset); // offset: var; size: 4; RK value $numValue = self::getIEEE754(self::getInt4d($recordData, $offset + 2)); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // add cell value $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC); } $offset += 6; } } /** * Read NUMBER record * This record represents a cell that contains a * floating-point value. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readNumber(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); $numValue = self::extractNumber(substr($recordData, 6, 8)); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // add cell value $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC); } } /** * Read FORMULA record + perhaps a following STRING record if formula result is a string * This record contains the token array and the result of a * formula cell. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readFormula(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; row index $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; col index $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // offset: 20: size: variable; formula structure $formulaStructure = substr($recordData, 20); // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc. $options = self::getUInt2d($recordData, 14); // bit: 0; mask: 0x0001; 1 = recalculate always // bit: 1; mask: 0x0002; 1 = calculate on open // bit: 2; mask: 0x0008; 1 = part of a shared formula $isPartOfSharedFormula = (bool) (0x0008 & $options); // WARNING: // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true // the formula data may be ordinary formula data, therefore we need to check // explicitly for the tExp token (0x01) $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure[2]) == 0x01; if ($isPartOfSharedFormula) { // part of shared formula which means there will be a formula with a tExp token and nothing else // get the base cell, grab tExp token $baseRow = self::getUInt2d($formulaStructure, 3); $baseCol = self::getUInt2d($formulaStructure, 5); $this->baseCell = Coordinate::stringFromColumnIndex($baseCol + 1) . ($baseRow + 1); } // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { if ($isPartOfSharedFormula) { // formula is added to this cell after the sheet has been read $this->sharedFormulaParts[$columnString . ($row + 1)] = $this->baseCell; } // offset: 16: size: 4; not used // offset: 4; size: 2; XF index $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 8; result of the formula if ((ord($recordData[6]) == 0) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255)) { // String formula. Result follows in appended STRING record $dataType = DataType::TYPE_STRING; // read possible SHAREDFMLA record $code = self::getUInt2d($this->data, $this->pos); if ($code == self::XLS_TYPE_SHAREDFMLA) { $this->readSharedFmla(); } // read STRING record $value = $this->readString(); } elseif ( (ord($recordData[6]) == 1) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255) ) { // Boolean formula. Result is in +2; 0=false, 1=true $dataType = DataType::TYPE_BOOL; $value = (bool) ord($recordData[8]); } elseif ( (ord($recordData[6]) == 2) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255) ) { // Error formula. Error code is in +2 $dataType = DataType::TYPE_ERROR; $value = Xls\ErrorCode::lookup(ord($recordData[8])); } elseif ( (ord($recordData[6]) == 3) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255) ) { // Formula result is a null string $dataType = DataType::TYPE_NULL; $value = ''; } else { // forumla result is a number, first 14 bytes like _NUMBER record $dataType = DataType::TYPE_NUMERIC; $value = self::extractNumber(substr($recordData, 6, 8)); } $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // store the formula if (!$isPartOfSharedFormula) { // not part of shared formula // add cell value. If we can read formula, populate with formula, otherwise just used cached value try { if ($this->version != self::XLS_BIFF8) { throw new Exception('Not BIFF8. Can only read BIFF8 formulas'); } $formula = $this->getFormulaFromStructure($formulaStructure); // get formula in human language $cell->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA); } catch (PhpSpreadsheetException) { $cell->setValueExplicit($value, $dataType); } } else { if ($this->version == self::XLS_BIFF8) { // do nothing at this point, formula id added later in the code } else { $cell->setValueExplicit($value, $dataType); } } // store the cached calculated value $cell->setCalculatedValue($value, $dataType === DataType::TYPE_NUMERIC); } } /** * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader, * which usually contains relative references. * These will be used to construct the formula in each shared formula part after the sheet is read. */ protected function readSharedFmla(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything //$cellRange = substr($recordData, 0, 6); //$cellRange = Xls\Biff5::readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax // offset: 6, size: 1; not used // offset: 7, size: 1; number of existing FORMULA records for this shared formula //$no = ord($recordData[7]); // offset: 8, size: var; Binary token array of the shared formula $formula = substr($recordData, 8); // at this point we only store the shared formula for later use $this->sharedFormulas[$this->baseCell] = $formula; } /** * Read a STRING record from current stream position and advance the stream pointer to next record * This record is used for storing result from FORMULA record when it is a string, and * it occurs directly after the FORMULA record. * * @return string The string contents as UTF-8 */ protected function readString(): string { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong($recordData); $value = $string['value']; } else { $string = $this->readByteStringLong($recordData); $value = $string['value']; } /** @var string $value */ return $value; } /** * Read BOOLERR record * This record represents a Boolean value or error value * cell. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readBoolErr(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; row index $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; column index $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 1; the boolean value or error value $boolErr = ord($recordData[6]); // offset: 7; size: 1; 0=boolean; 1=error $isError = ord($recordData[7]); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); switch ($isError) { case 0: // boolean $value = (bool) $boolErr; // add cell value $cell->setValueExplicit($value, DataType::TYPE_BOOL); break; case 1: // error type $value = Xls\ErrorCode::lookup($boolErr); // add cell value $cell->setValueExplicit($value, DataType::TYPE_ERROR); break; } if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read MULBLANK record * This record represents a cell range of empty cells. All * cells are located in the same row. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readMulBlank(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to first column $fc = self::getUInt2d($recordData, 2); // offset: 4; size: 2 x nc; list of indexes to XF records // add style information if (!$this->readDataOnly && $this->readEmptyCells) { for ($i = 0; $i < $length / 2 - 3; ++$i) { $columnString = Coordinate::stringFromColumnIndex($fc + $i + 1); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { $xfIndex = self::getUInt2d($recordData, 4 + 2 * $i); if (isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } } // offset: 6; size 2; index to last column (not needed) } /** * Read LABEL record * This record represents a cell that contains a string. In * BIFF8 it is usually replaced by the LABELSST record. * Excel still uses this record, if it copies unformatted * text cells to the clipboard. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readLabel(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; XF index $xfIndex = self::getUInt2d($recordData, 4); // add cell value // todo: what if string is very long? continue record if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong(substr($recordData, 6)); $value = $string['value']; } else { $string = $this->readByteStringLong(substr($recordData, 6)); $value = $string['value']; } /** @var string $value */ if ($this->readEmptyCells || trim($value) !== '') { $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($value, DataType::TYPE_STRING); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } } /** * Read BLANK record. */ protected function readBlank(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; row index $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; col index $col = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($col + 1); // Read cell? if ($this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; XF index $xfIndex = self::getUInt2d($recordData, 4); // add style information if (!$this->readDataOnly && $this->readEmptyCells && isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read MSODRAWING record. */ protected function readMsoDrawing(): void { //$length = self::getUInt2d($this->data, $this->pos + 2); // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); $recordData = $splicedRecordData['recordData']; $this->drawingData .= StringHelper::convertToString($recordData); } /** * Read OBJ record. */ protected function readObj(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly || $this->version != self::XLS_BIFF8) { return; } // recordData consists of an array of subrecords looking like this: // ft: 2 bytes; ftCmo type (0x15) // cb: 2 bytes; size in bytes of ftCmo data // ot: 2 bytes; Object Type // id: 2 bytes; Object id number // grbit: 2 bytes; Option Flags // data: var; subrecord data // for now, we are just interested in the second subrecord containing the object type $ftCmoType = self::getUInt2d($recordData, 0); $cbCmoSize = self::getUInt2d($recordData, 2); $otObjType = self::getUInt2d($recordData, 4); $idObjID = self::getUInt2d($recordData, 6); $grbitOpts = self::getUInt2d($recordData, 6); $this->objs[] = [ 'ftCmoType' => $ftCmoType, 'cbCmoSize' => $cbCmoSize, 'otObjType' => $otObjType, 'idObjID' => $idObjID, 'grbitOpts' => $grbitOpts, ]; $this->textObjRef = $idObjID; } /** * Read WINDOW2 record. */ protected function readWindow2(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; option flags $options = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to first visible row //$firstVisibleRow = self::getUInt2d($recordData, 2); // offset: 4; size: 2; index to first visible colum //$firstVisibleColumn = self::getUInt2d($recordData, 4); $zoomscaleInPageBreakPreview = 0; $zoomscaleInNormalView = 0; if ($this->version === self::XLS_BIFF8) { // offset: 8; size: 2; not used // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%) // offset: 14; size: 4; not used if (!isset($recordData[10])) { $zoomscaleInPageBreakPreview = 0; } else { $zoomscaleInPageBreakPreview = self::getUInt2d($recordData, 10); } if ($zoomscaleInPageBreakPreview === 0) { $zoomscaleInPageBreakPreview = 60; } if (!isset($recordData[12])) { $zoomscaleInNormalView = 0; } else { $zoomscaleInNormalView = self::getUInt2d($recordData, 12); } if ($zoomscaleInNormalView === 0) { $zoomscaleInNormalView = 100; } } // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines $showGridlines = (bool) ((0x0002 & $options) >> 1); $this->phpSheet->setShowGridlines($showGridlines); // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers $showRowColHeaders = (bool) ((0x0004 & $options) >> 2); $this->phpSheet->setShowRowColHeaders($showRowColHeaders); // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen $this->frozen = (bool) ((0x0008 & $options) >> 3); // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left $this->phpSheet->setRightToLeft((bool) ((0x0040 & $options) >> 6)); // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active $isActive = (bool) ((0x0400 & $options) >> 10); if ($isActive) { $this->spreadsheet->setActiveSheetIndex($this->spreadsheet->getIndex($this->phpSheet)); $this->activeSheetSet = true; } // bit: 11; mask: 0x0800; 0 = normal view, 1 = page break view $isPageBreakPreview = (bool) ((0x0800 & $options) >> 11); //FIXME: set $firstVisibleRow and $firstVisibleColumn if ($this->phpSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_PAGE_LAYOUT) { //NOTE: this setting is inferior to page layout view(Excel2007-) $view = $isPageBreakPreview ? SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW : SheetView::SHEETVIEW_NORMAL; $this->phpSheet->getSheetView()->setView($view); if ($this->version === self::XLS_BIFF8) { $zoomScale = $isPageBreakPreview ? $zoomscaleInPageBreakPreview : $zoomscaleInNormalView; $this->phpSheet->getSheetView()->setZoomScale($zoomScale); $this->phpSheet->getSheetView()->setZoomScaleNormal($zoomscaleInNormalView); } } } /** * Read PLV Record(Created by Excel2007 or upper). */ protected function readPageLayoutView(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; rt //->ignore //$rt = self::getUInt2d($recordData, 0); // offset: 2; size: 2; grbitfr //->ignore //$grbitFrt = self::getUInt2d($recordData, 2); // offset: 4; size: 8; reserved //->ignore // offset: 12; size 2; zoom scale $wScalePLV = self::getUInt2d($recordData, 12); // offset: 14; size 2; grbit $grbit = self::getUInt2d($recordData, 14); // decomprise grbit $fPageLayoutView = $grbit & 0x01; //$fRulerVisible = ($grbit >> 1) & 0x01; //no support //$fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support if ($fPageLayoutView === 1) { $this->phpSheet->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_LAYOUT); $this->phpSheet->getSheetView()->setZoomScale($wScalePLV); //set by Excel2007 only if SHEETVIEW_PAGE_LAYOUT } //otherwise, we cannot know whether SHEETVIEW_PAGE_LAYOUT or SHEETVIEW_PAGE_BREAK_PREVIEW. } /** * Read SCL record. */ protected function readScl(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; numerator of the view magnification $numerator = self::getUInt2d($recordData, 0); // offset: 2; size: 2; numerator of the view magnification $denumerator = self::getUInt2d($recordData, 2); // set the zoom scale (in percent) $this->phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator); } /** * Read PANE record. */ protected function readPane(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; position of vertical split $px = self::getUInt2d($recordData, 0); // offset: 2; size: 2; position of horizontal split $py = self::getUInt2d($recordData, 2); // offset: 4; size: 2; top most visible row in the bottom pane $rwTop = self::getUInt2d($recordData, 4); // offset: 6; size: 2; first visible left column in the right pane $colLeft = self::getUInt2d($recordData, 6); if ($this->frozen) { // frozen panes $cell = Coordinate::stringFromColumnIndex($px + 1) . ($py + 1); $topLeftCell = Coordinate::stringFromColumnIndex($colLeft + 1) . ($rwTop + 1); $this->phpSheet->freezePane($cell, $topLeftCell); } // unfrozen panes; split windows; not supported by PhpSpreadsheet core } } private const REGEX_WHOLE_COLUMN = '/^([A-Z]+1\:[A-Z]+)' . '(' . AddressRange::MAX_ROW_XLS_OLD . '|' . AddressRange::MAX_ROW_XLS . ')' . '$/'; private const REGEX_WHOLE_COLUMN_REPLACE = '${1}' . AddressRange::MAX_ROW; private const REGEX_WHOLE_ROW = '/^(A\d+\:)' . AddressRange::MAX_COLUMN_XLS . '(\d+)$/'; private const REGEX_WHOLE_ROW_REPLACE = '${1}' . AddressRange::MAX_COLUMN . '${2}'; /** * Read SELECTION record. There is one such record for each pane in the sheet. */ protected function readSelection(): string { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); $selectedCells = ''; // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 1; pane identifier //$paneId = ord($recordData[0]); // offset: 1; size: 2; index to row of the active cell //$r = self::getUInt2d($recordData, 1); // offset: 3; size: 2; index to column of the active cell //$c = self::getUInt2d($recordData, 3); // offset: 5; size: 2; index into the following cell range list to the // entry that contains the active cell //$index = self::getUInt2d($recordData, 5); // offset: 7; size: var; cell range address list containing all selected cell ranges $data = substr($recordData, 7); $cellRangeAddressList = Xls\Biff5::readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0]; // first row '1' + last row '16384' or '65536' indicates that full column is selected (apparently also in BIFF8!) if (Preg::isMatch(self::REGEX_WHOLE_COLUMN, $selectedCells)) { $selectedCells = Preg::replace(self::REGEX_WHOLE_COLUMN, self::REGEX_WHOLE_COLUMN_REPLACE, $selectedCells); } // first column 'A' + last column 'IV' indicates that full row is selected if (Preg::isMatch(self::REGEX_WHOLE_ROW, $selectedCells)) { $selectedCells = Preg::replace(self::REGEX_WHOLE_ROW, self::REGEX_WHOLE_ROW_REPLACE, $selectedCells); } $this->phpSheet->setSelectedCells($selectedCells); } return $selectedCells; } private function includeCellRangeFiltered(string $cellRangeAddress): bool { $includeCellRange = false; $rangeBoundaries = Coordinate::getRangeBoundaries($cellRangeAddress); StringHelper::stringIncrement($rangeBoundaries[1][0]); for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; ++$row) { for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; StringHelper::stringIncrement($column)) { if ($this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) { $includeCellRange = true; break 2; } } } return $includeCellRange; } /** * MERGEDCELLS. * * This record contains the addresses of merged cell ranges * in the current sheet. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ protected function readMergedCells(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { $cellRangeAddressList = Xls\Biff8::readBIFF8CellRangeAddressList($recordData); foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) { /** @var string $cellRangeAddress */ if ( (str_contains($cellRangeAddress, ':')) && ($this->includeCellRangeFiltered($cellRangeAddress)) ) { $this->phpSheet->mergeCells($cellRangeAddress, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } } /** * Read HYPERLINK record. */ protected function readHyperLink(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8; cell range address of all cells containing this hyperlink try { $cellRange = Xls\Biff8::readBIFF8CellRangeAddressFixed($recordData); } catch (PhpSpreadsheetException) { return; } // offset: 8, size: 16; GUID of StdLink // offset: 24, size: 4; unknown value // offset: 28, size: 4; option flags // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL $isFileLinkOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 0; // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL //$isAbsPathOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 1; // bit: 2 (and 4); mask: 0x00000014; 0 = no description $hasDesc = (0x00000014 & self::getUInt2d($recordData, 28)) >> 2; // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text $hasText = (0x00000008 & self::getUInt2d($recordData, 28)) >> 3; // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame $hasFrame = (0x00000080 & self::getUInt2d($recordData, 28)) >> 7; // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name) $isUNC = (0x00000100 & self::getUInt2d($recordData, 28)) >> 8; // offset within record data $offset = 32; if ($hasDesc) { // offset: 32; size: var; character count of description text $dl = self::getInt4d($recordData, 32); // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated //$desc = self::encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false); $offset += 4 + 2 * $dl; } if ($hasFrame) { $fl = self::getInt4d($recordData, $offset); $offset += 4 + 2 * $fl; } // detect type of hyperlink (there are 4 types) $hyperlinkType = null; if ($isUNC) { $hyperlinkType = 'UNC'; } elseif (!$isFileLinkOrUrl) { $hyperlinkType = 'workbook'; } elseif (ord($recordData[$offset]) == 0x03) { $hyperlinkType = 'local'; } elseif (ord($recordData[$offset]) == 0xE0) { $hyperlinkType = 'URL'; } switch ($hyperlinkType) { case 'URL': // section 5.58.2: Hyperlink containing a URL // e.g. http://example.org/index.php // offset: var; size: 16; GUID of URL Moniker $offset += 16; // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word $us = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated $url = self::encodeUTF16(substr($recordData, $offset, $us - 2), false); $nullOffset = strpos($url, chr(0x00)); if ($nullOffset) { $url = substr($url, 0, $nullOffset); } $url .= $hasText ? '#' : ''; $offset += $us; break; case 'local': // section 5.58.3: Hyperlink to local file // examples: // mydoc.txt // ../../somedoc.xls#Sheet!A1 // offset: var; size: 16; GUI of File Moniker $offset += 16; // offset: var; size: 2; directory up-level count. $upLevelCount = self::getUInt2d($recordData, $offset); $offset += 2; // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word $sl = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string) $shortenedFilePath = substr($recordData, $offset, $sl); $shortenedFilePath = self::encodeUTF16($shortenedFilePath, true); $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero $offset += $sl; // offset: var; size: 24; unknown sequence $offset += 24; // extended file path // offset: var; size: 4; size of the following file link field including string lenth mark $sz = self::getInt4d($recordData, $offset); $offset += 4; $extendedFilePath = ''; // only present if $sz > 0 if ($sz > 0) { // offset: var; size: 4; size of the character array of the extended file path and name $xl = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size 2; unknown $offset += 2; // offset: var; size $xl; character array of the extended file path and name. $extendedFilePath = substr($recordData, $offset, $xl); $extendedFilePath = self::encodeUTF16($extendedFilePath, false); $offset += $xl; } // construct the path $url = str_repeat('..\\', $upLevelCount); $url .= ($sz > 0) ? $extendedFilePath : $shortenedFilePath; // use extended path if available $url .= $hasText ? '#' : ''; break; case 'UNC': // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path // todo: implement return; case 'workbook': // section 5.58.5: Hyperlink to the Current Workbook // e.g. Sheet2!B1:C2, stored in text mark field $url = 'sheet://'; break; default: return; } if ($hasText) { // offset: var; size: 4; character count of text mark including trailing zero word $tl = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated $text = self::encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false); $url .= $text; } // apply the hyperlink to all the relevant cells foreach (Coordinate::extractAllCellReferencesInRange($cellRange) as $coordinate) { $this->phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url); } } } /** * Read DATAVALIDATIONS record. */ protected function readDataValidations(): void { $length = self::getUInt2d($this->data, $this->pos + 2); //$recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; } /** * Read DATAVALIDATION record. */ protected function readDataValidation(): void { (new Xls\DataValidationHelper())->readDataValidation2($this); } /** * Read SHEETLAYOUT record. Stores sheet tab color information. */ protected function readSheetLayout(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; repeated record identifier 0x0862 // offset: 2; size: 10; not used // offset: 12; size: 4; size of record data // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?) $sz = self::getInt4d($recordData, 12); switch ($sz) { case 0x14: // offset: 16; size: 2; color index for sheet tab $colorIndex = self::getUInt2d($recordData, 16); /** @var string[] */ $color = Xls\Color::map($colorIndex, $this->palette, $this->version); $this->phpSheet->getTabColor()->setRGB($color['rgb']); break; case 0x28: // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007 return; } } } /** * Read SHEETPROTECTION record (FEATHEADR). */ protected function readSheetProtection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; repeated record header // offset: 2; size: 2; FRT cell reference flag (=0 currently) // offset: 4; size: 8; Currently not used and set to 0 // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag) $isf = self::getUInt2d($recordData, 12); if ($isf != 2) { return; } // offset: 14; size: 1; =1 since this is a feat header // offset: 15; size: 4; size of rgbHdrSData // rgbHdrSData, assume "Enhanced Protection" // offset: 19; size: 2; option flags $options = self::getUInt2d($recordData, 19); // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects // Note - do not negate $bool $bool = (0x0001 & $options) >> 0; $this->phpSheet->getProtection()->setObjects((bool) $bool); // bit: 1; mask 0x0002; edit scenarios // Note - do not negate $bool $bool = (0x0002 & $options) >> 1; $this->phpSheet->getProtection()->setScenarios((bool) $bool); // bit: 2; mask 0x0004; format cells $bool = (0x0004 & $options) >> 2; $this->phpSheet->getProtection()->setFormatCells(!$bool); // bit: 3; mask 0x0008; format columns $bool = (0x0008 & $options) >> 3; $this->phpSheet->getProtection()->setFormatColumns(!$bool); // bit: 4; mask 0x0010; format rows $bool = (0x0010 & $options) >> 4; $this->phpSheet->getProtection()->setFormatRows(!$bool); // bit: 5; mask 0x0020; insert columns $bool = (0x0020 & $options) >> 5; $this->phpSheet->getProtection()->setInsertColumns(!$bool); // bit: 6; mask 0x0040; insert rows $bool = (0x0040 & $options) >> 6; $this->phpSheet->getProtection()->setInsertRows(!$bool); // bit: 7; mask 0x0080; insert hyperlinks $bool = (0x0080 & $options) >> 7; $this->phpSheet->getProtection()->setInsertHyperlinks(!$bool); // bit: 8; mask 0x0100; delete columns $bool = (0x0100 & $options) >> 8; $this->phpSheet->getProtection()->setDeleteColumns(!$bool); // bit: 9; mask 0x0200; delete rows $bool = (0x0200 & $options) >> 9; $this->phpSheet->getProtection()->setDeleteRows(!$bool); // bit: 10; mask 0x0400; select locked cells // Note that this is opposite of most of above. $bool = (0x0400 & $options) >> 10; $this->phpSheet->getProtection()->setSelectLockedCells((bool) $bool); // bit: 11; mask 0x0800; sort cell range $bool = (0x0800 & $options) >> 11; $this->phpSheet->getProtection()->setSort(!$bool); // bit: 12; mask 0x1000; auto filter $bool = (0x1000 & $options) >> 12; $this->phpSheet->getProtection()->setAutoFilter(!$bool); // bit: 13; mask 0x2000; pivot tables $bool = (0x2000 & $options) >> 13; $this->phpSheet->getProtection()->setPivotTables(!$bool); // bit: 14; mask 0x4000; select unlocked cells // Note that this is opposite of most of above. $bool = (0x4000 & $options) >> 14; $this->phpSheet->getProtection()->setSelectUnlockedCells((bool) $bool); // offset: 21; size: 2; not used } /** * Read RANGEPROTECTION record * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification, * where it is referred to as FEAT record. */ protected function readRangeProtection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // local pointer in record data $offset = 0; if (!$this->readDataOnly) { $offset += 12; // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag $isf = self::getUInt2d($recordData, 12); if ($isf != 2) { // we only read FEAT records of type 2 return; } $offset += 2; $offset += 5; // offset: 19; size: 2; count of ref ranges this feature is on $cref = self::getUInt2d($recordData, 19); $offset += 2; $offset += 6; // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record) $cellRanges = []; for ($i = 0; $i < $cref; ++$i) { try { $cellRange = Xls\Biff8::readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8)); } catch (PhpSpreadsheetException) { return; } $cellRanges[] = $cellRange; $offset += 8; } // offset: var; size: var; variable length of feature specific data //$rgbFeat = substr($recordData, $offset); $offset += 4; // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit) $wPassword = self::getInt4d($recordData, $offset); $offset += 4; // Apply range protection to sheet if ($cellRanges) { $this->phpSheet->protectCells(implode(' ', $cellRanges), ($wPassword === 0) ? '' : strtoupper(dechex($wPassword)), true); } } } /** * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented. * In this case, we must treat the CONTINUE record as a MSODRAWING record. */ protected function readContinue(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // check if we are reading drawing data // this is in case a free CONTINUE record occurs in other circumstances we are unaware of if ($this->drawingData == '') { // move stream pointer to next record $this->pos += 4 + $length; return; } // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data if ($length < 4) { // move stream pointer to next record $this->pos += 4 + $length; return; } // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record // look inside CONTINUE record to see if it looks like a part of an Escher stream // we know that Escher stream may be split at least at // 0xF003 MsofbtSpgrContainer // 0xF004 MsofbtSpContainer // 0xF00D MsofbtClientTextbox $validSplitPoints = [0xF003, 0xF004, 0xF00D]; // add identifiers if we find more $splitPoint = self::getUInt2d($recordData, 2); if (in_array($splitPoint, $validSplitPoints)) { // get spliced record data (and move pointer to next record) $splicedRecordData = $this->getSplicedRecordData(); $this->drawingData .= StringHelper::convertToString($splicedRecordData['recordData']); return; } // move stream pointer to next record $this->pos += 4 + $length; } /** * Reads a record from current position in data stream and continues reading data as long as CONTINUE * records are found. Splices the record data pieces and returns the combined string as if record data * is in one piece. * Moves to next current position in data stream to start of next record different from a CONtINUE record. * * @return mixed[] */ private function getSplicedRecordData(): array { $data = ''; $spliceOffsets = []; $i = 0; $spliceOffsets[0] = 0; do { ++$i; // offset: 0; size: 2; identifier //$identifier = self::getUInt2d($this->data, $this->pos); // offset: 2; size: 2; length $length = self::getUInt2d($this->data, $this->pos + 2); $data .= $this->readRecordData($this->data, $this->pos + 4, $length); $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length; $this->pos += 4 + $length; $nextIdentifier = self::getUInt2d($this->data, $this->pos); } while ($nextIdentifier == self::XLS_TYPE_CONTINUE); return [ 'recordData' => $data, 'spliceOffsets' => $spliceOffsets, ]; } /** * Convert formula structure into human readable Excel formula like 'A3+A5*5'. * * @param string $formulaStructure The complete binary data for the formula * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas * * @return string Human readable formula */ protected function getFormulaFromStructure(string $formulaStructure, string $baseCell = 'A1'): string { // offset: 0; size: 2; size of the following formula data $sz = self::getUInt2d($formulaStructure, 0); // offset: 2; size: sz $formulaData = substr($formulaStructure, 2, $sz); // offset: 2 + sz; size: variable (optional) if (strlen($formulaStructure) > 2 + $sz) { $additionalData = substr($formulaStructure, 2 + $sz); } else { $additionalData = ''; } return $this->getFormulaFromData($formulaData, $additionalData, $baseCell); } /** * Take formula data and additional data for formula and return human readable formula. * * @param string $formulaData The binary data for the formula itself * @param string $additionalData Additional binary data going with the formula * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas * * @return string Human readable formula */ private function getFormulaFromData(string $formulaData, string $additionalData = '', string $baseCell = 'A1'): string { // start parsing the formula data $tokens = []; while ($formulaData !== '' && $token = $this->getNextToken($formulaData, $baseCell)) { $tokens[] = $token; /** @var int[] $token */ $formulaData = substr($formulaData, $token['size']); } $formulaString = $this->createFormulaFromTokens($tokens, $additionalData); return $formulaString; } /** * Take array of tokens together with additional data for formula and return human readable formula. * * @param mixed[][] $tokens * @param string $additionalData Additional binary data going with the formula * * @return string Human readable formula */ private function createFormulaFromTokens(array $tokens, string $additionalData): string { // empty formula? if (empty($tokens)) { return ''; } $formulaStrings = []; foreach ($tokens as $token) { // initialize spaces $space0 = $space0 ?? ''; // spaces before next token, not tParen $space1 = $space1 ?? ''; // carriage returns before next token, not tParen $space2 = $space2 ?? ''; // spaces before opening parenthesis $space3 = $space3 ?? ''; // carriage returns before opening parenthesis $space4 = $space4 ?? ''; // spaces before closing parenthesis $space5 = $space5 ?? ''; // carriage returns before closing parenthesis /** @var string */ $tokenData = $token['data'] ?? ''; switch ($token['name']) { case 'tAdd': // addition case 'tConcat': // addition case 'tDiv': // division case 'tEQ': // equality case 'tGE': // greater than or equal case 'tGT': // greater than case 'tIsect': // intersection case 'tLE': // less than or equal case 'tList': // less than or equal case 'tLT': // less than case 'tMul': // multiplication case 'tNE': // multiplication case 'tPower': // power case 'tRange': // range case 'tSub': // subtraction $op2 = array_pop($formulaStrings); $op1 = array_pop($formulaStrings); $formulaStrings[] = "$op1$space1$space0{$tokenData}$op2"; unset($space0, $space1); break; case 'tUplus': // unary plus case 'tUminus': // unary minus $op = array_pop($formulaStrings); $formulaStrings[] = "$space1$space0{$tokenData}$op"; unset($space0, $space1); break; case 'tPercent': // percent sign $op = array_pop($formulaStrings); $formulaStrings[] = "$op$space1$space0{$tokenData}"; unset($space0, $space1); break; case 'tAttrVolatile': // indicates volatile function case 'tAttrIf': case 'tAttrSkip': case 'tAttrChoose': // token is only important for Excel formula evaluator // do nothing break; case 'tAttrSpace': // space / carriage return // space will be used when next token arrives, do not alter formulaString stack /** @var string[][] $token */ switch ($token['data']['spacetype']) { case 'type0': $space0 = str_repeat(' ', (int) $token['data']['spacecount']); break; case 'type1': $space1 = str_repeat("\n", (int) $token['data']['spacecount']); break; case 'type2': $space2 = str_repeat(' ', (int) $token['data']['spacecount']); break; case 'type3': $space3 = str_repeat("\n", (int) $token['data']['spacecount']); break; case 'type4': $space4 = str_repeat(' ', (int) $token['data']['spacecount']); break; case 'type5': $space5 = str_repeat("\n", (int) $token['data']['spacecount']); break; } break; case 'tAttrSum': // SUM function with one parameter $op = array_pop($formulaStrings); $formulaStrings[] = "{$space1}{$space0}SUM($op)"; unset($space0, $space1); break; case 'tFunc': // function with fixed number of arguments case 'tFuncV': // function with variable number of arguments /** @var string[] */ $temp1 = $token['data']; $temp2 = $temp1['function']; if ($temp2 != '') { // normal function $ops = []; // array of operators $temp3 = (int) $temp1['args']; for ($i = 0; $i < $temp3; ++$i) { $ops[] = array_pop($formulaStrings); } $ops = array_reverse($ops); $formulaStrings[] = "$space1$space0{$temp2}(" . implode(',', $ops) . ')'; unset($space0, $space1); } else { // add-in function $ops = []; // array of operators /** @var int[] */ $temp = $token['data']; for ($i = 0; $i < $temp['args'] - 1; ++$i) { $ops[] = array_pop($formulaStrings); } $ops = array_reverse($ops); $function = array_pop($formulaStrings); $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ')'; unset($space0, $space1); } break; case 'tParen': // parenthesis $expression = array_pop($formulaStrings); $formulaStrings[] = "$space3$space2($expression$space5$space4)"; unset($space2, $space3, $space4, $space5); break; case 'tArray': // array constant $constantArray = Xls\Biff8::readBIFF8ConstantArray($additionalData); $formulaStrings[] = $space1 . $space0 . $constantArray['value']; $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data unset($space0, $space1); break; case 'tMemArea': // bite off chunk of additional data $cellRangeAddressList = Xls\Biff8::readBIFF8CellRangeAddressList($additionalData); $additionalData = substr($additionalData, $cellRangeAddressList['size']); $formulaStrings[] = "$space1$space0{$tokenData}"; unset($space0, $space1); break; case 'tArea': // cell range address case 'tBool': // boolean case 'tErr': // error code case 'tInt': // integer case 'tMemErr': case 'tMemFunc': case 'tMissArg': case 'tName': case 'tNameX': case 'tNum': // number case 'tRef': // single cell reference case 'tRef3d': // 3d cell reference case 'tArea3d': // 3d cell range reference case 'tRefN': case 'tAreaN': case 'tStr': // string $formulaStrings[] = "$space1$space0{$tokenData}"; unset($space0, $space1); break; } } $formulaString = $formulaStrings[0]; return $formulaString; } /** * Fetch next token from binary formula data. * * @param string $formulaData Formula data * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas * * @return mixed[] */ private function getNextToken(string $formulaData, string $baseCell = 'A1'): array { // offset: 0; size: 1; token id $id = ord($formulaData[0]); // token id $name = false; // initialize token name switch ($id) { case 0x03: $name = 'tAdd'; $size = 1; $data = '+'; break; case 0x04: $name = 'tSub'; $size = 1; $data = '-'; break; case 0x05: $name = 'tMul'; $size = 1; $data = '*'; break; case 0x06: $name = 'tDiv'; $size = 1; $data = '/'; break; case 0x07: $name = 'tPower'; $size = 1; $data = '^'; break; case 0x08: $name = 'tConcat'; $size = 1; $data = '&'; break; case 0x09: $name = 'tLT'; $size = 1; $data = '<'; break; case 0x0A: $name = 'tLE'; $size = 1; $data = '<='; break; case 0x0B: $name = 'tEQ'; $size = 1; $data = '='; break; case 0x0C: $name = 'tGE'; $size = 1; $data = '>='; break; case 0x0D: $name = 'tGT'; $size = 1; $data = '>'; break; case 0x0E: $name = 'tNE'; $size = 1; $data = '<>'; break; case 0x0F: $name = 'tIsect'; $size = 1; $data = ' '; break; case 0x10: $name = 'tList'; $size = 1; $data = ','; break; case 0x11: $name = 'tRange'; $size = 1; $data = ':'; break; case 0x12: $name = 'tUplus'; $size = 1; $data = '+'; break; case 0x13: $name = 'tUminus'; $size = 1; $data = '-'; break; case 0x14: $name = 'tPercent'; $size = 1; $data = '%'; break; case 0x15: // parenthesis $name = 'tParen'; $size = 1; $data = null; break; case 0x16: // missing argument $name = 'tMissArg'; $size = 1; $data = ''; break; case 0x17: // string $name = 'tStr'; // offset: 1; size: var; Unicode string, 8-bit string length $string = self::readUnicodeStringShort(substr($formulaData, 1)); $size = 1 + $string['size']; $data = self::UTF8toExcelDoubleQuoted($string['value']); break; case 0x19: // Special attribute // offset: 1; size: 1; attribute type flags: switch (ord($formulaData[1])) { case 0x01: $name = 'tAttrVolatile'; $size = 4; $data = null; break; case 0x02: $name = 'tAttrIf'; $size = 4; $data = null; break; case 0x04: $name = 'tAttrChoose'; // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1) $nc = self::getUInt2d($formulaData, 2); // offset: 4; size: 2 * $nc // offset: 4 + 2 * $nc; size: 2 $size = 2 * $nc + 6; $data = null; break; case 0x08: $name = 'tAttrSkip'; $size = 4; $data = null; break; case 0x10: $name = 'tAttrSum'; $size = 4; $data = null; break; case 0x40: case 0x41: $name = 'tAttrSpace'; $size = 4; // offset: 2; size: 2; space type and position $spacetype = match (ord($formulaData[2])) { 0x00 => 'type0', 0x01 => 'type1', 0x02 => 'type2', 0x03 => 'type3', 0x04 => 'type4', 0x05 => 'type5', default => throw new Exception('Unrecognized space type in tAttrSpace token'), }; // offset: 3; size: 1; number of inserted spaces/carriage returns $spacecount = ord($formulaData[3]); $data = ['spacetype' => $spacetype, 'spacecount' => $spacecount]; break; default: throw new Exception('Unrecognized attribute flag in tAttr token'); } break; case 0x1C: // error code // offset: 1; size: 1; error code $name = 'tErr'; $size = 2; $data = Xls\ErrorCode::lookup(ord($formulaData[1])); break; case 0x1D: // boolean // offset: 1; size: 1; 0 = false, 1 = true; $name = 'tBool'; $size = 2; $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE'; break; case 0x1E: // integer // offset: 1; size: 2; unsigned 16-bit integer $name = 'tInt'; $size = 3; $data = self::getUInt2d($formulaData, 1); break; case 0x1F: // number // offset: 1; size: 8; $name = 'tNum'; $size = 9; $data = self::extractNumber(substr($formulaData, 1)); $data = str_replace(',', '.', (string) $data); // in case non-English locale break; case 0x20: // array constant case 0x40: case 0x60: // offset: 1; size: 7; not used $name = 'tArray'; $size = 8; $data = null; break; case 0x21: // function with fixed number of arguments case 0x41: case 0x61: $name = 'tFunc'; $size = 3; // offset: 1; size: 2; index to built-in sheet function $mapping = Xls\Mappings::TFUNC_MAPPINGS[self::getUInt2d($formulaData, 1)] ?? null; if ($mapping === null) { throw new Exception('Unrecognized function in formula'); } $data = ['function' => $mapping[0], 'args' => $mapping[1]]; break; case 0x22: // function with variable number of arguments case 0x42: case 0x62: $name = 'tFuncV'; $size = 4; // offset: 1; size: 1; number of arguments $args = ord($formulaData[1]); // offset: 2: size: 2; index to built-in sheet function $index = self::getUInt2d($formulaData, 2); $function = Xls\Mappings::TFUNCV_MAPPINGS[$index] ?? null; if ($function === null) { throw new Exception('Unrecognized function in formula'); } $data = ['function' => $function, 'args' => $args]; break; case 0x23: // index to defined name case 0x43: case 0x63: $name = 'tName'; $size = 5; // offset: 1; size: 2; one-based index to definedname record $definedNameIndex = self::getUInt2d($formulaData, 1) - 1; // offset: 2; size: 2; not used /** @var string[] */ $data = $this->definedname[$definedNameIndex]['name'] ?? ''; //* @phpstan-ignore-line break; case 0x24: // single cell reference e.g. A5 case 0x44: case 0x64: $name = 'tRef'; $size = 5; $data = Xls\Biff8::readBIFF8CellAddress(substr($formulaData, 1, 4)); break; case 0x25: // cell range reference to cells in the same sheet (2d) case 0x45: case 0x65: $name = 'tArea'; $size = 9; $data = Xls\Biff8::readBIFF8CellRangeAddress(substr($formulaData, 1, 8)); break; case 0x26: // Constant reference sub-expression case 0x46: case 0x66: $name = 'tMemArea'; // offset: 1; size: 4; not used // offset: 5; size: 2; size of the following subexpression $subSize = self::getUInt2d($formulaData, 5); $size = 7 + $subSize; $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize)); break; case 0x27: // Deleted constant reference sub-expression case 0x47: case 0x67: $name = 'tMemErr'; // offset: 1; size: 4; not used // offset: 5; size: 2; size of the following subexpression $subSize = self::getUInt2d($formulaData, 5); $size = 7 + $subSize; $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize)); break; case 0x29: // Variable reference sub-expression case 0x49: case 0x69: $name = 'tMemFunc'; // offset: 1; size: 2; size of the following sub-expression $subSize = self::getUInt2d($formulaData, 1); $size = 3 + $subSize; $data = $this->getFormulaFromData(substr($formulaData, 3, $subSize)); break; case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places case 0x4C: case 0x6C: $name = 'tRefN'; $size = 5; $data = Xls\Biff8::readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell); break; case 0x2D: // Relative 2d range reference case 0x4D: case 0x6D: $name = 'tAreaN'; $size = 9; $data = Xls\Biff8::readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell); break; case 0x39: // External name case 0x59: case 0x79: $name = 'tNameX'; $size = 7; // offset: 1; size: 2; index to REF entry in EXTERNSHEET record // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record $index = self::getUInt2d($formulaData, 3); // assume index is to EXTERNNAME record $data = $this->externalNames[$index - 1]['name'] ?? ''; // offset: 5; size: 2; not used break; case 0x3A: // 3d reference to cell case 0x5A: case 0x7A: $name = 'tRef3d'; $size = 7; try { // offset: 1; size: 2; index to REF entry $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1)); // offset: 3; size: 4; cell address $cellAddress = Xls\Biff8::readBIFF8CellAddress(substr($formulaData, 3, 4)); $data = "$sheetRange!$cellAddress"; } catch (PhpSpreadsheetException) { // deleted sheet reference $data = '#REF!'; } break; case 0x3B: // 3d reference to cell range case 0x5B: case 0x7B: $name = 'tArea3d'; $size = 11; try { // offset: 1; size: 2; index to REF entry $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1)); // offset: 3; size: 8; cell address $cellRangeAddress = Xls\Biff8::readBIFF8CellRangeAddress(substr($formulaData, 3, 8)); $data = "$sheetRange!$cellRangeAddress"; } catch (PhpSpreadsheetException) { // deleted sheet reference $data = '#REF!'; } break; // Unknown cases // don't know how to deal with default: throw new Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula'); } return [ 'id' => $id, 'name' => $name, 'size' => $size, 'data' => $data, ]; } /** * Get a sheet range like Sheet1:Sheet3 from REF index * Note: If there is only one sheet in the range, one gets e.g Sheet1 * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets, * in which case an Exception is thrown. */ protected function readSheetRangeByRefIndex(int $index): string|false { if (isset($this->ref[$index])) { $type = $this->externalBooks[$this->ref[$index]['externalBookIndex']]['type']; switch ($type) { case 'internal': // check if we have a deleted 3d reference if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF || $this->ref[$index]['lastSheetIndex'] == 0xFFFF) { throw new Exception('Deleted sheet reference'); } // we have normal sheet range (collapsed or uncollapsed) $firstSheetName = $this->sheets[$this->ref[$index]['firstSheetIndex']]['name']; $lastSheetName = $this->sheets[$this->ref[$index]['lastSheetIndex']]['name']; if ($firstSheetName == $lastSheetName) { // collapsed sheet range $sheetRange = $firstSheetName; } else { $sheetRange = "$firstSheetName:$lastSheetName"; } // escape the single-quotes $sheetRange = str_replace("'", "''", $sheetRange); // if there are special characters, we need to enclose the range in single-quotes // todo: check if we have identified the whole set of special characters // it seems that the following characters are not accepted for sheet names // and we may assume that they are not present: []*/:\? // 'u' qualifier makes it risky to use Preg::isMatch here if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/u", $sheetRange)) { $sheetRange = "'$sheetRange'"; } return $sheetRange; default: // TODO: external sheet support throw new Exception('Xls reader only supports internal sheets in formulas'); } } return false; } /** * Read byte string (8-bit string length) * OpenOffice documentation: 2.5.2. * * @return array{value: mixed, size: int} */ protected function readByteStringShort(string $subData): array { // offset: 0; size: 1; length of the string (character count) $ln = ord($subData[0]); // offset: 1: size: var; character array (8-bit characters) $value = $this->decodeCodepage(substr($subData, 1, $ln)); return [ 'value' => $value, 'size' => 1 + $ln, // size in bytes of data structure ]; } /** * Read byte string (16-bit string length) * OpenOffice documentation: 2.5.2. * * @return array{value: mixed, size: int} */ protected function readByteStringLong(string $subData): array { // offset: 0; size: 2; length of the string (character count) $ln = self::getUInt2d($subData, 0); // offset: 2: size: var; character array (8-bit characters) $value = $this->decodeCodepage(substr($subData, 2)); //return $string; return [ 'value' => $value, 'size' => 2 + $ln, // size in bytes of data structure ]; } protected function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } /** * Phpstan 1.4.4 complains that this property is never read. * So, we might be able to get rid of it altogether. * For now, however, this function makes it readable, * which satisfies Phpstan. * * @return mixed[] * * @codeCoverageIgnore */ public function getMapCellStyleXfIndex(): array { return $this->mapCellStyleXfIndex; } /** * Parse conditional formatting blocks. * * @see https://www.openoffice.org/sc/excelfileformat.pdf Search for CFHEADER followed by CFRULE * * @return mixed[] */ protected function readCFHeader(): array { return (new Xls\ConditionalFormatting())->readCFHeader2($this); } /** @param string[] $cellRangeAddresses */ protected function readCFRule(array $cellRangeAddresses): void { (new Xls\ConditionalFormatting())->readCFRule2($cellRangeAddresses, $this); } public function getVersion(): int { return $this->version; } } ================================================ FILE: src/PhpSpreadsheet/Reader/XlsBase.php ================================================ 0x00, Border::BORDER_THIN, // => 0x01, Border::BORDER_MEDIUM, // => 0x02, Border::BORDER_DASHED, // => 0x03, Border::BORDER_DOTTED, // => 0x04, Border::BORDER_THICK, // => 0x05, Border::BORDER_DOUBLE, // => 0x06, Border::BORDER_HAIR, // => 0x07, Border::BORDER_MEDIUMDASHED, // => 0x08, Border::BORDER_DASHDOT, // => 0x09, Border::BORDER_MEDIUMDASHDOT, // => 0x0A, Border::BORDER_DASHDOTDOT, // => 0x0B, Border::BORDER_MEDIUMDASHDOTDOT, // => 0x0C, Border::BORDER_SLANTDASHDOT, // => 0x0D, Border::BORDER_OMIT, // => 0x0E, Border::BORDER_OMIT, // => 0x0F, ]; /** * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95) * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE'. */ protected string $codepage = ''; public function setCodepage(string $codepage): void { if (CodePage::validate($codepage) === false) { throw new PhpSpreadsheetException('Unknown codepage: ' . $codepage); } $this->codepage = $codepage; } public function getCodepage(): string { return $this->codepage; } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { if (File::testFileNoThrow($filename) === false) { return false; } try { // Use ParseXL for the hard work. $ole = new OLERead(); // get excel data $ole->read($filename); if ($ole->wrkbook === null) { throw new Exception('The filename ' . $filename . ' is not recognised as a Spreadsheet file'); } return true; } catch (PhpSpreadsheetException) { return false; } } /** * Extract RGB color * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4. * * @param string $rgb Encoded RGB value (4 bytes) * * @return array{rgb: string} */ protected static function readRGB(string $rgb): array { // offset: 0; size 1; Red component $r = ord($rgb[0]); // offset: 1; size: 1; Green component $g = ord($rgb[1]); // offset: 2; size: 1; Blue component $b = ord($rgb[2]); // HEX notation, e.g. 'FF00FC' $rgb = sprintf('%02X%02X%02X', $r, $g, $b); return ['rgb' => $rgb]; } /** * Extracts an Excel Unicode short string (8-bit string length) * OpenOffice documentation: 2.5.3 * function will automatically find out where the Unicode string ends. * * @return array{value: string, size: int} */ protected static function readUnicodeStringShort(string $subData): array { // offset: 0: size: 1; length of the string (character count) $characterCount = ord($subData[0]); $string = self::readUnicodeString(substr($subData, 1), $characterCount); // add 1 for the string length ++$string['size']; return $string; } /** * Extracts an Excel Unicode long string (16-bit string length) * OpenOffice documentation: 2.5.3 * this function is under construction, needs to support rich text, and Asian phonetic settings. * * @return array{value: string, size: int} */ protected static function readUnicodeStringLong(string $subData): array { // offset: 0: size: 2; length of the string (character count) $characterCount = self::getUInt2d($subData, 0); $string = self::readUnicodeString(substr($subData, 2), $characterCount); // add 2 for the string length $string['size'] += 2; return $string; } /** * Read Unicode string with no string length field, but with known character count * this function is under construction, needs to support rich text, and Asian phonetic settings * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.3. * * @return array{value: string, size: int} */ protected static function readUnicodeString(string $subData, int $characterCount): array { // offset: 0: size: 1; option flags // bit: 0; mask: 0x01; character compression (0 = compressed 8-bit, 1 = uncompressed 16-bit) $isCompressed = !((0x01 & ord($subData[0])) >> 0); // bit: 2; mask: 0x04; Asian phonetic settings //$hasAsian = (0x04) & ord($subData[0]) >> 2; // bit: 3; mask: 0x08; Rich-Text settings //$hasRichText = (0x08) & ord($subData[0]) >> 3; // offset: 1: size: var; character array // this offset assumes richtext and Asian phonetic settings are off which is generally wrong // needs to be fixed $value = self::encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed); return [ 'value' => $value, 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags ]; } /** * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas. * Example: hello"world --> "hello""world". * * @param string $value UTF-8 encoded string */ protected static function UTF8toExcelDoubleQuoted(string $value): string { return '"' . str_replace('"', '""', $value) . '"'; } /** * Reads first 8 bytes of a string and return IEEE 754 float. * * @param string $data Binary string that is at least 8 bytes long */ protected static function extractNumber(string $data): int|float { $rknumhigh = self::getInt4d($data, 4); $rknumlow = self::getInt4d($data, 0); $sign = ($rknumhigh & self::HIGH_ORDER_BIT) >> 31; $exp = (($rknumhigh & 0x7FF00000) >> 20) - 1023; $mantissa = (0x100000 | ($rknumhigh & 0x000FFFFF)); $mantissalow1 = ($rknumlow & self::HIGH_ORDER_BIT) >> 31; $mantissalow2 = ($rknumlow & 0x7FFFFFFF); $value = $mantissa / 2 ** (20 - $exp); if ($mantissalow1 != 0) { $value += 1 / 2 ** (21 - $exp); } if ($mantissalow2 != 0) { $value += $mantissalow2 / 2 ** (52 - $exp); } if ($sign) { $value *= -1; } return $value; } protected static function getIEEE754(int $rknum): float|int { if (($rknum & 0x02) != 0) { $value = $rknum >> 2; } else { // changes by mmp, info on IEEE754 encoding from // research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html // The RK format calls for using only the most significant 30 bits // of the 64 bit floating point value. The other 34 bits are assumed // to be 0 so we use the upper 30 bits of $rknum as follows... $sign = ($rknum & self::HIGH_ORDER_BIT) >> 31; $exp = ($rknum & 0x7FF00000) >> 20; $mantissa = (0x100000 | ($rknum & 0x000FFFFC)); $value = $mantissa / 2 ** (20 - ($exp - 1023)); if ($sign) { $value = -1 * $value; } //end of changes by mmp } if (($rknum & 0x01) != 0) { $value /= 100; } return $value; } /** * Get UTF-8 string from (compressed or uncompressed) UTF-16 string. */ protected static function encodeUTF16(string $string, bool $compressed = false): string { if ($compressed) { $string = self::uncompressByteString($string); } return StringHelper::convertEncoding($string, 'UTF-8', 'UTF-16LE'); } /** * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8. */ protected static function uncompressByteString(string $string): string { $uncompressedString = ''; $strLen = strlen($string); for ($i = 0; $i < $strLen; ++$i) { $uncompressedString .= $string[$i] . "\0"; } return $uncompressedString; } /** * Convert string to UTF-8. Only used for BIFF5. */ protected function decodeCodepage(string $string): string { return StringHelper::convertEncoding($string, 'UTF-8', $this->codepage); } protected static function confirmPos(string $data, int $pos): void { if ($pos >= strlen($data)) { throw new PhpSpreadsheetException('File appears to be corrupt'); // @codeCoverageIgnore } } /** * Read 16-bit unsigned integer. */ public static function getUInt2d(string $data, int $pos): int { self::confirmPos($data, $pos + 1); return ord($data[$pos]) | (ord($data[$pos + 1]) << 8); } /** * Read 16-bit signed integer. */ public static function getInt2d(string $data, int $pos): int { self::confirmPos($data, $pos + 1); return unpack('s', $data[$pos] . $data[$pos + 1])[1]; // @phpstan-ignore-line } /** * Read 32-bit signed integer. */ public static function getInt4d(string $data, int $pos): int { self::confirmPos($data, $pos + 3); // FIX: represent numbers correctly on 64-bit system // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 // Changed by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems $_or_24 = ord($data[$pos + 3]); if ($_or_24 >= 128) { // negative number $_ord_24 = -abs((256 - $_or_24) << 24); } else { $_ord_24 = ($_or_24 & 127) << 24; } return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php ================================================ parent = $parent; $this->worksheetXml = $worksheetXml; } public function load(): void { // Remove all "$" in the auto filter range $attrs = $this->worksheetXml->autoFilter->attributes() ?? []; $autoFilterRange = (string) preg_replace('/\$/', '', $attrs['ref'] ?? ''); if (str_contains($autoFilterRange, ':')) { $this->readAutoFilter($autoFilterRange); } } private function readAutoFilter(string $autoFilterRange): void { $autoFilter = $this->parent->getAutoFilter(); $autoFilter->setRange($autoFilterRange); foreach ($this->worksheetXml->autoFilter->filterColumn as $filterColumn) { $attributes = $filterColumn->attributes() ?? []; $column = $autoFilter->getColumnByOffset((int) ($attributes['colId'] ?? 0)); // Check for standard filters if ($filterColumn->filters) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); $filters = Xlsx::testSimpleXml($filterColumn->filters->attributes()); if ((isset($filters['blank'])) && ((int) $filters['blank'] == 1)) { // Operator is undefined, but always treated as EQUAL $column->createRule()->setRule('', '')->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER); } // Standard filters are always an OR join, so no join rule needs to be set // Entries can be either filter elements foreach ($filterColumn->filters->filter as $filterRule) { // Operator is undefined, but always treated as EQUAL /** @var SimpleXMLElement */ $attr2 = $filterRule->attributes() ?? ['val' => '']; $column->createRule()->setRule('', (string) $attr2['val'])->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER); } // Or Date Group elements $this->readDateRangeAutoFilter($filterColumn->filters, $column); } // Check for custom filters $this->readCustomAutoFilter($filterColumn, $column); // Check for dynamic filters $this->readDynamicAutoFilter($filterColumn, $column); // Check for dynamic filters $this->readTopTenAutoFilter($filterColumn, $column); } $autoFilter->setEvaluated(true); } private function readDateRangeAutoFilter(SimpleXMLElement $filters, Column $column): void { foreach ($filters->dateGroupItem as $dateGroupItemx) { // Operator is undefined, but always treated as EQUAL $dateGroupItem = $dateGroupItemx->attributes(); if ($dateGroupItem !== null) { $column->createRule()->setRule( '', [ 'year' => (string) $dateGroupItem['year'], 'month' => (string) $dateGroupItem['month'], 'day' => (string) $dateGroupItem['day'], 'hour' => (string) $dateGroupItem['hour'], 'minute' => (string) $dateGroupItem['minute'], 'second' => (string) $dateGroupItem['second'], ], (string) $dateGroupItem['dateTimeGrouping'] )->setRuleType(Rule::AUTOFILTER_RULETYPE_DATEGROUP); } } } private function readCustomAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void { if (isset($filterColumn, $filterColumn->customFilters)) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); $customFilters = $filterColumn->customFilters; $attributes = $customFilters->attributes(); // Custom filters can an AND or an OR join; // and there should only ever be one or two entries if ((isset($attributes['and'])) && ((string) $attributes['and'] === '1')) { $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); } foreach ($customFilters->customFilter as $filterRule) { /** @var SimpleXMLElement */ $attr2 = $filterRule->attributes() ?? ['operator' => '', 'val' => '']; $column->createRule()->setRule( (string) $attr2['operator'], (string) $attr2['val'] )->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); } } } private function readDynamicAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void { if (isset($filterColumn, $filterColumn->dynamicFilter)) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); // We should only ever have one dynamic filter foreach ($filterColumn->dynamicFilter as $filterRule) { // Operator is undefined, but always treated as EQUAL $attr2 = $filterRule->attributes() ?? []; $column->createRule()->setRule( '', (string) ($attr2['val'] ?? ''), (string) ($attr2['type'] ?? '') )->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); if (isset($attr2['val'])) { $column->setAttribute('val', (string) $attr2['val']); } if (isset($attr2['maxVal'])) { $column->setAttribute('maxVal', (string) $attr2['maxVal']); } } } } private function readTopTenAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void { if (isset($filterColumn, $filterColumn->top10)) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); // We should only ever have one top10 filter foreach ($filterColumn->top10 as $filterRule) { $attr2 = $filterRule->attributes() ?? []; $column->createRule()->setRule( ( ((isset($attr2['percent'])) && ((string) $attr2['percent'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE ), (string) ($attr2['val'] ?? ''), ( ((isset($attr2['top'])) && ((string) $attr2['top'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) )->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php ================================================ cNamespace = $cNamespace; $this->aNamespace = $aNamespace; } private static function getAttributeString(SimpleXMLElement $component, string $name): string|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { return (string) $attributes[$name]; } return null; } private static function getAttributeInteger(SimpleXMLElement $component, string $name): int|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { return (int) $attributes[$name]; } return null; } private static function getAttributeBoolean(SimpleXMLElement $component, string $name): bool|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { $value = (string) $attributes[$name]; return $value === 'true' || $value === '1'; } return null; } private static function getAttributeFloat(SimpleXMLElement $component, string $name): float|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { return (float) $attributes[$name]; } return null; } public function readChart(SimpleXMLElement $chartElements, string $chartName): \PhpOffice\PhpSpreadsheet\Chart\Chart { $chartElementsC = $chartElements->children($this->cNamespace); $XaxisLabel = $YaxisLabel = $legend = $title = null; $dispBlanksAs = null; $plotVisOnly = false; $plotArea = null; $rotX = $rotY = $rAngAx = $perspective = null; $xAxis = new Axis(); $yAxis = new Axis(); $autoTitleDeleted = null; $chartNoFill = false; $chartBorderLines = null; $chartFillColor = null; $gradientArray = []; $gradientLin = null; $roundedCorners = false; $gapWidth = null; $useUpBars = null; $useDownBars = null; $noBorder = false; foreach ($chartElementsC as $chartElementKey => $chartElement) { switch ($chartElementKey) { case 'spPr': $children = $chartElementsC->spPr->children($this->aNamespace); if (isset($children->noFill)) { $chartNoFill = true; } if (isset($children->solidFill)) { $chartFillColor = $this->readColor($children->solidFill); } if (isset($children->ln)) { $chartBorderLines = new GridLines(); $this->readLineStyle($chartElementsC, $chartBorderLines); if (isset($children->ln->noFill)) { $noBorder = true; } } break; case 'roundedCorners': /** @var bool $roundedCorners */ $roundedCorners = self::getAttributeBoolean($chartElementsC->roundedCorners, 'val'); break; case 'chart': foreach ($chartElement as $chartDetailsKey => $chartDetails) { $chartDetails = Xlsx::testSimpleXml($chartDetails); switch ($chartDetailsKey) { case 'autoTitleDeleted': /** @var bool $autoTitleDeleted */ $autoTitleDeleted = self::getAttributeBoolean($chartElementsC->chart->autoTitleDeleted, 'val'); break; case 'view3D': $rotX = self::getAttributeInteger($chartDetails->rotX, 'val'); $rotY = self::getAttributeInteger($chartDetails->rotY, 'val'); $rAngAx = self::getAttributeInteger($chartDetails->rAngAx, 'val'); $perspective = self::getAttributeInteger($chartDetails->perspective, 'val'); break; case 'plotArea': $plotAreaLayout = $XaxisLabel = $YaxisLabel = null; $plotSeries = $plotAttributes = []; $catAxRead = false; $plotNoFill = false; foreach ($chartDetails as $chartDetailKey => $chartDetail) { $chartDetail = Xlsx::testSimpleXml($chartDetail); switch ($chartDetailKey) { case 'spPr': $possibleNoFill = $chartDetails->spPr->children($this->aNamespace); if (isset($possibleNoFill->noFill)) { $plotNoFill = true; } if (isset($possibleNoFill->gradFill->gsLst)) { foreach ($possibleNoFill->gradFill->gsLst->gs as $gradient) { $gradient = Xlsx::testSimpleXml($gradient); /** @var float $pos */ $pos = self::getAttributeFloat($gradient, 'pos'); $gradientArray[] = [ $pos / ChartProperties::PERCENTAGE_MULTIPLIER, new ChartColor($this->readColor($gradient)), ]; } } if (isset($possibleNoFill->gradFill->lin)) { $gradientLin = ChartProperties::XmlToAngle((string) self::getAttributeString($possibleNoFill->gradFill->lin, 'ang')); } break; case 'layout': $plotAreaLayout = $this->chartLayoutDetails($chartDetail); break; case Axis::AXIS_TYPE_CATEGORY: case Axis::AXIS_TYPE_DATE: $catAxRead = true; if (isset($chartDetail->title)) { $XaxisLabel = $this->chartTitle($chartDetail->title->children($this->cNamespace)); } $xAxis->setAxisType($chartDetailKey); $this->readEffects($chartDetail, $xAxis); $this->readLineStyle($chartDetail, $xAxis); if (isset($chartDetail->spPr)) { $sppr = $chartDetail->spPr->children($this->aNamespace); if (isset($sppr->solidFill)) { $axisColorArray = $this->readColor($sppr->solidFill); $xAxis->setFillParameters($axisColorArray['value'], $axisColorArray['alpha'], $axisColorArray['type']); } if (isset($chartDetail->spPr->ln->noFill)) { $xAxis->setNoFill(true); } } if (isset($chartDetail->majorGridlines)) { $majorGridlines = new GridLines(); if (isset($chartDetail->majorGridlines->spPr)) { $this->readEffects($chartDetail->majorGridlines, $majorGridlines); $this->readLineStyle($chartDetail->majorGridlines, $majorGridlines); } $xAxis->setMajorGridlines($majorGridlines); } if (isset($chartDetail->minorGridlines)) { $minorGridlines = new GridLines(); $minorGridlines->activateObject(); if (isset($chartDetail->minorGridlines->spPr)) { $this->readEffects($chartDetail->minorGridlines, $minorGridlines); $this->readLineStyle($chartDetail->minorGridlines, $minorGridlines); } $xAxis->setMinorGridlines($minorGridlines); } $this->setAxisProperties($chartDetail, $xAxis); break; case Axis::AXIS_TYPE_VALUE: $whichAxis = null; $axPos = null; if (isset($chartDetail->axPos)) { $axPos = self::getAttributeString($chartDetail->axPos, 'val'); } if ($catAxRead) { $whichAxis = $yAxis; $yAxis->setAxisType($chartDetailKey); } elseif (!empty($axPos)) { switch ($axPos) { case 't': case 'b': $whichAxis = $xAxis; $xAxis->setAxisType($chartDetailKey); break; case 'r': case 'l': $whichAxis = $yAxis; $yAxis->setAxisType($chartDetailKey); break; } } if (isset($chartDetail->title)) { $axisLabel = $this->chartTitle($chartDetail->title->children($this->cNamespace)); switch ($axPos) { case 't': case 'b': $XaxisLabel = $axisLabel; break; case 'r': case 'l': $YaxisLabel = $axisLabel; break; } } $this->readEffects($chartDetail, $whichAxis); $this->readLineStyle($chartDetail, $whichAxis); if ($whichAxis !== null && isset($chartDetail->spPr)) { $sppr = $chartDetail->spPr->children($this->aNamespace); if (isset($sppr->solidFill)) { $axisColorArray = $this->readColor($sppr->solidFill); $whichAxis->setFillParameters($axisColorArray['value'], $axisColorArray['alpha'], $axisColorArray['type']); } if (isset($sppr->ln->noFill)) { $whichAxis->setNoFill(true); } } if ($whichAxis !== null && isset($chartDetail->majorGridlines)) { $majorGridlines = new GridLines(); if (isset($chartDetail->majorGridlines->spPr)) { $this->readEffects($chartDetail->majorGridlines, $majorGridlines); $this->readLineStyle($chartDetail->majorGridlines, $majorGridlines); } $whichAxis->setMajorGridlines($majorGridlines); } if ($whichAxis !== null && isset($chartDetail->minorGridlines)) { $minorGridlines = new GridLines(); $minorGridlines->activateObject(); if (isset($chartDetail->minorGridlines->spPr)) { $this->readEffects($chartDetail->minorGridlines, $minorGridlines); $this->readLineStyle($chartDetail->minorGridlines, $minorGridlines); } $whichAxis->setMinorGridlines($minorGridlines); } $this->setAxisProperties($chartDetail, $whichAxis); break; case 'barChart': case 'bar3DChart': $barDirection = self::getAttributeString($chartDetail->barDir, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotDirection("$barDirection"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'lineChart': case 'line3DChart': $plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'areaChart': case 'area3DChart': $plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'doughnutChart': case 'pieChart': case 'pie3DChart': $explosion = self::getAttributeString($chartDetail->ser->explosion, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle("$explosion"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'scatterChart': $scatterStyle = self::getAttributeString($chartDetail->scatterStyle, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle($scatterStyle); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'bubbleChart': $bubbleScale = self::getAttributeInteger($chartDetail->bubbleScale, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle("$bubbleScale"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'radarChart': $radarStyle = self::getAttributeString($chartDetail->radarStyle, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle($radarStyle); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'surfaceChart': case 'surface3DChart': $wireFrame = self::getAttributeBoolean($chartDetail->wireframe, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle("$wireFrame"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'stockChart': $plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey); if (isset($chartDetail->upDownBars->gapWidth)) { $gapWidth = self::getAttributeInteger($chartDetail->upDownBars->gapWidth, 'val'); } if (isset($chartDetail->upDownBars->upBars)) { $useUpBars = true; } if (isset($chartDetail->upDownBars->downBars)) { $useDownBars = true; } $plotAttributes = $this->readChartAttributes($chartDetail); break; } } if ($plotAreaLayout == null) { $plotAreaLayout = new Layout(); } $plotArea = new PlotArea($plotAreaLayout, $plotSeries); $this->setChartAttributes($plotAreaLayout, $plotAttributes); if ($plotNoFill) { $plotArea->setNoFill(true); } if (!empty($gradientArray)) { $plotArea->setGradientFillProperties($gradientArray, $gradientLin); } if (is_int($gapWidth)) { $plotArea->setGapWidth($gapWidth); } if ($useUpBars === true) { $plotArea->setUseUpBars(true); } if ($useDownBars === true) { $plotArea->setUseDownBars(true); } break; case 'plotVisOnly': $plotVisOnly = (bool) self::getAttributeString($chartDetails, 'val'); break; case 'dispBlanksAs': $dispBlanksAs = self::getAttributeString($chartDetails, 'val'); break; case 'title': $title = $this->chartTitle($chartDetails); break; case 'legend': $legendPos = 'r'; $legendLayout = null; $legendOverlay = false; $legendBorderLines = null; $legendFillColor = null; $legendText = null; $addLegendText = false; foreach ($chartDetails as $chartDetailKey => $chartDetail) { $chartDetail = Xlsx::testSimpleXml($chartDetail); switch ($chartDetailKey) { case 'legendPos': $legendPos = self::getAttributeString($chartDetail, 'val'); break; case 'overlay': $legendOverlay = self::getAttributeBoolean($chartDetail, 'val'); break; case 'layout': $legendLayout = $this->chartLayoutDetails($chartDetail); break; case 'spPr': $children = $chartDetails->spPr->children($this->aNamespace); if (isset($children->solidFill)) { $legendFillColor = $this->readColor($children->solidFill); } if (isset($children->ln)) { $legendBorderLines = new GridLines(); $this->readLineStyle($chartDetails, $legendBorderLines); } break; case 'txPr': $children = $chartDetails->txPr->children($this->aNamespace); $addLegendText = false; $legendText = new AxisText(); if (isset($children->p->pPr->defRPr->solidFill)) { $colorArray = $this->readColor($children->p->pPr->defRPr->solidFill); $legendText->getFillColorObject()->setColorPropertiesArray($colorArray); $addLegendText = true; } if (isset($children->p->pPr->defRPr->effectLst)) { $this->readEffects($children->p->pPr->defRPr, $legendText, false); $addLegendText = true; } break; } } $legend = new Legend("$legendPos", $legendLayout, (bool) $legendOverlay); if ($legendFillColor !== null) { $legend->getFillColor()->setColorPropertiesArray($legendFillColor); } if ($legendBorderLines !== null) { $legend->setBorderLines($legendBorderLines); } if ($addLegendText) { $legend->setLegendText($legendText); } break; } } } } $chart = new \PhpOffice\PhpSpreadsheet\Chart\Chart($chartName, $title, $legend, $plotArea, $plotVisOnly, (string) $dispBlanksAs, $XaxisLabel, $YaxisLabel, $xAxis, $yAxis); if ($chartNoFill) { $chart->setNoFill(true); } if ($chartFillColor !== null) { $chart->getFillColor()->setColorPropertiesArray($chartFillColor); } if ($chartBorderLines !== null) { $chart->setBorderLines($chartBorderLines); } $chart->setNoBorder($noBorder); $chart->setRoundedCorners($roundedCorners); if (is_bool($autoTitleDeleted)) { $chart->setAutoTitleDeleted($autoTitleDeleted); } if (is_int($rotX)) { $chart->setRotX($rotX); } if (is_int($rotY)) { $chart->setRotY($rotY); } if (is_int($rAngAx)) { $chart->setRAngAx($rAngAx); } if (is_int($perspective)) { $chart->setPerspective($perspective); } return $chart; } private function chartTitle(SimpleXMLElement $titleDetails): Title { $caption = ''; $titleLayout = null; $titleOverlay = false; $titleFormula = null; $titleFont = null; foreach ($titleDetails as $titleDetailKey => $chartDetail) { $chartDetail = Xlsx::testSimpleXml($chartDetail); switch ($titleDetailKey) { case 'tx': $caption = []; if (isset($chartDetail->rich)) { $titleDetails = $chartDetail->rich->children($this->aNamespace); foreach ($titleDetails as $titleKey => $titleDetail) { $titleDetail = Xlsx::testSimpleXml($titleDetail); switch ($titleKey) { case 'p': $titleDetailPart = $titleDetail->children($this->aNamespace); $caption[] = $this->parseRichText($titleDetailPart); } } } elseif (isset($chartDetail->strRef->strCache)) { foreach ($chartDetail->strRef->strCache->pt as $pt) { if (isset($pt->v)) { $caption[] = (string) $pt->v; } } if (isset($chartDetail->strRef->f)) { $titleFormula = (string) $chartDetail->strRef->f; } } break; case 'overlay': $titleOverlay = self::getAttributeBoolean($chartDetail, 'val'); break; case 'layout': $titleLayout = $this->chartLayoutDetails($chartDetail); break; case 'txPr': if (isset($chartDetail->children($this->aNamespace)->p)) { $titleFont = $this->parseFont($chartDetail->children($this->aNamespace)->p); } break; } } $title = new Title($caption, $titleLayout, (bool) $titleOverlay); if (!empty($titleFormula)) { $title->setCellReference($titleFormula); } if ($titleFont !== null) { $title->setFont($titleFont); } return $title; } private function chartLayoutDetails(SimpleXMLElement $chartDetail): ?Layout { if (!isset($chartDetail->manualLayout)) { return null; } $details = $chartDetail->manualLayout->children($this->cNamespace); if ($details === null) { return null; } $layout = []; foreach ($details as $detailKey => $detail) { $detail = Xlsx::testSimpleXml($detail); $layout[$detailKey] = self::getAttributeString($detail, 'val'); } return new Layout($layout); } private function chartDataSeries(SimpleXMLElement $chartDetail, string $plotType): DataSeries { $multiSeriesType = null; $smoothLine = false; $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = $seriesBubbles = []; $plotDirection = null; $seriesDetailSet = $chartDetail->children($this->cNamespace); foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) { switch ($seriesDetailKey) { case 'grouping': $multiSeriesType = self::getAttributeString($chartDetail->grouping, 'val'); break; case 'ser': $marker = null; $seriesIndex = ''; $fillColor = null; $pointSize = null; $noFill = false; $bubble3D = false; $dptColors = []; $markerFillColor = null; $markerBorderColor = null; $lineStyle = null; $labelLayout = null; $trendLines = []; foreach ($seriesDetails as $seriesKey => $seriesDetail) { $seriesDetail = Xlsx::testSimpleXml($seriesDetail); switch ($seriesKey) { case 'idx': $seriesIndex = self::getAttributeInteger($seriesDetail, 'val'); break; case 'order': $seriesOrder = self::getAttributeInteger($seriesDetail, 'val'); if ($seriesOrder !== null) { $plotOrder[$seriesIndex] = $seriesOrder; } break; case 'tx': $temp = $this->chartDataSeriesValueSet($seriesDetail); if ($temp !== null) { $seriesLabel[$seriesIndex] = $temp; } break; case 'spPr': $children = $seriesDetail->children($this->aNamespace); if (isset($children->ln)) { $ln = $children->ln; if (is_countable($ln->noFill) && count($ln->noFill) === 1) { $noFill = true; } $lineStyle = new GridLines(); $this->readLineStyle($seriesDetails, $lineStyle); } if (isset($children->effectLst)) { if ($lineStyle === null) { $lineStyle = new GridLines(); } $this->readEffects($seriesDetails, $lineStyle); } if (isset($children->solidFill)) { $fillColor = new ChartColor($this->readColor($children->solidFill)); } break; case 'dPt': $dptIdx = (int) self::getAttributeString($seriesDetail->idx, 'val'); if (isset($seriesDetail->spPr)) { $children = $seriesDetail->spPr->children($this->aNamespace); if (isset($children->solidFill)) { $arrayColors = $this->readColor($children->solidFill); $dptColors[$dptIdx] = new ChartColor($arrayColors); } } break; case 'trendline': $trendLine = new TrendLine(); $this->readLineStyle($seriesDetail, $trendLine); $trendLineType = self::getAttributeString($seriesDetail->trendlineType, 'val'); $dispRSqr = self::getAttributeBoolean($seriesDetail->dispRSqr, 'val'); $dispEq = self::getAttributeBoolean($seriesDetail->dispEq, 'val'); $order = self::getAttributeInteger($seriesDetail->order, 'val'); $period = self::getAttributeInteger($seriesDetail->period, 'val'); $forward = self::getAttributeFloat($seriesDetail->forward, 'val'); $backward = self::getAttributeFloat($seriesDetail->backward, 'val'); $intercept = self::getAttributeFloat($seriesDetail->intercept, 'val'); $name = (string) $seriesDetail->name; $trendLine->setTrendLineProperties( $trendLineType, $order, $period, $dispRSqr, $dispEq, $backward, $forward, $intercept, $name ); $trendLines[] = $trendLine; break; case 'marker': $marker = self::getAttributeString($seriesDetail->symbol, 'val'); $pointSize = self::getAttributeString($seriesDetail->size, 'val'); $pointSize = is_numeric($pointSize) ? ((int) $pointSize) : null; if (isset($seriesDetail->spPr)) { $children = $seriesDetail->spPr->children($this->aNamespace); if (isset($children->solidFill)) { $markerFillColor = $this->readColor($children->solidFill); } if (isset($children->ln->solidFill)) { $markerBorderColor = $this->readColor($children->ln->solidFill); } } break; case 'smooth': $smoothLine = self::getAttributeBoolean($seriesDetail, 'val') ?? false; break; case 'cat': $temp = $this->chartDataSeriesValueSet($seriesDetail); if ($temp !== null) { $seriesCategory[$seriesIndex] = $temp; } break; case 'val': $temp = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($temp !== null) { $seriesValues[$seriesIndex] = $temp; } break; case 'xVal': $temp = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($temp !== null) { $seriesCategory[$seriesIndex] = $temp; } break; case 'yVal': $temp = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($temp !== null) { $seriesValues[$seriesIndex] = $temp; } break; case 'bubbleSize': $seriesBubble = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($seriesBubble !== null) { $seriesBubbles[$seriesIndex] = $seriesBubble; } break; case 'bubble3D': $bubble3D = self::getAttributeBoolean($seriesDetail, 'val'); break; case 'dLbls': $labelLayout = new Layout($this->readChartAttributes($seriesDetails)); break; } } if ($labelLayout) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setLabelLayout($labelLayout); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setLabelLayout($labelLayout); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setLabelLayout($labelLayout); } } if ($noFill) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setScatterLines(false); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setScatterLines(false); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setScatterLines(false); } } if ($lineStyle !== null) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->copyLineStyles($lineStyle); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->copyLineStyles($lineStyle); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->copyLineStyles($lineStyle); } } if ($bubble3D) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setBubble3D($bubble3D); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setBubble3D($bubble3D); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setBubble3D($bubble3D); } } if (!empty($dptColors)) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setFillColor($dptColors); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setFillColor($dptColors); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setFillColor($dptColors); } } if ($markerFillColor !== null) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->getMarkerFillColor()->setColorPropertiesArray($markerFillColor); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->getMarkerFillColor()->setColorPropertiesArray($markerFillColor); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->getMarkerFillColor()->setColorPropertiesArray($markerFillColor); } } if ($markerBorderColor !== null) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->getMarkerBorderColor()->setColorPropertiesArray($markerBorderColor); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->getMarkerBorderColor()->setColorPropertiesArray($markerBorderColor); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->getMarkerBorderColor()->setColorPropertiesArray($markerBorderColor); } } if ($smoothLine) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setSmoothLine(true); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setSmoothLine(true); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setSmoothLine(true); } } if (!empty($trendLines)) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setTrendLines($trendLines); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setTrendLines($trendLines); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setTrendLines($trendLines); } } } } $series = new DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $plotDirection, $smoothLine); $series->setPlotBubbleSizes($seriesBubbles); return $series; } private function chartDataSeriesValueSet(SimpleXMLElement $seriesDetail, ?string $marker = null, ?ChartColor $fillColor = null, ?string $pointSize = null): ?DataSeriesValues { if (isset($seriesDetail->strRef)) { $seriesSource = (string) $seriesDetail->strRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->strRef->strCache)) { /** @var array{formatCode: string, dataValues: mixed[]} */ $seriesData = $this->chartDataSeriesValues($seriesDetail->strRef->strCache->children($this->cNamespace), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->numRef)) { $seriesSource = (string) $seriesDetail->numRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->numRef->numCache)) { /** @var array{formatCode: string, dataValues: mixed[]} */ $seriesData = $this->chartDataSeriesValues($seriesDetail->numRef->numCache->children($this->cNamespace)); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->multiLvlStrRef)) { $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->multiLvlStrRef->multiLvlStrCache)) { /** @var array{formatCode: string, dataValues: mixed[]} */ $seriesData = $this->chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($this->cNamespace), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->multiLvlNumRef)) { $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->multiLvlNumRef->multiLvlNumCache)) { /** @var array{formatCode: string, dataValues: mixed[]} */ $seriesData = $this->chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($this->cNamespace), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } if (isset($seriesDetail->v)) { return new DataSeriesValues( DataSeriesValues::DATASERIES_TYPE_STRING, null, null, 1, [(string) $seriesDetail->v] ); } return null; } /** @return mixed[] */ private function chartDataSeriesValues(SimpleXMLElement $seriesValueSet, string $dataType = 'n'): array { $seriesVal = []; $formatCode = ''; $pointCount = 0; foreach ($seriesValueSet as $seriesValueIdx => $seriesValue) { $seriesValue = Xlsx::testSimpleXml($seriesValue); switch ($seriesValueIdx) { case 'ptCount': $pointCount = self::getAttributeInteger($seriesValue, 'val'); break; case 'formatCode': $formatCode = (string) $seriesValue; break; case 'pt': $pointVal = self::getAttributeInteger($seriesValue, 'idx'); if ($dataType == 's') { $seriesVal[$pointVal] = (string) $seriesValue->v; } elseif ((string) $seriesValue->v === ExcelError::NA()) { $seriesVal[$pointVal] = null; } else { $seriesVal[$pointVal] = (float) $seriesValue->v; } break; } } return [ 'formatCode' => $formatCode, 'pointCount' => $pointCount, 'dataValues' => $seriesVal, ]; } /** @return mixed[] */ private function chartDataSeriesValuesMultiLevel(SimpleXMLElement $seriesValueSet, string $dataType = 'n'): array { $seriesVal = []; $formatCode = ''; $pointCount = 0; foreach ($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) { foreach ($seriesLevel as $seriesValueIdx => $seriesValue) { $seriesValue = Xlsx::testSimpleXml($seriesValue); switch ($seriesValueIdx) { case 'ptCount': $pointCount = self::getAttributeInteger($seriesValue, 'val'); break; case 'formatCode': $formatCode = (string) $seriesValue; break; case 'pt': $pointVal = self::getAttributeInteger($seriesValue, 'idx'); if ($dataType == 's') { $seriesVal[$pointVal][] = (string) $seriesValue->v; } elseif ((string) $seriesValue->v === ExcelError::NA()) { $seriesVal[$pointVal] = null; } else { $seriesVal[$pointVal][] = (float) $seriesValue->v; } break; } } } return [ 'formatCode' => $formatCode, 'pointCount' => $pointCount, 'dataValues' => $seriesVal, ]; } private function parseRichText(SimpleXMLElement $titleDetailPart): RichText { $value = new RichText(); $defaultFontSize = null; $defaultBold = null; $defaultItalic = null; $defaultUnderscore = null; $defaultStrikethrough = null; $defaultBaseline = null; $defaultFontName = null; $defaultLatin = null; $defaultEastAsian = null; $defaultComplexScript = null; $defaultFontColor = null; if (isset($titleDetailPart->pPr->defRPr)) { $defaultFontSize = self::getAttributeInteger($titleDetailPart->pPr->defRPr, 'sz'); $defaultBold = self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'b'); $defaultItalic = self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'i'); $defaultUnderscore = self::getAttributeString($titleDetailPart->pPr->defRPr, 'u'); $defaultStrikethrough = self::getAttributeString($titleDetailPart->pPr->defRPr, 'strike'); $defaultBaseline = self::getAttributeInteger($titleDetailPart->pPr->defRPr, 'baseline'); if (isset($titleDetailPart->defRPr->rFont['val'])) { $defaultFontName = (string) $titleDetailPart->defRPr->rFont['val']; } if (isset($titleDetailPart->pPr->defRPr->latin)) { $defaultLatin = self::getAttributeString($titleDetailPart->pPr->defRPr->latin, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->ea)) { $defaultEastAsian = self::getAttributeString($titleDetailPart->pPr->defRPr->ea, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->cs)) { $defaultComplexScript = self::getAttributeString($titleDetailPart->pPr->defRPr->cs, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->solidFill)) { $defaultFontColor = $this->readColor($titleDetailPart->pPr->defRPr->solidFill); } } foreach ($titleDetailPart as $titleDetailElementKey => $titleDetailElement) { if ( (string) $titleDetailElementKey !== 'r' || !isset($titleDetailElement->t) ) { continue; } $objText = $value->createTextRun((string) $titleDetailElement->t); if ($objText->getFont() === null) { // @codeCoverageIgnoreStart continue; // @codeCoverageIgnoreEnd } $fontSize = null; $bold = null; $italic = null; $underscore = null; $strikethrough = null; $baseline = null; $fontName = null; $latinName = null; $eastAsian = null; $complexScript = null; $fontColor = null; $underlineColor = null; if (isset($titleDetailElement->rPr)) { // not used now, not sure it ever was, grandfathering if (isset($titleDetailElement->rPr->rFont['val'])) { // @codeCoverageIgnoreStart $fontName = (string) $titleDetailElement->rPr->rFont['val']; // @codeCoverageIgnoreEnd } if (isset($titleDetailElement->rPr->latin)) { $latinName = self::getAttributeString($titleDetailElement->rPr->latin, 'typeface'); } if (isset($titleDetailElement->rPr->ea)) { $eastAsian = self::getAttributeString($titleDetailElement->rPr->ea, 'typeface'); } if (isset($titleDetailElement->rPr->cs)) { $complexScript = self::getAttributeString($titleDetailElement->rPr->cs, 'typeface'); } $fontSize = self::getAttributeInteger($titleDetailElement->rPr, 'sz'); // not used now, not sure it ever was, grandfathering if (isset($titleDetailElement->rPr->solidFill)) { $fontColor = $this->readColor($titleDetailElement->rPr->solidFill); } $bold = self::getAttributeBoolean($titleDetailElement->rPr, 'b'); $italic = self::getAttributeBoolean($titleDetailElement->rPr, 'i'); $baseline = self::getAttributeInteger($titleDetailElement->rPr, 'baseline'); $underscore = self::getAttributeString($titleDetailElement->rPr, 'u'); if (isset($titleDetailElement->rPr->uFill->solidFill)) { $underlineColor = $this->readColor($titleDetailElement->rPr->uFill->solidFill); } $strikethrough = self::getAttributeString($titleDetailElement->rPr, 'strike'); } $fontFound = false; $latinName = $latinName ?? $defaultLatin; if ($latinName !== null) { $objText->getFont()->setLatin($latinName); $fontFound = true; } $eastAsian = $eastAsian ?? $defaultEastAsian; if ($eastAsian !== null) { $objText->getFont()->setEastAsian($eastAsian); $fontFound = true; } $complexScript = $complexScript ?? $defaultComplexScript; if ($complexScript !== null) { $objText->getFont()->setComplexScript($complexScript); $fontFound = true; } $fontName = $fontName ?? $defaultFontName; if ($fontName !== null) { // @codeCoverageIgnoreStart $objText->getFont()->setName($fontName); $fontFound = true; // @codeCoverageIgnoreEnd } $fontSize = $fontSize ?? $defaultFontSize; if (is_int($fontSize)) { $objText->getFont()->setSize(floor($fontSize / 100)); $fontFound = true; } else { $objText->getFont()->setSize(null, true); } $fontColor = $fontColor ?? $defaultFontColor; if (!empty($fontColor)) { $objText->getFont()->setChartColor($fontColor); $fontFound = true; } $bold = $bold ?? $defaultBold; if ($bold !== null) { $objText->getFont()->setBold($bold); $fontFound = true; } $italic = $italic ?? $defaultItalic; if ($italic !== null) { $objText->getFont()->setItalic($italic); $fontFound = true; } $baseline = $baseline ?? $defaultBaseline; if ($baseline !== null) { $objText->getFont()->setBaseLine($baseline); if ($baseline > 0) { $objText->getFont()->setSuperscript(true); } elseif ($baseline < 0) { $objText->getFont()->setSubscript(true); } $fontFound = true; } $underscore = $underscore ?? $defaultUnderscore; if ($underscore !== null) { if ($underscore == 'sng') { $objText->getFont()->setUnderline(Font::UNDERLINE_SINGLE); } elseif ($underscore == 'dbl') { $objText->getFont()->setUnderline(Font::UNDERLINE_DOUBLE); } elseif ($underscore !== '') { $objText->getFont()->setUnderline($underscore); } else { $objText->getFont()->setUnderline(Font::UNDERLINE_NONE); } $fontFound = true; if ($underlineColor) { $objText->getFont()->setUnderlineColor($underlineColor); } } $strikethrough = $strikethrough ?? $defaultStrikethrough; if ($strikethrough !== null) { $objText->getFont()->setStrikeType($strikethrough); if ($strikethrough == 'noStrike') { $objText->getFont()->setStrikethrough(false); } else { $objText->getFont()->setStrikethrough(true); } $fontFound = true; } if ($fontFound === false) { $objText->setFont(null); } } return $value; } private function parseFont(SimpleXMLElement $titleDetailPart): ?Font { if (!isset($titleDetailPart->pPr->defRPr)) { return null; } $fontArray = []; $fontArray['size'] = self::getAttributeInteger($titleDetailPart->pPr->defRPr, 'sz'); if ($fontArray['size'] !== null && $fontArray['size'] >= 100) { $fontArray['size'] /= 100.0; } if ($fontArray['size'] !== null) { $fontArray['size'] = (int) ($fontArray['size']); } $fontArray['bold'] = (bool) self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'b'); $fontArray['italic'] = (bool) self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'i'); $fontArray['underscore'] = self::getAttributeString($titleDetailPart->pPr->defRPr, 'u'); $strikethrough = self::getAttributeString($titleDetailPart->pPr->defRPr, 'strike'); if ($strikethrough !== null) { if ($strikethrough == 'noStrike') { $fontArray['strikethrough'] = false; } else { $fontArray['strikethrough'] = true; } } $fontArray['cap'] = (string) self::getAttributeString($titleDetailPart->pPr->defRPr, 'cap'); if (isset($titleDetailPart->pPr->defRPr->latin)) { $fontArray['latin'] = (string) self::getAttributeString($titleDetailPart->pPr->defRPr->latin, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->ea)) { $fontArray['eastAsian'] = (string) self::getAttributeString($titleDetailPart->pPr->defRPr->ea, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->cs)) { $fontArray['complexScript'] = (string) self::getAttributeString($titleDetailPart->pPr->defRPr->cs, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->solidFill)) { $fontArray['chartColor'] = new ChartColor($this->readColor($titleDetailPart->pPr->defRPr->solidFill)); } $font = new Font(); //$font->setSize(null, true); $font->applyFromArray($fontArray); return $font; } /** @return mixed[] */ private function readChartAttributes(?SimpleXMLElement $chartDetail): array { $plotAttributes = []; if (isset($chartDetail->dLbls)) { if (isset($chartDetail->dLbls->dLblPos)) { $plotAttributes['dLblPos'] = self::getAttributeString($chartDetail->dLbls->dLblPos, 'val'); } if (isset($chartDetail->dLbls->numFmt)) { $plotAttributes['numFmtCode'] = self::getAttributeString($chartDetail->dLbls->numFmt, 'formatCode'); $plotAttributes['numFmtLinked'] = self::getAttributeBoolean($chartDetail->dLbls->numFmt, 'sourceLinked'); } if (isset($chartDetail->dLbls->showLegendKey)) { $plotAttributes['showLegendKey'] = self::getAttributeString($chartDetail->dLbls->showLegendKey, 'val'); } if (isset($chartDetail->dLbls->showVal)) { $plotAttributes['showVal'] = self::getAttributeString($chartDetail->dLbls->showVal, 'val'); } if (isset($chartDetail->dLbls->showCatName)) { $plotAttributes['showCatName'] = self::getAttributeString($chartDetail->dLbls->showCatName, 'val'); } if (isset($chartDetail->dLbls->showSerName)) { $plotAttributes['showSerName'] = self::getAttributeString($chartDetail->dLbls->showSerName, 'val'); } if (isset($chartDetail->dLbls->showPercent)) { $plotAttributes['showPercent'] = self::getAttributeString($chartDetail->dLbls->showPercent, 'val'); } if (isset($chartDetail->dLbls->showBubbleSize)) { $plotAttributes['showBubbleSize'] = self::getAttributeString($chartDetail->dLbls->showBubbleSize, 'val'); } if (isset($chartDetail->dLbls->showLeaderLines)) { $plotAttributes['showLeaderLines'] = self::getAttributeString($chartDetail->dLbls->showLeaderLines, 'val'); } if (isset($chartDetail->dLbls->spPr)) { $sppr = $chartDetail->dLbls->spPr->children($this->aNamespace); if (isset($sppr->solidFill)) { $plotAttributes['labelFillColor'] = new ChartColor($this->readColor($sppr->solidFill)); } if (isset($sppr->ln->solidFill)) { $plotAttributes['labelBorderColor'] = new ChartColor($this->readColor($sppr->ln->solidFill)); } } if (isset($chartDetail->dLbls->txPr)) { $txpr = $chartDetail->dLbls->txPr->children($this->aNamespace); if (isset($txpr->p)) { $plotAttributes['labelFont'] = $this->parseFont($txpr->p); if (isset($txpr->p->pPr->defRPr->effectLst)) { $labelEffects = new GridLines(); $this->readEffects($txpr->p->pPr->defRPr, $labelEffects, false); $plotAttributes['labelEffects'] = $labelEffects; } } } } return $plotAttributes; } /** @param array $plotAttributes */ private function setChartAttributes(Layout $plotArea, array $plotAttributes): void { foreach ($plotAttributes as $plotAttributeKey => $plotAttributeValue) { /** @var ?bool $plotAttributeValue */ switch ($plotAttributeKey) { case 'showLegendKey': $plotArea->setShowLegendKey($plotAttributeValue); break; case 'showVal': $plotArea->setShowVal($plotAttributeValue); break; case 'showCatName': $plotArea->setShowCatName($plotAttributeValue); break; case 'showSerName': $plotArea->setShowSerName($plotAttributeValue); break; case 'showPercent': $plotArea->setShowPercent($plotAttributeValue); break; case 'showBubbleSize': $plotArea->setShowBubbleSize($plotAttributeValue); break; case 'showLeaderLines': $plotArea->setShowLeaderLines($plotAttributeValue); break; case 'labelFont': /** @var ?Font $plotAttributeValue */ $plotArea->setLabelFont($plotAttributeValue); break; } } } private function readEffects(SimpleXMLElement $chartDetail, ?ChartProperties $chartObject, bool $getSppr = true): void { if (!isset($chartObject)) { return; } if ($getSppr) { if (!isset($chartDetail->spPr)) { return; } $sppr = $chartDetail->spPr->children($this->aNamespace); } else { $sppr = $chartDetail; } if (isset($sppr->effectLst->glow)) { $axisGlowSize = (float) self::getAttributeInteger($sppr->effectLst->glow, 'rad') / ChartProperties::POINTS_WIDTH_MULTIPLIER; if ($axisGlowSize != 0.0) { $colorArray = $this->readColor($sppr->effectLst->glow); $chartObject->setGlowProperties($axisGlowSize, $colorArray['value'], $colorArray['alpha'], $colorArray['type']); } } if (isset($sppr->effectLst->softEdge)) { $softEdgeSize = self::getAttributeString($sppr->effectLst->softEdge, 'rad'); if (is_numeric($softEdgeSize)) { $chartObject->setSoftEdges((float) ChartProperties::xmlToPoints($softEdgeSize)); } } $type = ''; foreach (self::SHADOW_TYPES as $shadowType) { if (isset($sppr->effectLst->$shadowType)) { $type = $shadowType; break; } } if ($type !== '') { $blur = self::getAttributeString($sppr->effectLst->$type, 'blurRad'); $blur = is_numeric($blur) ? ChartProperties::xmlToPoints($blur) : null; $dist = self::getAttributeString($sppr->effectLst->$type, 'dist'); $dist = is_numeric($dist) ? ChartProperties::xmlToPoints($dist) : null; $direction = self::getAttributeString($sppr->effectLst->$type, 'dir'); $direction = is_numeric($direction) ? ChartProperties::xmlToAngle($direction) : null; $algn = self::getAttributeString($sppr->effectLst->$type, 'algn'); $rot = self::getAttributeString($sppr->effectLst->$type, 'rotWithShape'); $size = []; foreach (['sx', 'sy'] as $sizeType) { $sizeValue = self::getAttributeString($sppr->effectLst->$type, $sizeType); if (is_numeric($sizeValue)) { $size[$sizeType] = ChartProperties::xmlToTenthOfPercent((string) $sizeValue); } else { $size[$sizeType] = null; } } foreach (['kx', 'ky'] as $sizeType) { $sizeValue = self::getAttributeString($sppr->effectLst->$type, $sizeType); if (is_numeric($sizeValue)) { $size[$sizeType] = ChartProperties::xmlToAngle((string) $sizeValue); } else { $size[$sizeType] = null; } } $colorArray = $this->readColor($sppr->effectLst->$type); $chartObject ->setShadowProperty('effect', $type) ->setShadowProperty('blur', $blur) ->setShadowProperty('direction', $direction) ->setShadowProperty('distance', $dist) ->setShadowProperty('algn', $algn) ->setShadowProperty('rotWithShape', $rot) ->setShadowProperty('size', $size) ->setShadowProperty('color', $colorArray); } } private const SHADOW_TYPES = [ 'outerShdw', 'innerShdw', ]; /** @return array{type: ?string, value: ?string, alpha: ?int, brightness: ?int} */ private function readColor(SimpleXMLElement $colorXml): array { $result = [ 'type' => null, 'value' => null, 'alpha' => null, 'brightness' => null, ]; foreach (ChartColor::EXCEL_COLOR_TYPES as $type) { if (isset($colorXml->$type)) { $result['type'] = $type; $result['value'] = self::getAttributeString($colorXml->$type, 'val'); if (isset($colorXml->$type->alpha)) { $alpha = self::getAttributeString($colorXml->$type->alpha, 'val'); if (is_numeric($alpha)) { $result['alpha'] = ChartColor::alphaFromXml($alpha); } } if (isset($colorXml->$type->lumMod)) { $brightness = self::getAttributeString($colorXml->$type->lumMod, 'val'); if (is_numeric($brightness)) { $result['brightness'] = ChartColor::alphaFromXml($brightness); } } break; } } return $result; } private function readLineStyle(SimpleXMLElement $chartDetail, ?ChartProperties $chartObject): void { if (!isset($chartObject, $chartDetail->spPr)) { return; } $sppr = $chartDetail->spPr->children($this->aNamespace); if (!isset($sppr->ln)) { return; } $lineWidth = null; $lineWidthTemp = self::getAttributeString($sppr->ln, 'w'); if (is_numeric($lineWidthTemp)) { $lineWidth = ChartProperties::xmlToPoints($lineWidthTemp); } $compoundType = self::getAttributeString($sppr->ln, 'cmpd'); $dashType = self::getAttributeString($sppr->ln->prstDash, 'val'); $capType = self::getAttributeString($sppr->ln, 'cap'); if (isset($sppr->ln->miter)) { $joinType = ChartProperties::LINE_STYLE_JOIN_MITER; } elseif (isset($sppr->ln->bevel)) { $joinType = ChartProperties::LINE_STYLE_JOIN_BEVEL; } else { $joinType = ''; } $headArrowSize = 0; $endArrowSize = 0; $headArrowType = self::getAttributeString($sppr->ln->headEnd, 'type'); $headArrowWidth = self::getAttributeString($sppr->ln->headEnd, 'w'); $headArrowLength = self::getAttributeString($sppr->ln->headEnd, 'len'); $endArrowType = self::getAttributeString($sppr->ln->tailEnd, 'type'); $endArrowWidth = self::getAttributeString($sppr->ln->tailEnd, 'w'); $endArrowLength = self::getAttributeString($sppr->ln->tailEnd, 'len'); $chartObject->setLineStyleProperties( $lineWidth, $compoundType, $dashType, $capType, $joinType, $headArrowType, $headArrowSize, $endArrowType, $endArrowSize, $headArrowWidth, $headArrowLength, $endArrowWidth, $endArrowLength ); $colorArray = $this->readColor($sppr->ln->solidFill); $chartObject->getLineColor()->setColorPropertiesArray($colorArray); } private function setAxisProperties(SimpleXMLElement $chartDetail, ?Axis $whichAxis): void { if (!isset($whichAxis)) { return; } if (isset($chartDetail->delete)) { $whichAxis->setAxisOption('hidden', (string) self::getAttributeString($chartDetail->delete, 'val')); } if (isset($chartDetail->numFmt)) { $whichAxis->setAxisNumberProperties( (string) self::getAttributeString($chartDetail->numFmt, 'formatCode'), null, (int) self::getAttributeInteger($chartDetail->numFmt, 'sourceLinked') ); } if (isset($chartDetail->crossBetween)) { $whichAxis->setCrossBetween((string) self::getAttributeString($chartDetail->crossBetween, 'val')); } if (isset($chartDetail->dispUnits, $chartDetail->dispUnits->builtInUnit)) { $whichAxis->setAxisOption('dispUnitsBuiltIn', (string) self::getAttributeString($chartDetail->dispUnits->builtInUnit, 'val')); if (isset($chartDetail->dispUnits->dispUnitsLbl)) { $whichAxis->setDispUnitsTitle(new Title()); // TODO parse title elements } } if (isset($chartDetail->majorTickMark)) { $whichAxis->setAxisOption('major_tick_mark', (string) self::getAttributeString($chartDetail->majorTickMark, 'val')); } if (isset($chartDetail->minorTickMark)) { $whichAxis->setAxisOption('minor_tick_mark', (string) self::getAttributeString($chartDetail->minorTickMark, 'val')); } if (isset($chartDetail->tickLblPos)) { $whichAxis->setAxisOption('axis_labels', (string) self::getAttributeString($chartDetail->tickLblPos, 'val')); } if (isset($chartDetail->crosses)) { $whichAxis->setAxisOption('horizontal_crosses', (string) self::getAttributeString($chartDetail->crosses, 'val')); } if (isset($chartDetail->crossesAt)) { $whichAxis->setAxisOption('horizontal_crosses_value', (string) self::getAttributeString($chartDetail->crossesAt, 'val')); } if (isset($chartDetail->scaling->logBase)) { $whichAxis->setAxisOption('logBase', (string) self::getAttributeString($chartDetail->scaling->logBase, 'val')); } if (isset($chartDetail->scaling->orientation)) { $whichAxis->setAxisOption('orientation', (string) self::getAttributeString($chartDetail->scaling->orientation, 'val')); } if (isset($chartDetail->scaling->max)) { $whichAxis->setAxisOption('maximum', (string) self::getAttributeString($chartDetail->scaling->max, 'val')); } if (isset($chartDetail->scaling->min)) { $whichAxis->setAxisOption('minimum', (string) self::getAttributeString($chartDetail->scaling->min, 'val')); } if (isset($chartDetail->scaling->min)) { $whichAxis->setAxisOption('minimum', (string) self::getAttributeString($chartDetail->scaling->min, 'val')); } if (isset($chartDetail->majorUnit)) { $whichAxis->setAxisOption('major_unit', (string) self::getAttributeString($chartDetail->majorUnit, 'val')); } if (isset($chartDetail->minorUnit)) { $whichAxis->setAxisOption('minor_unit', (string) self::getAttributeString($chartDetail->minorUnit, 'val')); } if (isset($chartDetail->baseTimeUnit)) { $whichAxis->setAxisOption('baseTimeUnit', (string) self::getAttributeString($chartDetail->baseTimeUnit, 'val')); } if (isset($chartDetail->majorTimeUnit)) { $whichAxis->setAxisOption('majorTimeUnit', (string) self::getAttributeString($chartDetail->majorTimeUnit, 'val')); } if (isset($chartDetail->minorTimeUnit)) { $whichAxis->setAxisOption('minorTimeUnit', (string) self::getAttributeString($chartDetail->minorTimeUnit, 'val')); } if (isset($chartDetail->txPr)) { $children = $chartDetail->txPr->children($this->aNamespace); $addAxisText = false; $axisText = new AxisText(); if (isset($children->bodyPr)) { $textRotation = self::getAttributeString($children->bodyPr, 'rot'); if (is_numeric($textRotation)) { $axisText->setRotation((int) ChartProperties::xmlToAngle($textRotation)); $addAxisText = true; } } if (isset($children->p->pPr->defRPr)) { $font = $this->parseFont($children->p); if ($font !== null) { $axisText->setFont($font); $addAxisText = true; } } if (isset($children->p->pPr->defRPr->effectLst)) { $this->readEffects($children->p->pPr->defRPr, $axisText, false); $addAxisText = true; } if ($addAxisText) { $whichAxis->setAxisText($axisText); } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php ================================================ worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } /** * Set Worksheet column attributes by attributes array passed. * * @param string $columnAddress A, B, ... DX, ... * @param array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float, width?: int} $columnAttributes array of attributes (indexes are attribute name, values are value) */ private function setColumnAttributes(string $columnAddress, array $columnAttributes): void { if (isset($columnAttributes['xfIndex'])) { $this->worksheet->getColumnDimension($columnAddress)->setXfIndex($columnAttributes['xfIndex']); } if (isset($columnAttributes['visible'])) { $this->worksheet->getColumnDimension($columnAddress)->setVisible($columnAttributes['visible']); } if (isset($columnAttributes['collapsed'])) { $this->worksheet->getColumnDimension($columnAddress)->setCollapsed($columnAttributes['collapsed']); } if (isset($columnAttributes['outlineLevel'])) { $this->worksheet->getColumnDimension($columnAddress)->setOutlineLevel($columnAttributes['outlineLevel']); } if (isset($columnAttributes['width'])) { $this->worksheet->getColumnDimension($columnAddress)->setWidth($columnAttributes['width']); } } /** * Set Worksheet row attributes by attributes array passed. * * @param int $rowNumber 1, 2, 3, ... 99, ... * @param array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float, customFormat?: bool, ht?: float} $rowAttributes array of attributes (indexes are attribute name, values are value) * 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ? */ private function setRowAttributes(int $rowNumber, array $rowAttributes): void { if (isset($rowAttributes['xfIndex'])) { $this->worksheet->getRowDimension($rowNumber) ->setXfIndex($rowAttributes['xfIndex']); } if (isset($rowAttributes['visible'])) { $this->worksheet->getRowDimension($rowNumber) ->setVisible($rowAttributes['visible']); } if (isset($rowAttributes['collapsed'])) { $this->worksheet->getRowDimension($rowNumber) ->setCollapsed($rowAttributes['collapsed']); } if (isset($rowAttributes['outlineLevel'])) { $this->worksheet->getRowDimension($rowNumber) ->setOutlineLevel($rowAttributes['outlineLevel']); } if (isset($rowAttributes['customFormat'], $rowAttributes['rowHeight'])) { $this->worksheet->getRowDimension($rowNumber) ->setCustomFormat($rowAttributes['customFormat'], $rowAttributes['rowHeight']); } elseif (isset($rowAttributes['rowHeight'])) { $this->worksheet->getRowDimension($rowNumber) ->setRowHeight($rowAttributes['rowHeight']); } } public function load(?IReadFilter $readFilter = null, bool $readDataOnly = false, bool $ignoreRowsWithNoCells = false): bool { if ($this->worksheetXml === null) { return false; } if ($readFilter !== null && $readFilter::class === DefaultReadFilter::class) { $readFilter = null; } $columnsAttributes = []; $rowsAttributes = []; if (isset($this->worksheetXml->cols)) { $columnsAttributes = $this->readColumnAttributes($this->worksheetXml->cols, $readDataOnly); } if ($this->worksheetXml->sheetData && $this->worksheetXml->sheetData->row) { $rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly, $ignoreRowsWithNoCells, $readFilter !== null); } // set columns/rows attributes $columnsAttributesAreSet = []; foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) { if ( $readFilter === null || !$this->isFilteredColumn($readFilter, $columnCoordinate, $rowsAttributes) ) { if (!isset($columnsAttributesAreSet[$columnCoordinate])) { /** @var array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float, width?: int} $columnAttributes */ $this->setColumnAttributes($columnCoordinate, $columnAttributes); $columnsAttributesAreSet[$columnCoordinate] = true; } } } $rowsAttributesAreSet = []; foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) { if ( $readFilter === null || !$this->isFilteredRow($readFilter, $rowCoordinate, $columnsAttributes) ) { if (!isset($rowsAttributesAreSet[$rowCoordinate])) { /** @var array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float} $rowAttributes */ $this->setRowAttributes($rowCoordinate, $rowAttributes); $rowsAttributesAreSet[$rowCoordinate] = true; } } } return true; } /** @param mixed[] $rowsAttributes */ private function isFilteredColumn(IReadFilter $readFilter, string $columnCoordinate, array $rowsAttributes): bool { foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) { if ($readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) { return false; } } return true; } /** @return mixed[] */ private function readColumnAttributes(SimpleXMLElement $worksheetCols, bool $readDataOnly): array { $columnAttributes = []; foreach ($worksheetCols->col as $columnx) { $column = $columnx->attributes(); if ($column !== null) { $startColumn = Coordinate::stringFromColumnIndex((int) $column['min']); $endColumn = Coordinate::stringFromColumnIndex((int) $column['max']); StringHelper::stringIncrement($endColumn); for ($columnAddress = $startColumn; $columnAddress !== $endColumn; StringHelper::stringIncrement($columnAddress)) { $columnAttributes[$columnAddress] = $this->readColumnRangeAttributes($column, $readDataOnly); if ((int) ($column['max']) === AddressRange::MAX_COLUMN_INT) { break; } } } } return $columnAttributes; } /** @return mixed[] */ private function readColumnRangeAttributes(?SimpleXMLElement $column, bool $readDataOnly): array { $columnAttributes = []; if ($column !== null) { if (isset($column['style']) && !$readDataOnly) { $columnAttributes['xfIndex'] = (int) $column['style']; } if (isset($column['hidden']) && self::boolean($column['hidden'])) { $columnAttributes['visible'] = false; } if (isset($column['collapsed']) && self::boolean($column['collapsed'])) { $columnAttributes['collapsed'] = true; } if (isset($column['outlineLevel']) && ((int) $column['outlineLevel']) > 0) { $columnAttributes['outlineLevel'] = (int) $column['outlineLevel']; } if (isset($column['width'])) { $columnAttributes['width'] = (float) $column['width']; } } return $columnAttributes; } /** @param mixed[] $columnsAttributes */ private function isFilteredRow(IReadFilter $readFilter, int $rowCoordinate, array $columnsAttributes): bool { foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) { if (!$readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) { return true; } } return false; } /** @return mixed[] */ private function readRowAttributes(SimpleXMLElement $worksheetRow, bool $readDataOnly, bool $ignoreRowsWithNoCells, bool $readFilterIsNotNull): array { $rowAttributes = []; foreach ($worksheetRow as $rowx) { $row = $rowx->attributes(); if ($row !== null && (!$ignoreRowsWithNoCells || isset($rowx->c))) { $rowIndex = (int) $row['r']; if (!$readDataOnly) { if (isset($row['ht'])) { $rowAttributes[$rowIndex]['rowHeight'] = (float) $row['ht']; } if (isset($row['customFormat']) && self::boolean($row['customFormat'])) { $rowAttributes[$rowIndex]['customFormat'] = true; } if (isset($row['hidden']) && self::boolean($row['hidden'])) { $rowAttributes[$rowIndex]['visible'] = false; } if (isset($row['collapsed']) && self::boolean($row['collapsed'])) { $rowAttributes[$rowIndex]['collapsed'] = true; } if (isset($row['outlineLevel']) && (int) $row['outlineLevel'] > 0) { $rowAttributes[$rowIndex]['outlineLevel'] = (int) $row['outlineLevel']; } if (isset($row['s'])) { $rowAttributes[$rowIndex]['xfIndex'] = (int) $row['s']; } } if ($readFilterIsNotNull && empty($rowAttributes[$rowIndex])) { $rowAttributes[$rowIndex]['exists'] = true; } } } return $rowAttributes; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php ================================================ worksheet = $workSheet; $this->worksheetXml = $worksheetXml; $this->dxfs = $dxfs; $this->styleReader = $styleReader; } public function load(): void { $selectedCells = $this->worksheet->getSelectedCells(); $this->setConditionalStyles( $this->worksheet, $this->readConditionalStyles($this->worksheetXml), $this->worksheetXml->extLst ); $this->worksheet->setSelectedCells($selectedCells); } public function loadFromExt(): void { $selectedCells = $this->worksheet->getSelectedCells(); $this->ns = $this->worksheetXml->getNamespaces(true); $this->setConditionalsFromExt( $this->readConditionalsFromExt($this->worksheetXml->extLst) ); $this->worksheet->setSelectedCells($selectedCells); } /** @param Conditional[][] $conditionals */ private function setConditionalsFromExt(array $conditionals): void { foreach ($conditionals as $conditionalRange => $cfRules) { ksort($cfRules); // Priority is used as the key for sorting; but may not start at 0, // so we use array_values to reset the index after sorting. $existing = $this->worksheet->getConditionalStylesCollection(); if (array_key_exists($conditionalRange, $existing)) { $conditionalStyle = $existing[$conditionalRange]; $cfRules = array_merge($conditionalStyle, $cfRules); } $this->worksheet->getStyle($conditionalRange) ->setConditionalStyles(array_values($cfRules)); } } /** @return array> */ private function readConditionalsFromExt(SimpleXMLElement $extLst): array { $conditionals = []; if (!isset($extLst->ext)) { return $conditionals; } foreach ($extLst->ext as $extlstcond) { $extAttrs = $extlstcond->attributes() ?? []; $extUri = (string) ($extAttrs['uri'] ?? ''); if ($extUri !== '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { continue; } $conditionalFormattingRuleXml = $extlstcond->children($this->ns['x14']); if (!$conditionalFormattingRuleXml->conditionalFormattings) { return []; } foreach ($conditionalFormattingRuleXml->children($this->ns['x14']) as $extFormattingXml) { $extFormattingRangeXml = $extFormattingXml->children($this->ns['xm']); if (!$extFormattingRangeXml->sqref) { continue; } $sqref = (string) $extFormattingRangeXml->sqref; $extCfRuleXml = $extFormattingXml->cfRule; $attributes = $extCfRuleXml->attributes(); if (!$attributes) { continue; } $conditionType = (string) $attributes->type; if ( !Conditional::isValidConditionType($conditionType) || $conditionType === Conditional::CONDITION_DATABAR ) { continue; } $priority = (int) $attributes->priority; $conditional = $this->readConditionalRuleFromExt($extCfRuleXml, $attributes); $cfStyle = $this->readStyleFromExt($extCfRuleXml); $conditional->setStyle($cfStyle); $conditionals[$sqref][$priority] = $conditional; } } return $conditionals; } private function readConditionalRuleFromExt(SimpleXMLElement $cfRuleXml, SimpleXMLElement $attributes): Conditional { $conditionType = (string) $attributes->type; $operatorType = (string) $attributes->operator; $priority = (int) (string) $attributes->priority; $stopIfTrue = (int) (string) $attributes->stopIfTrue; $operands = []; foreach ($cfRuleXml->children($this->ns['xm']) as $cfRuleOperandsXml) { $operands[] = (string) $cfRuleOperandsXml; } $conditional = new Conditional(); $conditional->setConditionType($conditionType); $conditional->setOperatorType($operatorType); $conditional->setPriority($priority); $conditional->setStopIfTrue($stopIfTrue === 1); if ( $conditionType === Conditional::CONDITION_CONTAINSTEXT || $conditionType === Conditional::CONDITION_NOTCONTAINSTEXT || $conditionType === Conditional::CONDITION_BEGINSWITH || $conditionType === Conditional::CONDITION_ENDSWITH || $conditionType === Conditional::CONDITION_TIMEPERIOD ) { $conditional->setText(array_pop($operands) ?? ''); } $conditional->setConditions($operands); return $conditional; } private function readStyleFromExt(SimpleXMLElement $extCfRuleXml): Style { $cfStyle = new Style(false, true); if ($extCfRuleXml->dxf) { $styleXML = $extCfRuleXml->dxf->children(); if ($styleXML->borders) { $this->styleReader->readBorderStyle($cfStyle->getBorders(), $styleXML->borders); } if ($styleXML->fill) { $this->styleReader->readFillStyle($cfStyle->getFill(), $styleXML->fill); } if ($styleXML->font) { $this->styleReader->readFontStyle($cfStyle->getFont(), $styleXML->font); } } return $cfStyle; } /** @return mixed[] */ private function readConditionalStyles(SimpleXMLElement $xmlSheet): array { $conditionals = []; foreach ($xmlSheet->conditionalFormatting as $conditional) { foreach ($conditional->cfRule as $cfRule) { if (Conditional::isValidConditionType((string) $cfRule['type']) && (!isset($cfRule['dxfId']) || isset($this->dxfs[(int) ($cfRule['dxfId'])]))) { $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; } elseif ((string) $cfRule['type'] == Conditional::CONDITION_DATABAR) { $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; } } } return $conditionals; } /** @param mixed[] $conditionals */ private function setConditionalStyles(Worksheet $worksheet, array $conditionals, SimpleXMLElement $xmlExtLst): void { foreach ($conditionals as $cellRangeReference => $cfRules) { /** @var mixed[] $cfRules */ ksort($cfRules); // no longer needed for Xlsx, but helps Xls $conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst); // Extract all cell references in $cellRangeReference // N.B. In Excel UI, intersection is space and union is comma. // But in Xml, intersection is comma and union is space. $cellRangeReference = str_replace(['$', ' ', ',', '^'], ['', '^', ' ', ','], strtoupper($cellRangeReference)); foreach ($conditionalStyles as $cs) { $scale = $cs->getColorScale(); if ($scale !== null) { $scale->setSqRef($cellRangeReference, $worksheet); } } $worksheet->getStyle($cellRangeReference)->setConditionalStyles($conditionalStyles); } } /** * @param mixed[] $cfRules * * @return Conditional[] */ private function readStyleRules(array $cfRules, SimpleXMLElement $extLst): array { /** @var ConditionalFormattingRuleExtension[] */ $conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst); $conditionalStyles = []; /** @var SimpleXMLElement $cfRule */ foreach ($cfRules as $cfRule) { $objConditional = new Conditional(); $objConditional->setConditionType((string) $cfRule['type']); $objConditional->setOperatorType((string) $cfRule['operator']); $objConditional->setPriority((int) (string) $cfRule['priority']); $objConditional->setNoFormatSet(!isset($cfRule['dxfId'])); if ((string) $cfRule['text'] != '') { $objConditional->setText((string) $cfRule['text']); } elseif ((string) $cfRule['timePeriod'] != '') { $objConditional->setText((string) $cfRule['timePeriod']); } if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) { $objConditional->setStopIfTrue(true); } if (count($cfRule->formula) >= 1) { foreach ($cfRule->formula as $formulax) { $formula = (string) $formulax; $formula = str_replace(['_xlfn.', '_xlws.'], '', $formula); if ($formula === 'TRUE') { $objConditional->addCondition(true); } elseif ($formula === 'FALSE') { $objConditional->addCondition(false); } else { $objConditional->addCondition($formula); } } } else { $objConditional->addCondition(''); } if (isset($cfRule->dataBar)) { $objConditional->setDataBar( $this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions) ); } elseif (isset($cfRule->colorScale)) { $objConditional->setColorScale( $this->readColorScale($cfRule) ); } elseif (isset($cfRule->iconSet)) { $objConditional->setIconSet($this->readIconSet($cfRule)); } elseif (isset($cfRule['dxfId'])) { $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); } $conditionalStyles[] = $objConditional; } return $conditionalStyles; } /** @param ConditionalFormattingRuleExtension[] $conditionalFormattingRuleExtensions */ private function readDataBarOfConditionalRule(SimpleXMLElement $cfRule, array $conditionalFormattingRuleExtensions): ConditionalDataBar { $dataBar = new ConditionalDataBar(); //dataBar attribute if (isset($cfRule->dataBar['showValue'])) { $dataBar->setShowValue((bool) $cfRule->dataBar['showValue']); } //dataBar children //conditionalFormatValueObjects $cfvoXml = $cfRule->dataBar->cfvo; $cfvoIndex = 0; foreach ((count($cfvoXml) > 1 ? $cfvoXml : [$cfvoXml]) as $cfvo) { //* @phpstan-ignore-line /** @var SimpleXMLElement $cfvo */ if ($cfvoIndex === 0) { $dataBar->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); } if ($cfvoIndex === 1) { $dataBar->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); } ++$cfvoIndex; } //color if (isset($cfRule->dataBar->color)) { $dataBar->setColor($this->styleReader->readColor($cfRule->dataBar->color)); } //extLst $this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions); return $dataBar; } private function readColorScale(SimpleXMLElement|stdClass $cfRule): ConditionalColorScale { $colorScale = new ConditionalColorScale(); /** @var SimpleXMLElement $cfRule */ $count = count($cfRule->colorScale->cfvo); $idx = 0; foreach ($cfRule->colorScale->cfvo as $cfvoXml) { $attr = $cfvoXml->attributes() ?? []; $type = (string) ($attr['type'] ?? ''); $val = $attr['val'] ?? null; if ($idx === 0) { $method = 'setMinimumConditionalFormatValueObject'; } elseif ($idx === 1 && $count === 3) { $method = 'setMidpointConditionalFormatValueObject'; } else { $method = 'setMaximumConditionalFormatValueObject'; } if ($type !== 'formula') { $colorScale->$method(new ConditionalFormatValueObject($type, $val)); } else { $colorScale->$method(new ConditionalFormatValueObject($type, null, $val)); } ++$idx; } $idx = 0; foreach ($cfRule->colorScale->color as $color) { $rgb = $this->styleReader->readColor($color); if ($idx === 0) { $colorScale->setMinimumColor(new Color($rgb)); } elseif ($idx === 1 && $count === 3) { $colorScale->setMidpointColor(new Color($rgb)); } else { $colorScale->setMaximumColor(new Color($rgb)); } ++$idx; } return $colorScale; } private function readIconSet(SimpleXMLElement $cfRule): ConditionalIconSet { $iconSet = new ConditionalIconSet(); if (isset($cfRule->iconSet['iconSet'])) { $iconSet->setIconSetType(IconSetValues::from($cfRule->iconSet['iconSet'])); } if (isset($cfRule->iconSet['reverse'])) { $iconSet->setReverse('1' === (string) $cfRule->iconSet['reverse']); } if (isset($cfRule->iconSet['showValue'])) { $iconSet->setShowValue('1' === (string) $cfRule->iconSet['showValue']); } if (isset($cfRule->iconSet['custom'])) { $iconSet->setCustom('1' === (string) $cfRule->iconSet['custom']); } $cfvos = []; foreach ($cfRule->iconSet->cfvo as $cfvoXml) { $type = (string) $cfvoXml['type']; $value = (string) ($cfvoXml['val'] ?? ''); $cfvo = new ConditionalFormatValueObject($type, $value); if (isset($cfvoXml['gte'])) { $cfvo->setGreaterThanOrEqual('1' === (string) $cfvoXml['gte']); } $cfvos[] = $cfvo; } $iconSet->setCfvos($cfvos); // TODO: The cfIcon element is not implemented yet. return $iconSet; } /** @param ConditionalFormattingRuleExtension[] $conditionalFormattingRuleExtensions */ private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, SimpleXMLElement $cfRule, array $conditionalFormattingRuleExtensions): void { if (isset($cfRule->extLst)) { $ns = $cfRule->extLst->getNamespaces(true); foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) { //* @phpstan-ignore-line /** @var SimpleXMLElement $ext */ $extId = (string) $ext->children($ns['x14'])->id; if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') { $dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]); } } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php ================================================ worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } public function load(): void { foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) { // Uppercase coordinate $range = strtoupper((string) $dataValidation['sqref']); $rangeSet = explode(' ', $range); foreach ($rangeSet as $range) { if (preg_match('/^[A-Z]{1,3}\d{1,7}/', $range, $matches) === 1) { // Ensure left/top row of range exists, thereby // adjusting high row/column. $this->worksheet->getCell($matches[0]); } } } foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) { // Uppercase coordinate $range = strtoupper((string) $dataValidation['sqref']); $docValidation = new DataValidation(); $docValidation->setType((string) $dataValidation['type']); $docValidation->setErrorStyle((string) $dataValidation['errorStyle']); $docValidation->setOperator((string) $dataValidation['operator']); $docValidation->setAllowBlank(filter_var($dataValidation['allowBlank'], FILTER_VALIDATE_BOOLEAN)); // showDropDown is inverted (works as hideDropDown if true) $docValidation->setShowDropDown(!filter_var($dataValidation['showDropDown'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setShowInputMessage(filter_var($dataValidation['showInputMessage'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setShowErrorMessage(filter_var($dataValidation['showErrorMessage'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setErrorTitle((string) $dataValidation['errorTitle']); $docValidation->setError((string) $dataValidation['error']); $docValidation->setPromptTitle((string) $dataValidation['promptTitle']); $docValidation->setPrompt((string) $dataValidation['prompt']); $docValidation->setFormula1(Xlsx::replacePrefixes((string) $dataValidation->formula1)); $docValidation->setFormula2(Xlsx::replacePrefixes((string) $dataValidation->formula2)); $this->worksheet->setDataValidation($range, $docValidation); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php ================================================ worksheet = $workSheet; } public function readHyperlinks(SimpleXMLElement $relsWorksheet): void { foreach ($relsWorksheet->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) { $element = Xlsx::getAttributes($elementx); if ($element->Type == Namespaces::HYPERLINK) { $this->hyperlinks[(string) $element->Id] = (string) $element->Target; } } } public function setHyperlinks(SimpleXMLElement $worksheetXml): void { foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) { $this->setHyperlink($hyperlink, $this->worksheet); } } private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void { // Link url $linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT); $attributes = Xlsx::getAttributes($hyperlink); foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) { $cell = $worksheet->getCell($cellReference); if (isset($attributes['location'])) { $cell->getHyperlink()->setUrl('sheet://' . (string) $attributes['location']); } elseif (isset($linkRel['id'])) { $hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? ''; $cell->getHyperlink()->setUrl($hyperlinkUrl); } // Tooltip if (isset($attributes['tooltip'])) { $cell->getHyperlink()->setTooltip((string) $attributes['tooltip']); } if (isset($attributes['display'])) { $cell->getHyperlink()->setDisplay((string) $attributes['display']); } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php ================================================ worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } /** * @param mixed[] $unparsedLoadedData * * @return mixed[] */ public function load(array $unparsedLoadedData): array { $worksheetXml = $this->worksheetXml; if ($worksheetXml === null) { return $unparsedLoadedData; } $this->margins($worksheetXml, $this->worksheet); $unparsedLoadedData = $this->pageSetup($worksheetXml, $this->worksheet, $unparsedLoadedData); $this->headerFooter($worksheetXml, $this->worksheet); $this->pageBreaks($worksheetXml, $this->worksheet); return $unparsedLoadedData; } private function margins(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->pageMargins) { $docPageMargins = $worksheet->getPageMargins(); $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left'])); $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right'])); $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top'])); $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom'])); $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header'])); $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer'])); } } /** * @param mixed[] $unparsedLoadedData * * @return mixed[] */ private function pageSetup(SimpleXMLElement $xmlSheet, Worksheet $worksheet, array $unparsedLoadedData): array { if ($xmlSheet->pageSetup) { $docPageSetup = $worksheet->getPageSetup(); if (isset($xmlSheet->pageSetup['orientation'])) { $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']); } if (isset($xmlSheet->pageSetup['paperSize'])) { $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize'])); } if (isset($xmlSheet->pageSetup['scale'])) { $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false); } if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) { $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false); } if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) { $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false); } if ( isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) && self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber']) ) { $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber'])); } if (isset($xmlSheet->pageSetup['pageOrder'])) { $docPageSetup->setPageOrder((string) $xmlSheet->pageSetup['pageOrder']); } $relAttributes = $xmlSheet->pageSetup->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT); if (isset($relAttributes['id'])) { $relid = (string) $relAttributes['id']; if (!str_ends_with($relid, 'ps')) { $relid .= 'ps'; } /** @var mixed[][][] $unparsedLoadedData */ $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = $relid; } } return $unparsedLoadedData; } private function headerFooter(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->headerFooter) { $docHeaderFooter = $worksheet->getHeaderFooter(); if ( isset($xmlSheet->headerFooter['differentOddEven']) && self::boolean((string) $xmlSheet->headerFooter['differentOddEven']) ) { $docHeaderFooter->setDifferentOddEven(true); } else { $docHeaderFooter->setDifferentOddEven(false); } if ( isset($xmlSheet->headerFooter['differentFirst']) && self::boolean((string) $xmlSheet->headerFooter['differentFirst']) ) { $docHeaderFooter->setDifferentFirst(true); } else { $docHeaderFooter->setDifferentFirst(false); } if ( isset($xmlSheet->headerFooter['scaleWithDoc']) && !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc']) ) { $docHeaderFooter->setScaleWithDocument(false); } else { $docHeaderFooter->setScaleWithDocument(true); } if ( isset($xmlSheet->headerFooter['alignWithMargins']) && !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins']) ) { $docHeaderFooter->setAlignWithMargins(false); } else { $docHeaderFooter->setAlignWithMargins(true); } $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader); $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter); $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader); $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter); $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader); $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter); } } private function pageBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk) { $this->rowBreaks($xmlSheet, $worksheet); } if ($xmlSheet->colBreaks && $xmlSheet->colBreaks->brk) { $this->columnBreaks($xmlSheet, $worksheet); } } private function rowBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { foreach ($xmlSheet->rowBreaks->brk as $brk) { $rowBreakMax = /*isset($brk['max']) ? ((int) $brk['max']) :*/ -1; if ($brk['man']) { $worksheet->setBreak("A{$brk['id']}", Worksheet::BREAK_ROW, $rowBreakMax); } } } private function columnBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { foreach ($xmlSheet->colBreaks->brk as $brk) { if ($brk['man']) { $worksheet->setBreak( Coordinate::stringFromColumnIndex(((int) $brk['id']) + 1) . '1', Worksheet::BREAK_COLUMN ); } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/Properties.php ================================================ securityScanner = $securityScanner; $this->docProps = $docProps; } private function extractPropertyData(string $propertyData): ?SimpleXMLElement { // okay to omit namespace because everything will be processed by xpath $obj = simplexml_load_string( $this->securityScanner->scan($propertyData) ); return $obj === false ? null : $obj; } public function readCoreProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { $xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS); $xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS); $xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2); $this->docProps->setCreator($this->getArrayItem($xmlCore->xpath('dc:creator'))); $this->docProps->setLastModifiedBy($this->getArrayItem($xmlCore->xpath('cp:lastModifiedBy'))); $this->docProps->setCreated($this->getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type $this->docProps->setModified($this->getArrayItem($xmlCore->xpath('dcterms:modified'))); //! respect xsi:type $this->docProps->setTitle($this->getArrayItem($xmlCore->xpath('dc:title'))); $this->docProps->setDescription($this->getArrayItem($xmlCore->xpath('dc:description'))); $this->docProps->setSubject($this->getArrayItem($xmlCore->xpath('dc:subject'))); $this->docProps->setKeywords($this->getArrayItem($xmlCore->xpath('cp:keywords'))); $this->docProps->setCategory($this->getArrayItem($xmlCore->xpath('cp:category'))); } } public function readExtendedProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { if (isset($xmlCore->Company)) { $this->docProps->setCompany((string) $xmlCore->Company); } if (isset($xmlCore->Manager)) { $this->docProps->setManager((string) $xmlCore->Manager); } if (isset($xmlCore->HyperlinkBase)) { $this->docProps->setHyperlinkBase((string) $xmlCore->HyperlinkBase); } } } public function readCustomProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { foreach ($xmlCore as $xmlProperty) { /** @var SimpleXMLElement $xmlProperty */ $cellDataOfficeAttributes = $xmlProperty->attributes(); if (isset($cellDataOfficeAttributes['name'])) { $propertyName = (string) $cellDataOfficeAttributes['name']; $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); $attributeType = $cellDataOfficeChildren->getName(); /** @var SimpleXMLElement */ $attributeValue = $cellDataOfficeChildren->{$attributeType}; $attributeValue = (string) $attributeValue; $attributeValue = DocumentProperties::convertProperty($attributeValue, $attributeType); $attributeType = DocumentProperties::convertPropertyType($attributeType); $this->docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); } } } } /** @param null|false|scalar[] $array */ private function getArrayItem(null|array|false $array): string { return is_array($array) ? (string) ($array[0] ?? '') : ''; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/SharedFormula.php ================================================ master = $master; $this->formula = $formula; } public function master(): string { return $this->master; } public function formula(): string { return $this->formula; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php ================================================ worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } public function load(bool $readDataOnly, Styles $styleReader): void { if ($this->worksheetXml === null) { return; } if (isset($this->worksheetXml->sheetPr)) { $sheetPr = $this->worksheetXml->sheetPr; $this->tabColor($sheetPr, $styleReader); $this->codeName($sheetPr); $this->outlines($sheetPr); $this->pageSetup($sheetPr); } if (isset($this->worksheetXml->sheetFormatPr)) { $this->sheetFormat($this->worksheetXml->sheetFormatPr); } if (!$readDataOnly && isset($this->worksheetXml->printOptions)) { $this->printOptions($this->worksheetXml->printOptions); } } private function tabColor(SimpleXMLElement $sheetPr, Styles $styleReader): void { if (isset($sheetPr->tabColor)) { $this->worksheet->getTabColor()->setARGB($styleReader->readColor($sheetPr->tabColor)); } } private function codeName(SimpleXMLElement $sheetPrx): void { $sheetPr = $sheetPrx->attributes() ?? []; if (isset($sheetPr['codeName'])) { $this->worksheet->setCodeName((string) $sheetPr['codeName'], false); } } private function outlines(SimpleXMLElement $sheetPr): void { if (isset($sheetPr->outlinePr)) { $attr = $sheetPr->outlinePr->attributes() ?? []; if ( isset($attr['summaryRight']) && !self::boolean((string) $attr['summaryRight']) ) { $this->worksheet->setShowSummaryRight(false); } else { $this->worksheet->setShowSummaryRight(true); } if ( isset($attr['summaryBelow']) && !self::boolean((string) $attr['summaryBelow']) ) { $this->worksheet->setShowSummaryBelow(false); } else { $this->worksheet->setShowSummaryBelow(true); } } } private function pageSetup(SimpleXMLElement $sheetPr): void { if (isset($sheetPr->pageSetUpPr)) { $attr = $sheetPr->pageSetUpPr->attributes() ?? []; if ( isset($attr['fitToPage']) && !self::boolean((string) $attr['fitToPage']) ) { $this->worksheet->getPageSetup()->setFitToPage(false); } else { $this->worksheet->getPageSetup()->setFitToPage(true); } } } private function sheetFormat(SimpleXMLElement $sheetFormatPrx): void { $sheetFormatPr = $sheetFormatPrx->attributes() ?? []; if ( isset($sheetFormatPr['customHeight']) && self::boolean((string) $sheetFormatPr['customHeight']) && isset($sheetFormatPr['defaultRowHeight']) ) { $this->worksheet->getDefaultRowDimension() ->setRowHeight((float) $sheetFormatPr['defaultRowHeight']); } if (isset($sheetFormatPr['defaultColWidth'])) { $this->worksheet->getDefaultColumnDimension() ->setWidth((float) $sheetFormatPr['defaultColWidth']); } if ( isset($sheetFormatPr['zeroHeight']) && ((string) $sheetFormatPr['zeroHeight'] === '1') ) { $this->worksheet->getDefaultRowDimension()->setZeroHeight(true); } } private function printOptions(SimpleXMLElement $printOptionsx): void { $printOptions = $printOptionsx->attributes() ?? []; // Spec is weird. gridLines (default false) // and gridLinesSet (default true) must both be true. if (isset($printOptions['gridLines']) && self::boolean((string) $printOptions['gridLines'])) { if (!isset($printOptions['gridLinesSet']) || self::boolean((string) $printOptions['gridLinesSet'])) { $this->worksheet->setPrintGridlines(true); } } if (isset($printOptions['horizontalCentered']) && self::boolean((string) $printOptions['horizontalCentered'])) { $this->worksheet->getPageSetup()->setHorizontalCentered(true); } if (isset($printOptions['verticalCentered']) && self::boolean((string) $printOptions['verticalCentered'])) { $this->worksheet->getPageSetup()->setVerticalCentered(true); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php ================================================ sheetViewXml = $sheetViewXml; $this->sheetViewAttributes = Xlsx::testSimpleXml($sheetViewXml->attributes()); $this->worksheet = $workSheet; } public function load(): void { $this->topLeft(); $this->zoomScale(); $this->view(); $this->gridLines(); $this->headers(); $this->direction(); $this->showZeros(); $usesPanes = false; if (isset($this->sheetViewXml->pane)) { $this->pane(); $usesPanes = true; } if (isset($this->sheetViewXml->selection)) { foreach ($this->sheetViewXml->selection as $selection) { $this->selection($selection, $usesPanes); } } } private function zoomScale(): void { if (isset($this->sheetViewAttributes->zoomScale)) { $zoomScale = (int) ($this->sheetViewAttributes->zoomScale); if ($zoomScale <= 0) { // setZoomScale will throw an Exception if the scale is less than or equals 0 // that is OK when manually creating documents, but we should be able to read all documents $zoomScale = 100; } $this->worksheet->getSheetView()->setZoomScale($zoomScale); } if (isset($this->sheetViewAttributes->zoomScaleNormal)) { $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleNormal); if ($zoomScaleNormal <= 0) { // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0 // that is OK when manually creating documents, but we should be able to read all documents $zoomScaleNormal = 100; } $this->worksheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal); } if (isset($this->sheetViewAttributes->zoomScalePageLayoutView)) { $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScalePageLayoutView); if ($zoomScaleNormal > 0) { $this->worksheet->getSheetView()->setZoomScalePageLayoutView($zoomScaleNormal); } } if (isset($this->sheetViewAttributes->zoomScaleSheetLayoutView)) { $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleSheetLayoutView); if ($zoomScaleNormal > 0) { $this->worksheet->getSheetView()->setZoomScaleSheetLayoutView($zoomScaleNormal); } } } private function view(): void { if (isset($this->sheetViewAttributes->view)) { $this->worksheet->getSheetView()->setView((string) $this->sheetViewAttributes->view); } } private function topLeft(): void { if (isset($this->sheetViewAttributes->topLeftCell)) { $this->worksheet->setTopLeftCell($this->sheetViewAttributes->topLeftCell); } } private function gridLines(): void { if (isset($this->sheetViewAttributes->showGridLines)) { $this->worksheet->setShowGridLines( self::boolean((string) $this->sheetViewAttributes->showGridLines) ); } } private function headers(): void { if (isset($this->sheetViewAttributes->showRowColHeaders)) { $this->worksheet->setShowRowColHeaders( self::boolean((string) $this->sheetViewAttributes->showRowColHeaders) ); } } private function direction(): void { if (isset($this->sheetViewAttributes->rightToLeft)) { $this->worksheet->setRightToLeft( self::boolean((string) $this->sheetViewAttributes->rightToLeft) ); } } private function showZeros(): void { if (isset($this->sheetViewAttributes->showZeros)) { $this->worksheet->getSheetView()->setShowZeros( self::boolean((string) $this->sheetViewAttributes->showZeros) ); } } private function pane(): void { $xSplit = 0; $ySplit = 0; $topLeftCell = null; $paneAttributes = $this->sheetViewXml->pane->attributes(); if (isset($paneAttributes->xSplit)) { $xSplit = (int) ($paneAttributes->xSplit); $this->worksheet->setXSplit($xSplit); } if (isset($paneAttributes->ySplit)) { $ySplit = (int) ($paneAttributes->ySplit); $this->worksheet->setYSplit($ySplit); } $paneState = isset($paneAttributes->state) ? ((string) $paneAttributes->state) : ''; $this->worksheet->setPaneState($paneState); if (isset($paneAttributes->topLeftCell)) { $topLeftCell = (string) $paneAttributes->topLeftCell; $this->worksheet->setPaneTopLeftCell($topLeftCell); if ($paneState === Worksheet::PANE_FROZEN) { $this->worksheet->setTopLeftCell($topLeftCell); } } $activePane = isset($paneAttributes->activePane) ? ((string) $paneAttributes->activePane) : 'topLeft'; $this->worksheet->setActivePane($activePane); $this->activePane = $activePane; if ($paneState === Worksheet::PANE_FROZEN || $paneState === Worksheet::PANE_FROZENSPLIT) { $this->worksheet->freezePane( Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell, $paneState === Worksheet::PANE_FROZENSPLIT ); } } private function selection(?SimpleXMLElement $selection, bool $usesPanes): void { $attributes = ($selection === null) ? null : $selection->attributes(); if ($attributes !== null) { $position = (string) $attributes->pane; if ($usesPanes && $position === '') { $position = 'topLeft'; } $activeCell = (string) $attributes->activeCell; $sqref = (string) $attributes->sqref; $sqref = explode(' ', $sqref); $sqref = $sqref[0]; if ($position === '') { $this->worksheet->setSelectedCells($sqref); } else { $pane = new Pane($position, $sqref, $activeCell); $this->worksheet->setPane($position, $pane); if ($position === $this->activePane && $sqref !== '') { $this->worksheet->setSelectedCells($sqref); } } } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/Styles.php ================================================ */ private array $cellStyles = []; private SimpleXMLElement $styleXml; private string $namespace = ''; /** @var array */ private array $fontCharsets = []; /** @return array */ public function getFontCharsets(): array { return $this->fontCharsets; } public function setNamespace(string $namespace): void { $this->namespace = $namespace; } /** @param string[] $palette */ public function setWorkbookPalette(array $palette): void { $this->workbookPalette = $palette; } private function getStyleAttributes(SimpleXMLElement $value): SimpleXMLElement { $attr = $value->attributes(''); if ($attr === null || count($attr) === 0) { $attr = $value->attributes($this->namespace); } return Xlsx::testSimpleXml($attr); } public function setStyleXml(SimpleXMLElement $styleXml): void { $this->styleXml = $styleXml; } public function setTheme(Theme $theme): void { $this->theme = $theme; } /** * @param mixed[] $styles * @param array $cellStyles */ public function setStyleBaseData(?Theme $theme = null, array $styles = [], array $cellStyles = []): void { $this->theme = $theme; $this->styles = $styles; $this->cellStyles = $cellStyles; } public function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void { if (isset($fontStyleXml->name)) { $attr = $this->getStyleAttributes($fontStyleXml->name); if (isset($attr['val'])) { $fontStyle->setName((string) $attr['val']); } if (isset($fontStyleXml->charset)) { $charsetAttr = $this->getStyleAttributes($fontStyleXml->charset); if (isset($charsetAttr['val'])) { $charsetVal = (int) $charsetAttr['val']; $this->fontCharsets[$fontStyle->getName()] = $charsetVal; } } } if (isset($fontStyleXml->sz)) { $attr = $this->getStyleAttributes($fontStyleXml->sz); if (isset($attr['val'])) { $fontStyle->setSize((float) $attr['val']); } } if (isset($fontStyleXml->b)) { $attr = $this->getStyleAttributes($fontStyleXml->b); $fontStyle->setBold(!isset($attr['val']) || self::boolean((string) $attr['val'])); } if (isset($fontStyleXml->i)) { $attr = $this->getStyleAttributes($fontStyleXml->i); $fontStyle->setItalic(!isset($attr['val']) || self::boolean((string) $attr['val'])); } if (isset($fontStyleXml->strike)) { $attr = $this->getStyleAttributes($fontStyleXml->strike); $fontStyle->setStrikethrough(!isset($attr['val']) || self::boolean((string) $attr['val'])); } $fontStyle->getColor() ->setARGB( $this->readColor($fontStyleXml->color) ); $theme = $this->readColorTheme($fontStyleXml->color); if ($theme >= 0) { $fontStyle->getColor()->setTheme($theme); } if (isset($fontStyleXml->u)) { $attr = $this->getStyleAttributes($fontStyleXml->u); if (!isset($attr['val'])) { $fontStyle->setUnderline(Font::UNDERLINE_SINGLE); } else { $fontStyle->setUnderline((string) $attr['val']); } } if (isset($fontStyleXml->vertAlign)) { $attr = $this->getStyleAttributes($fontStyleXml->vertAlign); if (isset($attr['val'])) { $verticalAlign = strtolower((string) $attr['val']); if ($verticalAlign === 'superscript') { $fontStyle->setSuperscript(true); } elseif ($verticalAlign === 'subscript') { $fontStyle->setSubscript(true); } } } if (isset($fontStyleXml->scheme)) { $attr = $this->getStyleAttributes($fontStyleXml->scheme); $fontStyle->setScheme((string) $attr['val']); } if (isset($fontStyleXml->auto)) { $attr = $this->getStyleAttributes($fontStyleXml->auto); if (isset($attr['val'])) { $fontStyle->setAutoColor(self::boolean((string) $attr['val'])); } } } private function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void { if ((string) $numfmtStyleXml['formatCode'] !== '') { $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmtStyleXml['formatCode'])); return; } $numfmt = $this->getStyleAttributes($numfmtStyleXml); if (isset($numfmt['formatCode'])) { $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmt['formatCode'])); } } public function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void { if ($fillStyleXml->gradientFill) { /** @var SimpleXMLElement $gradientFill */ $gradientFill = $fillStyleXml->gradientFill[0]; $attr = $this->getStyleAttributes($gradientFill); if (!empty($attr['type'])) { $fillStyle->setFillType((string) $attr['type']); } $fillStyle->setRotation((float) ($attr['degree'])); $gradientFill->registerXPathNamespace('sml', Namespaces::MAIN); $fillStyle->getStartColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); //* @phpstan-ignore-line $fillStyle->getEndColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); //* @phpstan-ignore-line } elseif ($fillStyleXml->patternFill) { $defaultFillStyle = ($fillStyle->getFillType() !== null) ? Fill::FILL_NONE : ''; $fgFound = false; $bgFound = false; if ($fillStyleXml->patternFill->fgColor) { $fillStyle->getStartColor()->setARGB($this->readColor($fillStyleXml->patternFill->fgColor, true)); if ($fillStyle->getFillType() !== null) { $defaultFillStyle = Fill::FILL_SOLID; } $fgFound = true; } if ($fillStyleXml->patternFill->bgColor) { $fillStyle->getEndColor()->setARGB($this->readColor($fillStyleXml->patternFill->bgColor, true)); if ($fillStyle->getFillType() !== null) { $defaultFillStyle = Fill::FILL_SOLID; } $bgFound = true; } $type = ''; if ((string) $fillStyleXml->patternFill['patternType'] !== '') { $type = (string) $fillStyleXml->patternFill['patternType']; } else { $attr = $this->getStyleAttributes($fillStyleXml->patternFill); $type = (string) $attr['patternType']; } $patternType = ($type === '') ? $defaultFillStyle : $type; $fillStyle->setFillType($patternType); if ( !$fgFound // no foreground color specified && !in_array($patternType, [Fill::FILL_NONE, Fill::FILL_SOLID], true) // these patterns aren't relevant && $fillStyle->getStartColor()->getARGB() // not conditional ) { $fillStyle->getStartColor() ->setARGB('', true); } if ( !$bgFound // no background color specified && !in_array($patternType, [Fill::FILL_NONE, Fill::FILL_SOLID], true) // these patterns aren't relevant && $fillStyle->getEndColor()->getARGB() // not conditional ) { $fillStyle->getEndColor() ->setARGB('', true); } } } public function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void { $diagonalUp = $this->getAttribute($borderStyleXml, 'diagonalUp'); $diagonalUp = self::boolean($diagonalUp); $diagonalDown = $this->getAttribute($borderStyleXml, 'diagonalDown'); $diagonalDown = self::boolean($diagonalDown); if ($diagonalUp === false) { if ($diagonalDown === false) { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_NONE); } else { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_DOWN); } } elseif ($diagonalDown === false) { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_UP); } else { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_BOTH); } if (isset($borderStyleXml->left)) { $this->readBorder($borderStyle->getLeft(), $borderStyleXml->left); } if (isset($borderStyleXml->right)) { $this->readBorder($borderStyle->getRight(), $borderStyleXml->right); } if (isset($borderStyleXml->top)) { $this->readBorder($borderStyle->getTop(), $borderStyleXml->top); } if (isset($borderStyleXml->bottom)) { $this->readBorder($borderStyle->getBottom(), $borderStyleXml->bottom); } if (isset($borderStyleXml->diagonal)) { $this->readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal); } } private function getAttribute(SimpleXMLElement $xml, string $attribute): string { $style = ''; if ((string) $xml[$attribute] !== '') { $style = (string) $xml[$attribute]; } else { $attr = $this->getStyleAttributes($xml); if (isset($attr[$attribute])) { $style = (string) $attr[$attribute]; } } return $style; } private function readBorder(Border $border, SimpleXMLElement $borderXml): void { $style = $this->getAttribute($borderXml, 'style'); if ($style !== '') { $border->setBorderStyle((string) $style); } else { $border->setBorderStyle(Border::BORDER_NONE); } if (isset($borderXml->color)) { $border->getColor()->setARGB($this->readColor($borderXml->color)); } } public function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void { $horizontal = (string) $this->getAttribute($alignmentXml, 'horizontal'); if ($horizontal !== '') { $alignment->setHorizontal($horizontal); } $justifyLastLine = (string) $this->getAttribute($alignmentXml, 'justifyLastLine'); if ($justifyLastLine !== '') { $alignment->setJustifyLastLine( self::boolean($justifyLastLine) ); } $vertical = (string) $this->getAttribute($alignmentXml, 'vertical'); if ($vertical !== '') { $alignment->setVertical($vertical); } $textRotation = (int) $this->getAttribute($alignmentXml, 'textRotation'); if ($textRotation > 90) { $textRotation = 90 - $textRotation; } $alignment->setTextRotation($textRotation); $wrapText = $this->getAttribute($alignmentXml, 'wrapText'); $alignment->setWrapText(self::boolean((string) $wrapText)); $shrinkToFit = $this->getAttribute($alignmentXml, 'shrinkToFit'); $alignment->setShrinkToFit(self::boolean((string) $shrinkToFit)); $indent = (int) $this->getAttribute($alignmentXml, 'indent'); $alignment->setIndent(max($indent, 0)); $readingOrder = (int) $this->getAttribute($alignmentXml, 'readingOrder'); $alignment->setReadOrder(max($readingOrder, 0)); } private static function formatGeneral(string $formatString): string { if ($formatString === 'GENERAL') { $formatString = NumberFormat::FORMAT_GENERAL; } return $formatString; } /** * Read style. */ public function readStyle(Style $docStyle, SimpleXMLElement|stdClass $style): void { if ($style instanceof SimpleXMLElement) { $this->readNumberFormat($docStyle->getNumberFormat(), $style->numFmt); } else { /** @var SimpleXMLElement */ $temp = $style->numFmt; $docStyle->getNumberFormat()->setFormatCode(self::formatGeneral((string) $temp)); } /** @var SimpleXMLElement $style */ if (isset($style->font)) { $this->readFontStyle($docStyle->getFont(), $style->font); } if (isset($style->fill)) { $this->readFillStyle($docStyle->getFill(), $style->fill); } if (isset($style->border)) { $this->readBorderStyle($docStyle->getBorders(), $style->border); } if (isset($style->alignment)) { $this->readAlignmentStyle($docStyle->getAlignment(), $style->alignment); } // protection if (isset($style->protection)) { $this->readProtectionLocked($docStyle, $style->protection); $this->readProtectionHidden($docStyle, $style->protection); } // top-level style settings if (isset($style->quotePrefix)) { $docStyle->setQuotePrefix((bool) $style->quotePrefix); } } /** * Read protection locked attribute. */ public function readProtectionLocked(Style $docStyle, SimpleXMLElement $style): void { $locked = ''; if ((string) $style['locked'] !== '') { $locked = (string) $style['locked']; } else { $attr = $this->getStyleAttributes($style); if (isset($attr['locked'])) { $locked = (string) $attr['locked']; } } if ($locked !== '') { if (self::boolean($locked)) { $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED); } else { $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); } } } /** * Read protection hidden attribute. */ public function readProtectionHidden(Style $docStyle, SimpleXMLElement $style): void { $hidden = ''; if ((string) $style['hidden'] !== '') { $hidden = (string) $style['hidden']; } else { $attr = $this->getStyleAttributes($style); if (isset($attr['hidden'])) { $hidden = (string) $attr['hidden']; } } if ($hidden !== '') { if (self::boolean((string) $hidden)) { $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED); } else { $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED); } } } public function readColorTheme(SimpleXMLElement $color): int { $attr = $this->getStyleAttributes($color); $retVal = -1; if (isset($attr['theme']) && is_numeric((string) $attr['theme']) && !isset($attr['tint'])) { $retVal = (int) $attr['theme']; } return $retVal; } public function readColor(SimpleXMLElement $color, bool $background = false): string { $attr = $this->getStyleAttributes($color); if (isset($attr['rgb'])) { return (string) $attr['rgb']; } if (isset($attr['indexed'])) { $indexedColor = (int) $attr['indexed']; if ($indexedColor >= count($this->workbookPalette)) { return Color::indexedColor($indexedColor - 7, $background)->getARGB() ?? ''; } return Color::indexedColor($indexedColor, $background, $this->workbookPalette)->getARGB() ?? ''; } if (isset($attr['theme'])) { if ($this->theme !== null) { $returnColour = $this->theme->getColourByIndex((int) $attr['theme']); if (isset($attr['tint'])) { $tintAdjust = (float) $attr['tint']; $returnColour = Color::changeBrightness($returnColour ?? '', $tintAdjust); } return 'FF' . $returnColour; } } return ($background) ? 'FFFFFFFF' : 'FF000000'; } /** @return Style[] */ public function dxfs(bool $readDataOnly = false): array { $dxfs = []; if (!$readDataOnly && $this->styleXml) { // Conditional Styles if ($this->styleXml->dxfs) { foreach ($this->styleXml->dxfs->dxf as $dxf) { $style = new Style(false, true); $this->readStyle($style, $dxf); $dxfs[] = $style; } } // Cell Styles if ($this->styleXml->cellStyles) { foreach ($this->styleXml->cellStyles->cellStyle as $cellStylex) { $cellStyle = Xlsx::getAttributes($cellStylex); if ((int) ($cellStyle['builtinId']) == 0) { if (isset($this->cellStyles[(int) ($cellStyle['xfId'])])) { // Set default style $style = new Style(); $this->readStyle($style, $this->cellStyles[(int) ($cellStyle['xfId'])]); // normal style, currently not using it for anything } } } } } return $dxfs; } /** @return TableDxfsStyle[] */ public function tableStyles(bool $readDataOnly = false): array { $tableStyles = []; if (!$readDataOnly && $this->styleXml) { // Conditional Styles if ($this->styleXml->tableStyles) { foreach ($this->styleXml->tableStyles->tableStyle as $s) { $attrs = Xlsx::getAttributes($s); if (isset($attrs['name'][0])) { $style = new TableDxfsStyle((string) ($attrs['name'][0])); foreach ($s->tableStyleElement as $e) { $a = Xlsx::getAttributes($e); if (isset($a['dxfId'][0], $a['type'][0])) { switch ($a['type'][0]) { case 'headerRow': $style->setHeaderRow((int) ($a['dxfId'][0])); break; case 'firstRowStripe': $style->setFirstRowStripe((int) ($a['dxfId'][0])); break; case 'secondRowStripe': $style->setSecondRowStripe((int) ($a['dxfId'][0])); break; default: } } } $tableStyles[] = $style; } } } } return $tableStyles; } /** @return mixed[] */ public function styles(): array { return $this->styles; } /** * Get array item. * * @param false|mixed[] $array (usually array, in theory can be false) */ private static function getArrayItem(mixed $array): ?SimpleXMLElement { return is_array($array) ? ($array[0] ?? null) : null; // @phpstan-ignore-line } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/TableReader.php ================================================ worksheet = $workSheet; $this->tableXml = $tableXml; } /** * Loads Table into the Worksheet. * * @param TableDxfsStyle[] $tableStyles * @param Style[] $dxfs */ public function load(array $tableStyles, array $dxfs): void { $this->tableAttributes = $this->tableXml->attributes() ?? []; // Remove all "$" in the table range $tableRange = (string) preg_replace('/\$/', '', $this->tableAttributes['ref'] ?? ''); if (str_contains($tableRange, ':')) { $this->readTable($tableRange, $tableStyles, $dxfs); } } /** * Read Table from xml. * * @param TableDxfsStyle[] $tableStyles * @param Style[] $dxfs */ private function readTable(string $tableRange, array $tableStyles, array $dxfs): void { $table = new Table($tableRange); /** @var string[] */ $attributes = $this->tableAttributes; $table->setName((string) ($attributes['displayName'] ?? '')); $table->setShowHeaderRow(((string) ($attributes['headerRowCount'] ?? '')) !== '0'); $table->setShowTotalsRow(((string) ($attributes['totalsRowCount'] ?? '')) === '1'); $this->readTableAutoFilter($table, $this->tableXml->autoFilter); $this->readTableColumns($table, $this->tableXml->tableColumns); $this->readTableStyle($table, $this->tableXml->tableStyleInfo, $tableStyles, $dxfs); (new AutoFilter($table, $this->tableXml))->load(); $this->worksheet->addTable($table); } /** * Reads TableAutoFilter from xml. */ private function readTableAutoFilter(Table $table, SimpleXMLElement $autoFilterXml): void { if ($autoFilterXml->filterColumn === null) { $table->setAllowFilter(false); return; } foreach ($autoFilterXml->filterColumn as $filterColumn) { /** @var SimpleXMLElement */ $attributes = $filterColumn->attributes() ?? ['colId' => 0, 'hiddenButton' => 0]; $column = $table->getColumnByOffset((int) $attributes['colId']); $column->setShowFilterButton(((string) $attributes['hiddenButton']) !== '1'); } } /** * Reads TableColumns from xml. */ private function readTableColumns(Table $table, SimpleXMLElement $tableColumnsXml): void { $offset = 0; foreach ($tableColumnsXml->tableColumn as $tableColumn) { /** @var SimpleXMLElement */ $attributes = $tableColumn->attributes() ?? ['totalsRowLabel' => 0, 'totalsRowFunction' => 0]; $column = $table->getColumnByOffset($offset++); if ($table->getShowTotalsRow()) { if ($attributes['totalsRowLabel']) { $column->setTotalsRowLabel((string) $attributes['totalsRowLabel']); } if ($attributes['totalsRowFunction']) { $column->setTotalsRowFunction((string) $attributes['totalsRowFunction']); } } if ($tableColumn->calculatedColumnFormula) { $column->setColumnFormula((string) $tableColumn->calculatedColumnFormula); } } } /** * Reads TableStyle from xml. * * @param TableDxfsStyle[] $tableStyles * @param Style[] $dxfs */ private function readTableStyle(Table $table, SimpleXMLElement $tableStyleInfoXml, array $tableStyles, array $dxfs): void { $tableStyle = new TableStyle(); $attributes = $tableStyleInfoXml->attributes(); if ($attributes !== null) { $tableStyle->setTheme((string) $attributes['name']); $tableStyle->setShowRowStripes((string) $attributes['showRowStripes'] === '1'); $tableStyle->setShowColumnStripes((string) $attributes['showColumnStripes'] === '1'); $tableStyle->setShowFirstColumn((string) $attributes['showFirstColumn'] === '1'); $tableStyle->setShowLastColumn((string) $attributes['showLastColumn'] === '1'); foreach ($tableStyles as $style) { if ($style->getName() === (string) $attributes['name']) { $tableStyle->setTableDxfsStyle($style, $dxfs); } } } $table->setStyle($tableStyle); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/Theme.php ================================================ themeName = $themeName; $this->colourSchemeName = $colourSchemeName; $this->colourMap = $colourMap; } /** * Not called by Reader, never accessible any other time. * * @codeCoverageIgnore */ public function getThemeName(): string { return $this->themeName; } /** * Not called by Reader, never accessible any other time. * * @codeCoverageIgnore */ public function getColourSchemeName(): string { return $this->colourSchemeName; } /** * Get colour Map Value by Position. */ public function getColourByIndex(int $index): ?string { return $this->colourMap[$index] ?? null; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php ================================================ spreadsheet = $spreadsheet; } /** @param array $mapSheetId */ public function viewSettings(SimpleXMLElement $xmlWorkbook, string $mainNS, array $mapSheetId, bool $readDataOnly): void { // Default active sheet index to the first loaded worksheet from the file $this->spreadsheet->setActiveSheetIndex(0); $workbookView = $xmlWorkbook->children($mainNS)->bookViews->workbookView; if ($readDataOnly !== true && !empty($workbookView)) { $workbookViewAttributes = self::testSimpleXml(self::getAttributes($workbookView)); // active sheet index $activeTab = (int) $workbookViewAttributes->activeTab; // refers to old sheet index // keep active sheet index if sheet is still loaded, else first sheet is set as the active worksheet if (isset($mapSheetId[$activeTab])) { $this->spreadsheet->setActiveSheetIndex($mapSheetId[$activeTab]); } $this->horizontalScroll($workbookViewAttributes); $this->verticalScroll($workbookViewAttributes); $this->sheetTabs($workbookViewAttributes); $this->minimized($workbookViewAttributes); $this->autoFilterDateGrouping($workbookViewAttributes); $this->firstSheet($workbookViewAttributes); $this->visibility($workbookViewAttributes); $this->tabRatio($workbookViewAttributes); } } public static function testSimpleXml(mixed $value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); } public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement { return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); } /** * Convert an 'xsd:boolean' XML value to a PHP boolean value. * A valid 'xsd:boolean' XML value can be one of the following * four values: 'true', 'false', '1', '0'. It is case-sensitive. * * Note that just doing '(bool) $xsdBoolean' is not safe, * since '(bool) "false"' returns true. * * @see https://www.w3.org/TR/xmlschema11-2/#boolean * * @param string $xsdBoolean An XML string value of type 'xsd:boolean' * * @return bool Boolean value */ private function castXsdBooleanToBool(string $xsdBoolean): bool { if ($xsdBoolean === 'false') { return false; } return (bool) $xsdBoolean; } private function horizontalScroll(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->showHorizontalScroll)) { $showHorizontalScroll = (string) $workbookViewAttributes->showHorizontalScroll; $this->spreadsheet->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll)); } } private function verticalScroll(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->showVerticalScroll)) { $showVerticalScroll = (string) $workbookViewAttributes->showVerticalScroll; $this->spreadsheet->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll)); } } private function sheetTabs(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->showSheetTabs)) { $showSheetTabs = (string) $workbookViewAttributes->showSheetTabs; $this->spreadsheet->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs)); } } private function minimized(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->minimized)) { $minimized = (string) $workbookViewAttributes->minimized; $this->spreadsheet->setMinimized($this->castXsdBooleanToBool($minimized)); } } private function autoFilterDateGrouping(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->autoFilterDateGrouping)) { $autoFilterDateGrouping = (string) $workbookViewAttributes->autoFilterDateGrouping; $this->spreadsheet->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping)); } } private function firstSheet(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->firstSheet)) { $firstSheet = (string) $workbookViewAttributes->firstSheet; $this->spreadsheet->setFirstSheetIndex((int) $firstSheet); } } private function visibility(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->visibility)) { $visibility = (string) $workbookViewAttributes->visibility; $this->spreadsheet->setVisibility($visibility); } } private function tabRatio(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->tabRatio)) { $tabRatio = (string) $workbookViewAttributes->tabRatio; $this->spreadsheet->setTabRatio((int) $tabRatio); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xlsx.php ================================================ parseHuge = $parseHuge; } /** * Create a new Xlsx Reader instance. */ public function __construct() { parent::__construct(); $this->referenceHelper = ReferenceHelper::getInstance(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) { return false; } $result = false; $this->zip = $zip = new ZipArchive(); if ($zip->open($filename) === true) { [$workbookBasename] = $this->getWorkbookBaseName(); $result = !empty($workbookBasename); $zip->close(); } return $result; } public static function testSimpleXml(mixed $value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); } public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement { return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); } // Phpstan thinks, correctly, that xpath can return false. /** @return mixed[] */ private static function xpathNoFalse(SimpleXMLElement $sxml, string $path): array { return self::falseToArray($sxml->xpath($path)); } /** @return mixed[] */ public static function falseToArray(mixed $value): array { return is_array($value) ? $value : []; } private function loadZip(string $filename, string $ns = '', bool $replaceUnclosedBr = false): SimpleXMLElement { $contents = $this->getFromZipArchive($this->zip, $filename); if ($replaceUnclosedBr) { $contents = str_replace('
', '
', $contents); } $rels = @simplexml_load_string( $this->getSecurityScannerOrThrow()->scan($contents), SimpleXMLElement::class, $this->parseHuge ? LIBXML_PARSEHUGE : 0, $ns ); return self::testSimpleXml($rels); } // This function is just to identify cases where I'm not sure // why empty namespace is required. private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement { $contents = $this->getFromZipArchive($this->zip, $filename); $rels = simplexml_load_string( $this->getSecurityScannerOrThrow()->scan($contents), SimpleXMLElement::class, $this->parseHuge ? LIBXML_PARSEHUGE : 0, ($ns === '' ? $ns : '') ); return self::testSimpleXml($rels); } private const REL_TO_MAIN = [ Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN, Namespaces::THUMBNAIL => '', ]; private const REL_TO_DRAWING = [ Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING, ]; private const REL_TO_CHART = [ Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_CHART, ]; /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * * @return string[] */ public function listWorksheetNames(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relType = (string) $rel['Type']; $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; if ($mainNS !== '') { $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS); if ($xmlWorkbook->sheets) { foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { // Check if sheet should be skipped $worksheetNames[] = (string) self::getAttributes($eleSheet)['name']; } } } } $zip->close(); return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relType = (string) $rel['Type']; $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; if ($mainNS !== '') { $relTarget = (string) $rel['Target']; $dir = dirname($relTarget); $namespace = dirname($relType); $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', Namespaces::RELATIONSHIPS); $worksheets = []; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); if ( ((string) $ele['Type'] === "$namespace/worksheet") || ((string) $ele['Type'] === "$namespace/chartsheet") ) { $worksheets[(string) $ele['Id']] = $ele['Target']; } } $xmlWorkbook = $this->loadZip($relTarget, $mainNS); if ($xmlWorkbook->sheets) { $dir = dirname($relTarget); foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = [ 'worksheetName' => (string) self::getAttributes($eleSheet)['name'], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; $sheetState = (string) (self::getAttributes($eleSheet)['state'] ?? Worksheet::SHEETSTATE_VISIBLE); $tmpInfo['sheetState'] = $sheetState; $fileWorksheet = (string) $worksheets[self::getArrayItemString(self::getAttributes($eleSheet, $namespace), 'id')]; $fileWorksheetPath = str_starts_with($fileWorksheet, '/') ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet"; $xml = new XMLReader(); $xml->xml( $this->getSecurityScannerOrThrow() ->scan( $this->getFromZipArchive( $this->zip, $fileWorksheetPath ) ), null, $this->parseHuge ? LIBXML_PARSEHUGE : 0 ); $xml->setParserProperty(2, true); $currCells = 0; $currRow = 0; while ($xml->read()) { if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { $row = (int) $xml->getAttribute('r'); if ($this->readEmptyCells) { $tmpInfo['totalRows'] = $row; } else { $currRow = $row; } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { if ($this->readEmptyCells || !$xml->isEmptyElement) { if ($currRow !== 0) { $tmpInfo['totalRows'] = $currRow; $currRow = 0; } $cell = $xml->getAttribute('r'); $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1); } } } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $xml->close(); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1, true); $worksheetInfo[] = $tmpInfo; } } } } $zip->close(); return $worksheetInfo; } private static function castToBoolean(SimpleXMLElement $c): bool { $value = isset($c->v) ? (string) $c->v : null; if ($value == '0') { return false; } elseif ($value == '1') { return true; } return (bool) $c->v; } private static function castToError(?SimpleXMLElement $c): ?string { return isset($c, $c->v) ? (string) $c->v : null; } private static function castToString(?SimpleXMLElement $c): ?string { return isset($c, $c->v) ? (string) $c->v : null; } public static function replacePrefixes(string $formula): string { return str_replace(['_xlfn.', '_xlws.'], '', $formula); } private function castToFormula(?SimpleXMLElement $c, string $r, string &$cellDataType, mixed &$value, mixed &$calculatedValue, string $castBaseType, bool $updateSharedCells = true): void { if ($c === null) { return; } $attr = $c->f->attributes(); $cellDataType = DataType::TYPE_FORMULA; $formula = self::replacePrefixes((string) $c->f); $value = "=$formula"; $calculatedValue = self::$castBaseType($c); // Shared formula? if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') { $instance = (string) $attr['si']; if (!isset($this->sharedFormulae[(string) $attr['si']])) { $this->sharedFormulae[$instance] = new SharedFormula($r, $value); } elseif ($updateSharedCells === true) { // It's only worth the overhead of adjusting the shared formula for this cell if we're actually loading // the cell, which may not be the case if we're using a read filter. $master = Coordinate::indexesFromString($this->sharedFormulae[$instance]->master()); $current = Coordinate::indexesFromString($r); $difference = [0, 0]; $difference[0] = $current[0] - $master[0]; $difference[1] = $current[1] - $master[1]; $value = $this->referenceHelper->updateFormulaReferences($this->sharedFormulae[$instance]->formula(), 'A1', $difference[0], $difference[1]); } } } private function fileExistsInArchive(ZipArchive $archive, string $fileName = ''): bool { // Root-relative paths if (str_contains($fileName, '//')) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } $fileName = File::realpath($fileName); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming // so we need to load case-insensitively from the zip file // Apache POI fixes $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE); if ($contents === false) { $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE); } return $contents !== false; } private function getFromZipArchive(ZipArchive $archive, string $fileName = ''): string { // Root-relative paths if (str_contains($fileName, '//')) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } // Relative paths generated by dirname($filename) when $filename // has no path (i.e.files in root of the zip archive) $fileName = Preg::replace('/^\.\//', '', $fileName); $fileName = File::realpath($fileName); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming // so we need to load case-insensitively from the zip file $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE); // Apache POI fixes if ($contents === false) { $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE); } // Has the file been saved with Windoze directory separators rather than unix? if ($contents === false) { $contents = $archive->getFromName(str_replace('/', '\\', $fileName), 0, ZipArchive::FL_NOCASE); } return ($contents === false) ? '' : $contents; } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { File::assertFile($filename, self::INITIAL_FILE); // Initialisations $excel = $this->newSpreadsheet(); $excel->setValueBinder($this->valueBinder); $excel->removeSheetByIndex(0); $addingFirstCellStyleXf = true; $addingFirstCellXf = true; /** @var mixed[][][][] */ $unparsedLoadedData = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); // Read the theme first, because we need the colour scheme when reading the styles [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML; $chartNS = self::REL_TO_CHART[$xmlNamespaceBase] ?? Namespaces::CHART; $wbRels = $this->loadZip("xl/_rels/{$workbookBasename}.rels", Namespaces::RELATIONSHIPS); $theme = null; $this->styleReader = new Styles(); foreach ($wbRels->Relationship as $relx) { $rel = self::getAttributes($relx); $relTarget = (string) $rel['Target']; if (str_starts_with($relTarget, '/xl/')) { $relTarget = substr($relTarget, 4); } switch ($rel['Type']) { case "$xmlNamespaceBase/sheetMetadata": if ($this->fileExistsInArchive($zip, "xl/{$relTarget}")) { $excel->returnArrayAsArray(); } break; case "$xmlNamespaceBase/theme": if (!$this->fileExistsInArchive($zip, "xl/{$relTarget}")) { break; // issue3770 } $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2']; $themeOrderAdditional = count($themeOrderArray); $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS); $xmlThemeName = self::getAttributes($xmlTheme); $xmlTheme = $xmlTheme->children($drawingNS); $themeName = (string) $xmlThemeName['name']; $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme); $colourSchemeName = (string) $colourScheme['name']; $excel->getTheme()->setThemeColorName($colourSchemeName); $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS); $themeColours = []; foreach ($colourScheme as $k => $xmlColour) { $themePos = array_search($k, $themeOrderArray); if ($themePos === false) { $themePos = $themeOrderAdditional++; } if (isset($xmlColour->sysClr)) { $xmlColourData = self::getAttributes($xmlColour->sysClr); $themeColours[$themePos] = (string) $xmlColourData['lastClr']; $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['lastClr']); } elseif (isset($xmlColour->srgbClr)) { $xmlColourData = self::getAttributes($xmlColour->srgbClr); $themeColours[$themePos] = (string) $xmlColourData['val']; $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['val']); } } $theme = new Theme($themeName, $colourSchemeName, $themeColours); $this->styleReader->setTheme($theme); $fontScheme = self::getAttributes($xmlTheme->themeElements->fontScheme); $fontSchemeName = (string) $fontScheme['name']; $excel->getTheme()->setThemeFontName($fontSchemeName); $majorFonts = []; $minorFonts = []; $fontScheme = $xmlTheme->themeElements->fontScheme->children($drawingNS); $majorLatin = self::getAttributes($fontScheme->majorFont->latin)['typeface'] ?? ''; $majorEastAsian = self::getAttributes($fontScheme->majorFont->ea)['typeface'] ?? ''; $majorComplexScript = self::getAttributes($fontScheme->majorFont->cs)['typeface'] ?? ''; $minorLatin = self::getAttributes($fontScheme->minorFont->latin)['typeface'] ?? ''; $minorEastAsian = self::getAttributes($fontScheme->minorFont->ea)['typeface'] ?? ''; $minorComplexScript = self::getAttributes($fontScheme->minorFont->cs)['typeface'] ?? ''; foreach ($fontScheme->majorFont->font as $xmlFont) { $fontAttributes = self::getAttributes($xmlFont); $script = (string) ($fontAttributes['script'] ?? ''); if (!empty($script)) { $majorFonts[$script] = (string) ($fontAttributes['typeface'] ?? ''); } } foreach ($fontScheme->minorFont->font as $xmlFont) { $fontAttributes = self::getAttributes($xmlFont); $script = (string) ($fontAttributes['script'] ?? ''); if (!empty($script)) { $minorFonts[$script] = (string) ($fontAttributes['typeface'] ?? ''); } } $excel->getTheme()->setMajorFontValues($majorLatin, $majorEastAsian, $majorComplexScript, $majorFonts); $excel->getTheme()->setMinorFontValues($minorLatin, $minorEastAsian, $minorComplexScript, $minorFonts); break; } } $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $propertyReader = new PropertyReader($this->getSecurityScannerOrThrow(), $excel->getProperties()); $charts = $chartDetails = []; foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relTarget = (string) $rel['Target']; // issue 3553 if ($relTarget[0] === '/') { $relTarget = substr($relTarget, 1); } $relType = (string) $rel['Type']; $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; switch ($relType) { case Namespaces::CORE_PROPERTIES: $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget)); break; case "$xmlNamespaceBase/extended-properties": $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget)); break; case "$xmlNamespaceBase/custom-properties": $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget)); break; //Ribbon case Namespaces::EXTENSIBILITY: $customUI = $relTarget; if ($customUI) { $this->readRibbon($excel, $customUI, $zip); } break; case "$xmlNamespaceBase/officeDocument": $dir = dirname($relTarget); // Do not specify namespace in next stmt - do it in Xpath $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', Namespaces::RELATIONSHIPS); $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS); $worksheets = []; $macros = $customUI = null; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); switch ($ele['Type']) { case Namespaces::WORKSHEET: case Namespaces::PURL_WORKSHEET: $worksheets[(string) $ele['Id']] = $ele['Target']; break; case Namespaces::CHARTSHEET: if ($this->includeCharts === true) { $worksheets[(string) $ele['Id']] = $ele['Target']; } break; // a vbaProject ? (: some macros) case Namespaces::VBA: $macros = $ele['Target']; break; } } if ($macros !== null) { $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin if (!empty($macrosCode)) { $excel->setMacrosCode($macrosCode); $excel->setHasMacros(true); //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); $excel->setMacrosCertificate($Certificate); } } $relType = "rel:Relationship[@Type='" . "$xmlNamespaceBase/styles" . "']"; /** @var ?SimpleXMLElement */ $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType)); if ($xpath === null) { $xmlStyles = self::testSimpleXml(null); } else { $stylesTarget = (string) $xpath['Target']; $stylesTarget = str_starts_with($stylesTarget, '/') ? substr($stylesTarget, 1) : "$dir/$stylesTarget"; $xmlStyles = $this->loadZip($stylesTarget, $mainNS); } $palette = self::extractPalette($xmlStyles); $this->styleReader->setWorkbookPalette($palette); $fills = self::extractStyles($xmlStyles, 'fills', 'fill'); $fonts = self::extractStyles($xmlStyles, 'fonts', 'font'); $borders = self::extractStyles($xmlStyles, 'borders', 'border'); $xfTags = self::extractStyles($xmlStyles, 'cellXfs', 'xf'); $cellXfTags = self::extractStyles($xmlStyles, 'cellStyleXfs', 'xf'); $styles = []; $cellStyles = []; $numFmts = null; if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) { $numFmts = $xmlStyles->numFmts[0]; } if (isset($numFmts)) { /** @var SimpleXMLElement $numFmts */ $numFmts->registerXPathNamespace('sml', $mainNS); } $this->styleReader->setNamespace($mainNS); if (!$this->readDataOnly/* && $xmlStyles*/) { foreach ($xfTags as $xfTag) { /** @var SimpleXMLElement $xfTag */ $xf = self::getAttributes($xfTag); $numFmt = null; if ($xf['numFmtId']) { if (isset($numFmts)) { /** @var ?SimpleXMLElement */ $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); if (isset($tmpNumFmt['formatCode'])) { $numFmt = (string) $tmpNumFmt['formatCode']; } } // We shouldn't override any of the built-in MS Excel values (values below id 164) // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used // So we make allowance for them rather than lose formatting masks if ( $numFmt === null && (int) $xf['numFmtId'] < 164 && NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '' ) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? ''); $style = (object) [ 'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL, 'font' => $fonts[(int) ($xf['fontId'])], 'fill' => $fills[(int) ($xf['fillId'])], 'border' => $borders[(int) ($xf['borderId'])], 'alignment' => $xfTag->alignment, 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $styles[] = $style; // add style to cellXf collection $objStyle = new Style(); $this->styleReader ->readStyle($objStyle, $style); if (isset($xfTag->extLst)) { foreach ($xfTag->extLst->ext as $extTag) { $attributes = $extTag->attributes(); if (isset($attributes['uri'])) { if ((string) $attributes['uri'] === Namespaces::STYLE_CHECKBOX_URI) { $objStyle->setCheckBox(true); } } } } foreach ($this->styleReader->getFontCharsets() as $fontName => $charset) { $excel->addFontCharset($fontName, $charset); } if ($addingFirstCellXf) { $excel->removeCellXfByIndex(0); // remove the default style $addingFirstCellXf = false; } $excel->addCellXf($objStyle); } foreach ($cellXfTags as $xfTag) { /** @var SimpleXMLElement $xfTag */ $xf = self::getAttributes($xfTag); $numFmt = NumberFormat::FORMAT_GENERAL; if ($numFmts && $xf['numFmtId']) { /** @var ?SimpleXMLElement */ $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); if (isset($tmpNumFmt['formatCode'])) { $numFmt = (string) $tmpNumFmt['formatCode']; } elseif ((int) $xf['numFmtId'] < 165) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? ''); $cellStyle = (object) [ 'numFmt' => $numFmt, 'font' => $fonts[(int) ($xf['fontId'])], 'fill' => $fills[((int) $xf['fillId'])], 'border' => $borders[(int) ($xf['borderId'])], 'alignment' => $xfTag->alignment, 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $cellStyles[] = $cellStyle; // add style to cellStyleXf collection $objStyle = new Style(); $this->styleReader->readStyle($objStyle, $cellStyle); if ($addingFirstCellStyleXf) { $excel->removeCellStyleXfByIndex(0); // remove the default style $addingFirstCellStyleXf = false; } $excel->addCellStyleXf($objStyle); } } $this->styleReader->setStyleXml($xmlStyles); $this->styleReader->setNamespace($mainNS); $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles); $dxfs = $this->styleReader->dxfs($this->readDataOnly); $tableStyles = $this->styleReader->tableStyles($this->readDataOnly); $styles = $this->styleReader->styles(); // Read content after setting the styles $sharedStrings = []; $relType = "rel:Relationship[@Type='" //. Namespaces::SHARED_STRINGS . "$xmlNamespaceBase/sharedStrings" . "']"; /** @var ?SimpleXMLElement */ $xpath = self::getArrayItem($relsWorkbook->xpath($relType)); if ($xpath) { $sharedStringsTarget = (string) $xpath['Target']; $sharedStringsTarget = str_starts_with($sharedStringsTarget, '/') ? substr($sharedStringsTarget, 1) : "$dir/$sharedStringsTarget"; $xmlStrings = $this->loadZip($sharedStringsTarget, $mainNS); if (isset($xmlStrings->si)) { foreach ($xmlStrings->si as $val) { if (isset($val->t)) { $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t); } elseif (isset($val->r)) { $sharedStrings[] = $this->parseRichText($val); } else { $sharedStrings[] = ''; } } } } $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS); $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS); // Set base date $excel->setExcelCalendar(Date::CALENDAR_WINDOWS_1900); if ($xmlWorkbookNS->workbookPr) { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr); if (isset($attrs1904['date1904'])) { if (self::boolean((string) $attrs1904['date1904'])) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); $excel->setExcelCalendar(Date::CALENDAR_MAC_1904); } } } // Set protection $this->readProtection($excel, $xmlWorkbook); $sheetId = 0; // keep track of new sheet id in final workbook $oldSheetId = -1; // keep track of old sheet id in final workbook $countSkippedSheets = 0; // keep track of number of skipped sheets $mapSheetId = []; // mapping of sheet ids from old to new $charts = $chartDetails = []; // Add richData (contains relation of in-cell images) $richData = []; $relationsFileName = $dir . '/richData/_rels/richValueRel.xml.rels'; if ($zip->locateName($relationsFileName)) { $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); foreach ($relsWorksheet->Relationship as $elex) { $ele = self::getAttributes($elex); if ($ele['Type'] == Namespaces::IMAGE) { $richData['image'][(string) $ele['Id']] = (string) $ele['Target']; } } } $sheetCreated = false; if ($xmlWorkbookNS->sheets) { foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) { $eleSheetAttr = self::getAttributes($eleSheet); ++$oldSheetId; // Check if sheet should be skipped if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; continue; } $sheetReferenceId = self::getArrayItemString(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id'); if (isset($worksheets[$sheetReferenceId]) === false) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; continue; } // Map old sheet id in original workbook to new sheet id. // They will differ if loadSheetsOnly() is being used $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; // Load sheet $docSheet = $excel->createSheet(); $sheetCreated = true; // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet // references in formula cells... during the load, all formulae should be correct, // and we're simply bringing the worksheet name in line with the formula, not the // reverse $docSheet->setTitle((string) $eleSheetAttr['name'], false, false); $fileWorksheet = (string) $worksheets[$sheetReferenceId]; // issue 3665 adds test for /. // This broke XlsxRootZipFilesTest, // but Excel reports an error with that file. // Testing dir for . avoids this problem. // It might be better just to drop the test. if ($fileWorksheet[0] == '/' && $dir !== '.') { $fileWorksheet = substr($fileWorksheet, strlen($dir) + 2); } $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS); $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS); // Shared Formula table is unique to each Worksheet, so we need to reset it here $this->sharedFormulae = []; if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') { $docSheet->setSheetState((string) $eleSheetAttr['state']); } if ($xmlSheetNS) { $xmlSheetMain = $xmlSheetNS->children($mainNS); // Setting Conditional Styles adjusts selected cells, so we need to execute this // before reading the sheet view data to get the actual selected cells if (!$this->readDataOnly && ($xmlSheet->conditionalFormatting)) { (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->load(); } if (!$this->readDataOnly && $xmlSheet->extLst) { (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->loadFromExt(); } if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) { $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet); $sheetViews->load(); } $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheetNS); $sheetViewOptions->load($this->readDataOnly, $this->styleReader); (new ColumnAndRowAttributes($docSheet, $xmlSheetNS)) ->load($this->getReadFilter(), $this->readDataOnly, $this->ignoreRowsWithNoCells); } $holdSelectedCells = $docSheet->getSelectedCells(); if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) { $cIndex = 1; // Cell Start from 1 foreach ($xmlSheetNS->sheetData->row as $row) { $rowIndex = 1; foreach ($row->c as $c) { $cAttr = self::getAttributes($c); $r = (string) $cAttr['r']; if ($r == '') { $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex; } $cellDataType = (string) $cAttr['t']; $originalCellDataTypeNumeric = $cellDataType === ''; $value = null; $calculatedValue = null; // Read cell? $coordinates = Coordinate::coordinateFromString($r); if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) { // Normally, just testing for the f attribute should identify this cell as containing a formula // that we need to read, even though it is outside of the filter range, in case it is a shared formula. // But in some cases, this attribute isn't set; so we need to delve a level deeper and look at // whether or not the cell has a child formula element that is shared. if (isset($cAttr->f) || (isset($c->f, $c->f->attributes()['t']) && strtolower((string) $c->f->attributes()['t']) === 'shared')) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError', false); } ++$rowIndex; continue; } // Read cell! $useFormula = isset($c->f) && ((string) $c->f !== '' || (isset($c->f->attributes()['t']) && strtolower((string) $c->f->attributes()['t']) === 'shared')); switch ($cellDataType) { case DataType::TYPE_STRING: if ((string) $c->v != '') { $value = $sharedStrings[(int) ($c->v)]; if ($value instanceof RichText) { $value = clone $value; } } else { $value = ''; } break; case DataType::TYPE_BOOL: if (!$useFormula) { if (isset($c->v)) { $value = self::castToBoolean($c); } else { $value = null; $cellDataType = DataType::TYPE_NULL; } } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToBoolean'); self::storeFormulaAttributes($c->f, $docSheet, $r); } break; case DataType::TYPE_STRING2: if ($useFormula) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToString'); self::storeFormulaAttributes($c->f, $docSheet, $r); } else { $value = self::castToString($c); } break; case DataType::TYPE_INLINE: if ($useFormula) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError'); self::storeFormulaAttributes($c->f, $docSheet, $r); } else { $value = $this->parseRichText($c->is); } break; case DataType::TYPE_ERROR: if (isset($cAttr->vm, $richData['image']['rId' . $cAttr->vm]) && !$useFormula) { $imagePath = $dir . '/' . str_replace('../', '', $richData['image']['rId' . $cAttr->vm]); $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $objDrawing->setPath( 'zip://' . File::realpath($filename) . '#' . $imagePath, false, $zip ); $objDrawing->setCoordinates($r); $objDrawing->setResizeProportional(false); $objDrawing->setInCell(true); $objDrawing->setWorksheet($docSheet); $value = $objDrawing; $cellDataType = DataType::TYPE_DRAWING_IN_CELL; $c->t = DataType::TYPE_ERROR; break; } if (!$useFormula) { $value = self::castToError($c); } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError'); $eattr = $c->attributes(); if (isset($eattr['vm'])) { if ($calculatedValue === ExcelError::VALUE()) { $calculatedValue = ExcelError::SPILL(); } } } break; default: if (!$useFormula) { $value = self::castToString($c); if (is_numeric($value)) { $value += 0; $cellDataType = DataType::TYPE_NUMERIC; } } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToString'); if (is_numeric($calculatedValue)) { $calculatedValue += 0; } self::storeFormulaAttributes($c->f, $docSheet, $r); } break; } // read empty cells or the cells are not empty if ($this->readEmptyCells || ($value !== null && $value !== '')) { // Rich text? if ($value instanceof RichText && $this->readDataOnly) { $value = $value->getPlainText(); } $cell = $docSheet->getCell($r); // Assign value if ($cellDataType != '') { // it is possible, that datatype is numeric but with an empty string, which result in an error if ($cellDataType === DataType::TYPE_NUMERIC && ($value === '' || $value === null)) { $cellDataType = DataType::TYPE_NULL; } if ($cellDataType !== DataType::TYPE_NULL) { $cell->setValueExplicit($value, $cellDataType); } } else { $cell->setValue($value); } if ($calculatedValue !== null) { $cell->setCalculatedValue($calculatedValue, $originalCellDataTypeNumeric); } // Style information? if (!$this->readDataOnly) { $cAttrS = (int) ($cAttr['s'] ?? 0); // no style index means 0, it seems $cAttrS = isset($styles[$cAttrS]) ? $cAttrS : 0; $cell->setXfIndex($cAttrS); // issue 3495 if ($cellDataType === DataType::TYPE_FORMULA && $styles[$cAttrS]->quotePrefix === true) { //* @phpstan-ignore-line $holdSelected = $docSheet->getSelectedCells(); $cell->getStyle()->setQuotePrefix(false); $docSheet->setSelectedCells($holdSelected); } } } ++$rowIndex; } ++$cIndex; } } $docSheet->setSelectedCells($holdSelectedCells); if (!$this->readDataOnly && $xmlSheetNS && $xmlSheetNS->ignoredErrors) { foreach ($xmlSheetNS->ignoredErrors->ignoredError as $ignoredError) { $this->processIgnoredErrors($ignoredError, $docSheet); } } if (!$this->readDataOnly && $xmlSheetNS && $xmlSheetNS->sheetProtection) { $protAttr = $xmlSheetNS->sheetProtection->attributes() ?? []; foreach ($protAttr as $key => $value) { $method = 'set' . ucfirst($key); $docSheet->getProtection()->$method(self::boolean((string) $value)); } } if ($xmlSheet) { $this->readSheetProtection($docSheet, $xmlSheet); } if ($this->readDataOnly === false) { $this->readAutoFilter($xmlSheetNS, $docSheet); $this->readBackgroundImage($xmlSheetNS, $docSheet, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'); } $this->readTables($xmlSheetNS, $docSheet, $dir, $fileWorksheet, $zip, $mainNS, $tableStyles, $dxfs); if ($xmlSheetNS && $xmlSheetNS->mergeCells && $xmlSheetNS->mergeCells->mergeCell && !$this->readDataOnly) { foreach ($xmlSheetNS->mergeCells->mergeCell as $mergeCellx) { $mergeCell = $mergeCellx->attributes(); $mergeRef = (string) ($mergeCell['ref'] ?? ''); if (str_contains($mergeRef, ':')) { $docSheet->mergeCells($mergeRef, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } if ($xmlSheet && !$this->readDataOnly) { $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData); } if (isset($xmlSheet->extLst->ext)) { foreach ($xmlSheet->extLst->ext as $extlst) { $extAttrs = $extlst->attributes() ?? []; $extUri = (string) ($extAttrs['uri'] ?? ''); if ($extUri !== '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}') { continue; } // Create dataValidations node if does not exists, maybe is better inside the foreach ? if (!$xmlSheet->dataValidations) { $xmlSheet->addChild('dataValidations'); } foreach ($extlst->children(Namespaces::DATA_VALIDATIONS1)->dataValidations->dataValidation as $item) { $item = self::testSimpleXml($item); $node = self::testSimpleXml($xmlSheet->dataValidations)->addChild('dataValidation'); foreach ($item->attributes() ?? [] as $attr) { $node->addAttribute($attr->getName(), $attr); } $node->addAttribute('sqref', $item->children(Namespaces::DATA_VALIDATIONS2)->sqref); if (isset($item->formula1)) { $childNode = $node->addChild('formula1'); if ($childNode !== null) { // null should never happen // see https://github.com/phpstan/phpstan/issues/8236 // resolved with Phpstan 2.1.23 $childNode[0] = (string) $item->formula1->children(Namespaces::DATA_VALIDATIONS2)->f; } } } } } if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) { (new DataValidations($docSheet, $xmlSheet))->load(); } // unparsed sheet AlternateContent if ($xmlSheet && !$this->readDataOnly) { $mc = $xmlSheet->children(Namespaces::COMPATIBILITY); if ($mc->AlternateContent) { foreach ($mc->AlternateContent as $alternateContent) { $alternateContent = self::testSimpleXml($alternateContent); /** @var mixed[][][][] $unparsedLoadedData */ $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML(); } } } // Add hyperlinks if (!$this->readDataOnly) { $hyperlinkReader = new Hyperlinks($docSheet); // Locate hyperlink relations $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($relationsFileName) !== false) { $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); $hyperlinkReader->readHyperlinks($relsWorksheet); } // Loop through hyperlinks if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) { $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks); } } // Add comments $comments = []; $vmlComments = []; if (!$this->readDataOnly) { // Locate comment relations $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($commentRelations) !== false) { $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS); foreach ($relsWorksheet->Relationship as $elex) { $ele = self::getAttributes($elex); if ($ele['Type'] == Namespaces::COMMENTS) { $comments[(string) $ele['Id']] = (string) $ele['Target']; } if ($ele['Type'] == Namespaces::VML) { $vmlComments[(string) $ele['Id']] = (string) $ele['Target']; } } } // Loop through comments foreach ($comments as $relName => $relPath) { // Load comments file $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); // okay to ignore namespace - using xpath $commentsFile = $this->loadZip($relPath, ''); // Utility variables $authors = []; $commentsFile->registerXpathNamespace('com', $mainNS); $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author'); foreach ($authorPath as $author) { /** @var SimpleXMLElement $author */ $authors[] = (string) $author; } // Loop through contents $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment'); foreach ($contentPath as $comment) { /** @var SimpleXMLElement $comment */ $commentx = $comment->attributes(); /** @var array{ref: scalar, authorId?: scalar} $commentx */ $commentModel = $docSheet->getComment((string) $commentx['ref']); if (isset($commentx['authorId'])) { $commentModel->setAuthor($authors[(int) $commentx['authorId']]); } /** @var SimpleXMLElement */ $temp = $comment->children($mainNS); $commentModel->setText($this->parseRichText($temp->text)); } } // later we will remove from it real vmlComments $unparsedVmlDrawings = $vmlComments; $vmlDrawingContents = []; // Loop through VML comments foreach ($vmlComments as $relName => $relPath) { // Load VML comments file $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); try { // no namespace okay - processed with Xpath $vmlCommentsFile = $this->loadZip($relPath, '', true); $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML); } catch (Throwable) { //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData continue; } // Locate VML drawings image relations $drowingImages = []; $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels'; $vmlDrawingContents[$relName] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $relPath)); if ($zip->locateName($VMLDrawingsRelations) !== false) { $relsVMLDrawing = $this->loadZip($VMLDrawingsRelations, Namespaces::RELATIONSHIPS); foreach ($relsVMLDrawing->Relationship as $elex) { $ele = self::getAttributes($elex); if ($ele['Type'] == Namespaces::IMAGE) { $drowingImages[(string) $ele['Id']] = (string) $ele['Target']; } } } $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape'); foreach ($shapes as $shape) { /** @var SimpleXMLElement $shape */ $vmlNamespaces = $shape->getNamespaces(); $shape->registerXPathNamespace('v', $vmlNamespaces['v'] ?? Namespaces::URN_VML); $shape->registerXPathNamespace('x', $vmlNamespaces['x'] ?? Namespaces::URN_EXCEL); $shape->registerXPathNamespace('o', $vmlNamespaces['o'] ?? Namespaces::URN_MSOFFICE); if (isset($shape['style'])) { $style = (string) $shape['style']; $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1)); $column = null; $row = null; $textHAlign = null; $fillImageRelId = null; $fillImageTitle = ''; $clientData = $shape->xpath('.//x:ClientData'); $textboxDirection = ''; $textboxPath = $shape->xpath('.//v:textbox'); $textbox = (string) ($textboxPath[0]['style'] ?? ''); if (Preg::isMatch('/rtl/i', $textbox)) { $textboxDirection = Comment::TEXTBOX_DIRECTION_RTL; } elseif (Preg::isMatch('/ltr/i', $textbox)) { $textboxDirection = Comment::TEXTBOX_DIRECTION_LTR; } if (is_array($clientData) && !empty($clientData)) { /** @var SimpleXMLElement */ $clientData = $clientData[0]; if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') { $clientData->registerXPathNamespace('x', $vmlNamespaces['x'] ?? Namespaces::URN_EXCEL); $temp = $clientData->xpath('.//x:Row'); if (is_array($temp)) { $row = $temp[0]; } $temp = $clientData->xpath('.//x:Column'); if (is_array($temp)) { $column = $temp[0]; } $temp = $clientData->xpath('.//x:TextHAlign'); if (!empty($temp)) { $textHAlign = strtolower($temp[0]); } } } $rowx = (string) $row; $colx = (string) $column; if (is_numeric($rowx) && is_numeric($colx) && $textHAlign !== null) { $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setAlignment((string) $textHAlign); } if (is_numeric($rowx) && is_numeric($colx) && $textboxDirection !== '') { $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setTextboxDirection($textboxDirection); } $fillImageRelNode = $shape->xpath('.//v:fill/@o:relid'); if (is_array($fillImageRelNode) && !empty($fillImageRelNode)) { /** @var SimpleXMLElement */ $fillImageRelNode = $fillImageRelNode[0]; if (isset($fillImageRelNode['relid'])) { $fillImageRelId = (string) $fillImageRelNode['relid']; } } $fillImageTitleNode = $shape->xpath('.//v:fill/@o:title'); if (is_array($fillImageTitleNode) && !empty($fillImageTitleNode)) { /** @var SimpleXMLElement */ $fillImageTitleNode = $fillImageTitleNode[0]; if (isset($fillImageTitleNode['title'])) { $fillImageTitle = (string) $fillImageTitleNode['title']; } } if (($column !== null) && ($row !== null)) { // Set comment properties $comment = $docSheet->getComment([(int) $column + 1, (int) $row + 1]); $comment->getFillColor()->setRGB($fillColor); if (isset($fillImageRelId, $drowingImages[$fillImageRelId])) { $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $objDrawing->setName($fillImageTitle); $imagePath = str_replace(['../', '/xl/'], 'xl/', $drowingImages[$fillImageRelId]); $objDrawing->setPath( 'zip://' . File::realpath($filename) . '#' . $imagePath, true, $zip ); $comment->setBackgroundImage($objDrawing); } // Parse style $styleArray = explode(';', str_replace(' ', '', $style)); foreach ($styleArray as $stylePair) { $stylePair = explode(':', $stylePair); if ($stylePair[0] == 'margin-left') { $comment->setMarginLeft($stylePair[1]); } if ($stylePair[0] == 'margin-top') { $comment->setMarginTop($stylePair[1]); } if ($stylePair[0] == 'width') { $comment->setWidth($stylePair[1]); } if ($stylePair[0] == 'height') { $comment->setHeight($stylePair[1]); } if ($stylePair[0] == 'visibility') { $comment->setVisible($stylePair[1] == 'visible'); } } unset($unparsedVmlDrawings[$relName]); } } } } // unparsed vmlDrawing if ($unparsedVmlDrawings) { foreach ($unparsedVmlDrawings as $rId => $relPath) { /** @var mixed[][][] $unparsedLoadedData */ $rId = substr($rId, 3); // rIdXXX /** @var mixed[][] */ $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings']; $unparsedVmlDrawing[$rId] = []; $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath); $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath; $unparsedVmlDrawing[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath'])); unset($unparsedVmlDrawing); } } // Header/footer images if ($xmlSheetNS && $xmlSheetNS->legacyDrawingHF) { $vmlHfRid = ''; $vmlHfRidAttr = $xmlSheetNS->legacyDrawingHF->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT); if ($vmlHfRidAttr !== null && isset($vmlHfRidAttr['id'])) { $vmlHfRid = (string) $vmlHfRidAttr['id'][0]; } if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') !== false) { $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS); $vmlRelationship = ''; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] == Namespaces::VML && (string) $ele['Id'] === $vmlHfRid) { $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); break; } } if ($vmlRelationship != '') { // Fetch linked images $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS); $drawings = []; if (isset($relsVML->Relationship)) { foreach ($relsVML->Relationship as $ele) { if ($ele['Type'] == Namespaces::IMAGE) { $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']); } } } // Fetch VML document $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, ''); $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML); $hfImages = []; $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape'); foreach ($shapes as $idx => $shape) { /** @var SimpleXMLElement $shape */ $shape->registerXPathNamespace('v', Namespaces::URN_VML); $imageData = $shape->xpath('//v:imagedata'); if (empty($imageData)) { continue; } $imageData = $imageData[$idx]; $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE); /** @var array{width: int, height: int, margin-left?: int, margin-top: int} */ $style = self::toCSSArray((string) $shape['style']); if (array_key_exists((string) $imageData['relid'], $drawings)) { $shapeId = (string) $shape['id']; $hfImages[$shapeId] = new HeaderFooterDrawing(); if (isset($imageData['title'])) { $hfImages[$shapeId]->setName((string) $imageData['title']); } $hfImages[$shapeId]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false, $zip); $hfImages[$shapeId]->setResizeProportional(false); $hfImages[$shapeId]->setWidth($style['width']); $hfImages[$shapeId]->setHeight($style['height']); if (isset($style['margin-left'])) { $hfImages[$shapeId]->setOffsetX($style['margin-left']); } $hfImages[$shapeId]->setOffsetY($style['margin-top']); $hfImages[$shapeId]->setResizeProportional(true); } } $docSheet->getHeaderFooter()->setImages($hfImages); } } } } // TODO: Autoshapes from twoCellAnchors! $drawingFilename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if (str_starts_with($drawingFilename, 'xl//xl/')) { $drawingFilename = substr($drawingFilename, 4); } if (str_starts_with($drawingFilename, '/xl//xl/')) { $drawingFilename = substr($drawingFilename, 5); } if ($zip->locateName($drawingFilename) !== false) { $relsWorksheet = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS); $drawings = []; foreach ($relsWorksheet->Relationship as $elex) { $ele = self::getAttributes($elex); if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { $drawings[(string) $ele['Id']] = substr($eleTarget, 1); } else { $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } } if ($xmlSheetNS->drawing && !$this->readDataOnly) { $unparsedDrawings = []; $fileDrawing = null; foreach ($xmlSheetNS->drawing as $drawing) { $drawingRelId = self::getArrayItemString(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); $fileDrawing = $drawings[$drawingRelId]; $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; $relsDrawing = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS); $images = []; $hyperlinks = []; if ($relsDrawing && $relsDrawing->Relationship) { foreach ($relsDrawing->Relationship as $elex) { $ele = self::getAttributes($elex); $eleType = (string) $ele['Type']; if ($eleType === Namespaces::HYPERLINK) { $hyperlinks[(string) $ele['Id']] = (string) $ele['Target']; } if ($eleType === "$xmlNamespaceBase/image") { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { $eleTarget = substr($eleTarget, 1); $images[(string) $ele['Id']] = $eleTarget; } else { $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $eleTarget); } } elseif ($eleType === "$xmlNamespaceBase/chart") { if ($this->includeCharts) { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { $index = substr($eleTarget, 1); } else { $index = self::dirAdd($fileDrawing, $eleTarget); } $charts[$index] = [ 'id' => (string) $ele['Id'], 'sheet' => $docSheet->getTitle(), ]; } } } } $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, ''); $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING); // Store drawing XML for pass-through if enabled if ($this->enableDrawingPassThrough) { $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML(); // Mark that pass-through is enabled for this sheet $sheetCodeName = $docSheet->getCodeName(); if (!isset($unparsedLoadedData['sheets']) || !is_array($unparsedLoadedData['sheets'])) { $unparsedLoadedData['sheets'] = []; } if (!isset($unparsedLoadedData['sheets'][$sheetCodeName]) || !is_array($unparsedLoadedData['sheets'][$sheetCodeName])) { $unparsedLoadedData['sheets'][$sheetCodeName] = []; } /** @var array $sheetUnparsedData */ $sheetUnparsedData = &$unparsedLoadedData['sheets'][$sheetCodeName]; $sheetUnparsedData['drawingPassThroughEnabled'] = true; // Store original drawing relationships for pass-through if ($relsDrawing) { $sheetUnparsedData['drawingRelationships'] = $relsDrawing->asXML(); } // Store original media files paths and source file for pass-through $sheetUnparsedData['drawingMediaFiles'] = $images; $sheetUnparsedData['drawingSourceFile'] = File::realpath($filename); } if ($xmlDrawingChildren->oneCellAnchor) { foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) { $oneCellAnchor = self::testSimpleXml($oneCellAnchor); if ($oneCellAnchor->pic->blipFill) { $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; if (isset($blip, $blip->alphaModFix)) { $temp = (string) $blip->alphaModFix->attributes()->amt; if (is_numeric($temp)) { $objDrawing->setOpacity((int) $temp); } } $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; $objDrawing->setName(self::getArrayItemString(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name')); $objDrawing->setDescription(self::getArrayItemString(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr')); $embedImageKey = self::getArrayItemString( self::getAttributes($blip, $xmlNamespaceBase), 'embed' ); if (isset($images[$embedImageKey])) { $objDrawing->setPath( 'zip://' . File::realpath($filename) . '#' . $images[$embedImageKey], false, $zip ); } else { $linkImageKey = self::getArrayItemString( $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'link' ); if (isset($images[$linkImageKey])) { $url = str_replace('xl/drawings/', '', $images[$linkImageKey]); $objDrawing->setPath($url, false, allowExternal: $this->allowExternalImages, isWhitelisted: $this->isWhitelisted); } if ($objDrawing->getPath() === '') { continue; } } $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1)); $objDrawing->setOffsetX((int) Drawing::EMUToPixels($oneCellAnchor->from->colOff)); $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); $objDrawing->setResizeProportional(false); $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cx'))); $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cy'))); if ($xfrm) { $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($xfrm), 'rot'))); $objDrawing->setFlipVertical((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipV')); $objDrawing->setFlipHorizontal((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipH')); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'blurRad'))); $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dist'))); $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dir'))); $shadow->setAlignment(self::getArrayItemString(self::getAttributes($outerShdw), 'algn')); $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr; $shadow->getColor()->setRGB(self::getArrayItemString(self::getAttributes($clr), 'val')); if ($clr->alpha) { $alpha = StringHelper::convertToString(self::getArrayItem(self::getAttributes($clr->alpha), 'val')); if (is_numeric($alpha)) { $alpha = (int) ($alpha / 1000); $shadow->setAlpha($alpha); } } } $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks); $objDrawing->setWorksheet($docSheet); } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) { // Exported XLSX from Google Sheets positions charts with a oneCellAnchor $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1); $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff); $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff); $width = Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cx')); $height = Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cy')); $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $coordinates, 'fromOffsetX' => $offsetX, 'fromOffsetY' => $offsetY, 'width' => $width, 'height' => $height, 'worksheetTitle' => $docSheet->getTitle(), 'oneCellAnchor' => true, ]; } } } if ($xmlDrawingChildren->twoCellAnchor) { foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) { $twoCellAnchor = self::testSimpleXml($twoCellAnchor); if ($twoCellAnchor->pic->blipFill) { $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; if (isset($blip, $blip->alphaModFix)) { $temp = (string) $blip->alphaModFix->attributes()->amt; if (is_numeric($temp)) { $objDrawing->setOpacity((int) $temp); } } if (isset($twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->srcRect)) { $objDrawing->setSrcRect($twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->srcRect->attributes()); } $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; $editAs = $twoCellAnchor->attributes(); if (isset($editAs, $editAs['editAs'])) { $objDrawing->setEditAs($editAs['editAs']); } $objDrawing->setName((string) self::getArrayItemString(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name')); $objDrawing->setDescription(self::getArrayItemString(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr')); $embedImageKey = self::getArrayItemString( self::getAttributes($blip, $xmlNamespaceBase), 'embed' ); if (isset($images[$embedImageKey])) { $objDrawing->setPath( 'zip://' . File::realpath($filename) . '#' . $images[$embedImageKey], false, $zip ); } else { $linkImageKey = self::getArrayItemString( $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'link' ); if (isset($images[$linkImageKey])) { $url = str_replace('xl/drawings/', '', $images[$linkImageKey]); $objDrawing->setPath($url, false, allowExternal: $this->allowExternalImages, isWhitelisted: $this->isWhitelisted); } if ($objDrawing->getPath() === '') { continue; } } $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1)); $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff)); $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); $objDrawing->setCoordinates2(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1)); $objDrawing->setOffsetX2(Drawing::EMUToPixels($twoCellAnchor->to->colOff)); $objDrawing->setOffsetY2(Drawing::EMUToPixels($twoCellAnchor->to->rowOff)); $objDrawing->setResizeProportional(false); if ($xfrm) { $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($xfrm->ext), 'cx'))); $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($xfrm->ext), 'cy'))); $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($xfrm), 'rot'))); $objDrawing->setFlipVertical((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipV')); $objDrawing->setFlipHorizontal((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipH')); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'blurRad'))); $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dist'))); $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dir'))); $shadow->setAlignment(self::getArrayItemString(self::getAttributes($outerShdw), 'algn')); $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr; $shadow->getColor()->setRGB(self::getArrayItemString(self::getAttributes($clr), 'val')); if ($clr->alpha) { $alpha = StringHelper::convertToString(self::getArrayItem(self::getAttributes($clr->alpha), 'val')); if (is_numeric($alpha)) { $alpha = (int) ($alpha / 1000); $shadow->setAlpha($alpha); } } } $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks); $objDrawing->setWorksheet($docSheet); } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) { $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1); $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff); $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff); $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1); $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff); $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff); $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $fromCoordinate, 'fromOffsetX' => $fromOffsetX, 'fromOffsetY' => $fromOffsetY, 'toCoordinate' => $toCoordinate, 'toOffsetX' => $toOffsetX, 'toOffsetY' => $toOffsetY, 'worksheetTitle' => $docSheet->getTitle(), ]; } } } if ($xmlDrawingChildren->absoluteAnchor) { foreach ($xmlDrawingChildren->absoluteAnchor as $absoluteAnchor) { if (($this->includeCharts) && ($absoluteAnchor->graphicFrame)) { $graphic = $absoluteAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $width = Drawing::EMUToPixels((int) self::getArrayItemString(self::getAttributes($absoluteAnchor->ext), 'cx')[0]); $height = Drawing::EMUToPixels((int) self::getArrayItemString(self::getAttributes($absoluteAnchor->ext), 'cy')[0]); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => 'A1', 'fromOffsetX' => 0, 'fromOffsetY' => 0, 'width' => $width, 'height' => $height, 'worksheetTitle' => $docSheet->getTitle(), ]; } } } if (empty($relsDrawing) && $xmlDrawing->count() == 0) { // Save Drawing without rels and children as unparsed $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML(); } } // store original rId of drawing files /** @var mixed[][][][] $unparsedLoadedData */ $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = []; foreach ($relsWorksheet->Relationship as $elex) { $ele = self::getAttributes($elex); if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $drawingRelId = (string) $ele['Id']; $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId; if (isset($unparsedDrawings[$drawingRelId])) { $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['Drawings'][$drawingRelId] = $unparsedDrawings[$drawingRelId]; } } } if ($xmlSheet->legacyDrawing && !$this->readDataOnly) { foreach ($xmlSheet->legacyDrawing as $drawing) { $drawingRelId = self::getArrayItemString(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); if (isset($vmlDrawingContents[$drawingRelId])) { if (self::onlyNoteVml($vmlDrawingContents[$drawingRelId]) === false) { $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['legacyDrawing'] = $vmlDrawingContents[$drawingRelId]; } } } } // unparsed drawing AlternateContent $xmlAltDrawing = $this->loadZip((string) $fileDrawing, Namespaces::COMPATIBILITY); if ($xmlAltDrawing->AlternateContent) { foreach ($xmlAltDrawing->AlternateContent as $alternateContent) { $alternateContent = self::testSimpleXml($alternateContent); /** @var mixed[][][][][] $unparsedLoadedData */ $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML(); } } } } /** @var mixed[][][][] $unparsedLoadedData */ $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); // Loop through definedNames if ($xmlWorkbook->definedNames) { foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range $extractedRange = (string) $definedName; if (($spos = strpos($extractedRange, '!')) !== false) { $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos)); } else { $extractedRange = str_replace('$', '', $extractedRange); } // Valid range? if ($extractedRange == '') { continue; } // Some definedNames are only applicable if we are on the same sheet... if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) { // Switch on type switch ((string) $definedName['name']) { case '_xlnm._FilterDatabase': if ((string) $definedName['hidden'] !== '1') { $extractedRange = explode(',', $extractedRange); foreach ($extractedRange as $range) { $autoFilterRange = $range; if (str_contains($autoFilterRange, ':')) { $docSheet->getAutoFilter()->setRange($autoFilterRange); } } } break; case '_xlnm.Print_Titles': // Split $extractedRange $extractedRange = explode(',', $extractedRange); // Set print titles foreach ($extractedRange as $range) { $matches = []; $range = str_replace('$', '', $range); // check for repeating columns, e g. 'A:A' or 'A:D' if (Preg::isMatch('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]); } elseif (Preg::isMatch('/!?(\d+)\:(\d+)$/', $range, $matches)) { // check for repeating rows, e.g. '1:1' or '1:5' $docSheet->getPageSetup()->setRowsToRepeatAtTop([(int) $matches[1], (int) $matches[2]]); } } break; case '_xlnm.Print_Area': $rangeSets = Preg::split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ?: []; $newRangeSets = []; foreach ($rangeSets as $rangeSet) { [, $rangeSet] = Worksheet::extractSheetTitle($rangeSet, true); if (empty($rangeSet)) { continue; } if (!str_contains($rangeSet, ':')) { $rangeSet = $rangeSet . ':' . $rangeSet; } $newRangeSets[] = str_replace('$', '', $rangeSet); } if (count($newRangeSets) > 0) { $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets)); } break; default: break; } } } } // Next sheet id ++$sheetId; } // Loop through definedNames if ($xmlWorkbook->definedNames) { foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range $extractedRange = (string) $definedName; // Valid range? if ($extractedRange == '') { continue; } // Some definedNames are only applicable if we are on the same sheet... if ((string) $definedName['localSheetId'] != '') { // Local defined name // Switch on type switch ((string) $definedName['name']) { case '_xlnm._FilterDatabase': case '_xlnm.Print_Titles': case '_xlnm.Print_Area': break; default: if ($mapSheetId[(int) $definedName['localSheetId']] !== null) { $range = Worksheet::extractSheetTitle($extractedRange, true); $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]); if (str_contains((string) $definedName, '!')) { $range[0] = str_replace("''", "'", $range[0]); $range[0] = str_replace("'", '', $range[0]); if ($worksheet = $excel->getSheetByName($range[0])) { $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope)); } else { $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope)); } } else { $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true)); } } break; } } elseif (!isset($definedName['localSheetId'])) { // "Global" definedNames $locatedSheet = null; if (str_contains((string) $definedName, '!')) { // Modify range, and extract the first worksheet reference // Need to split on a comma or a space if not in quotes, and extract the first part. $definedNameValueParts = Preg::split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $extractedRange); // Extract sheet name [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true, true); // Locate sheet $locatedSheet = $excel->getSheetByName("$extractedSheetName"); } if ($locatedSheet === null && !DefinedName::testIfFormula($extractedRange)) { $extractedRange = '#REF!'; } $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $extractedRange, false)); } } } } if ($this->createBlankSheetIfNoneRead && !$sheetCreated) { $excel->createSheet(); } (new WorkbookView($excel))->viewSettings($xmlWorkbook, $mainNS, $mapSheetId, $this->readDataOnly); break; } } if (!$this->readDataOnly) { $contentTypes = $this->loadZip('[Content_Types].xml'); // Default content types foreach ($contentTypes->Default as $contentType) { switch ($contentType['ContentType']) { case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings': $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType']; break; } } // Override content types foreach ($contentTypes->Override as $contentType) { switch ($contentType['ContentType']) { case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml': if ($this->includeCharts) { $chartEntryRef = ltrim((string) $contentType['PartName'], '/'); $chartElements = $this->loadZip($chartEntryRef); $chartReader = new Chart($chartNS, $drawingNS); $objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml')); if (isset($charts[$chartEntryRef])) { $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id']; if (isset($chartDetails[$chartPositionRef]) && $excel->getSheetByName($charts[$chartEntryRef]['sheet']) !== null) { $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); // For oneCellAnchor or absoluteAnchor positioned charts, // toCoordinate is not in the data. Does it need to be calculated? if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) { // twoCellAnchor $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); } else { // oneCellAnchor or absoluteAnchor (e.g. Chart sheet) $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); $objChart->setBottomRightPosition('', $chartDetails[$chartPositionRef]['width'], $chartDetails[$chartPositionRef]['height']); if (array_key_exists('oneCellAnchor', $chartDetails[$chartPositionRef])) { $objChart->setOneCellAnchor($chartDetails[$chartPositionRef]['oneCellAnchor']); } } } } } break; // unparsed case 'application/vnd.ms-excel.controlproperties+xml': $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType']; break; } } } /** @var array|string>>> $unparsedLoadedData */ $excel->setUnparsedLoadedData($unparsedLoadedData); $zip->close(); return $excel; } private function parseRichText(?SimpleXMLElement $is): RichText { $value = new RichText(); if (isset($is->t)) { $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t)); } elseif ($is !== null) { if (is_object($is->r)) { foreach ($is->r as $run) { if (!isset($run->rPr)) { $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t)); } else { $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t)); $objFont = $objText->getFont() ?? new StyleFont(); if (isset($run->rPr->rFont)) { $attr = $run->rPr->rFont->attributes(); if (isset($attr['val'])) { $objFont->setName((string) $attr['val']); } } if (isset($run->rPr->sz)) { $attr = $run->rPr->sz->attributes(); if (isset($attr['val'])) { $objFont->setSize((float) $attr['val']); } } if (isset($run->rPr->color)) { $objFont->setColor(new Color($this->styleReader->readColor($run->rPr->color))); } if (isset($run->rPr->b)) { $attr = $run->rPr->b->attributes(); if ( (isset($attr['val']) && self::boolean((string) $attr['val'])) || (!isset($attr['val'])) ) { $objFont->setBold(true); } } if (isset($run->rPr->i)) { $attr = $run->rPr->i->attributes(); if ( (isset($attr['val']) && self::boolean((string) $attr['val'])) || (!isset($attr['val'])) ) { $objFont->setItalic(true); } } if (isset($run->rPr->vertAlign)) { $attr = $run->rPr->vertAlign->attributes(); if (isset($attr['val'])) { $vertAlign = strtolower((string) $attr['val']); if ($vertAlign == 'superscript') { $objFont->setSuperscript(true); } if ($vertAlign == 'subscript') { $objFont->setSubscript(true); } } } if (isset($run->rPr->u)) { $attr = $run->rPr->u->attributes(); if (!isset($attr['val'])) { $objFont->setUnderline(StyleFont::UNDERLINE_SINGLE); } else { $objFont->setUnderline((string) $attr['val']); } } if (isset($run->rPr->strike)) { $attr = $run->rPr->strike->attributes(); if ( (isset($attr['val']) && self::boolean((string) $attr['val'])) || (!isset($attr['val'])) ) { $objFont->setStrikethrough(true); } } } } } } return $value; } private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void { $baseDir = dirname($customUITarget); $nameCustomUI = basename($customUITarget); // get the xml file (ribbon) $localRibbon = $this->getFromZipArchive($zip, $customUITarget); $customUIImagesNames = []; $customUIImagesBinaries = []; // something like customUI/_rels/customUI.xml.rels $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; $dataRels = $this->getFromZipArchive($zip, $pathRels); if ($dataRels) { // exists and not empty if the ribbon have some pictures (other than internal MSO) $UIRels = simplexml_load_string( $this->getSecurityScannerOrThrow() ->scan($dataRels), SimpleXMLElement::class, $this->parseHuge ? LIBXML_PARSEHUGE : 0 ); if (false !== $UIRels) { // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image foreach ($UIRels->Relationship as $ele) { if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') { // an image ? $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target']; $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); } } } } if ($localRibbon) { $excel->setRibbonXMLData($customUITarget, $localRibbon); if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) { $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries); } else { $excel->setRibbonBinObjects(null, null); } } else { $excel->setRibbonXMLData(null, null); $excel->setRibbonBinObjects(null, null); } } /** @param null|bool|mixed[]|SimpleXMLElement $array */ private static function getArrayItem(null|array|bool|SimpleXMLElement $array, int|string $key = 0): mixed { return ($array === null || is_bool($array)) ? null : ($array[$key] ?? null); } /** @param null|bool|mixed[]|SimpleXMLElement $array */ private static function getArrayItemString(null|array|bool|SimpleXMLElement $array, int|string $key = 0): string { $retVal = self::getArrayItem($array, $key); return StringHelper::convertToString($retVal, false); } /** @param null|bool|mixed[]|SimpleXMLElement $array */ private static function getArrayItemIntOrSxml(null|array|bool|SimpleXMLElement $array, int|string $key = 0): int|SimpleXMLElement { $retVal = self::getArrayItem($array, $key); return (is_int($retVal) || $retVal instanceof SimpleXMLElement) ? $retVal : 0; } private static function dirAdd(null|SimpleXMLElement|string $base, null|SimpleXMLElement|string $add): string { $base = (string) $base; $add = (string) $add; return Preg::replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); } /** @return mixed[] */ private static function toCSSArray(string $style): array { $style = self::stripWhiteSpaceFromStyleString($style); $temp = explode(';', $style); $style = []; foreach ($temp as $item) { $item = explode(':', $item); if (str_contains($item[1], 'px')) { $item[1] = str_replace('px', '', $item[1]); } elseif (str_contains($item[1], 'pt')) { $item[1] = str_replace('pt', '', $item[1]); $item[1] = Font::fontSizeToPixels((float) $item[1]); } elseif (str_contains($item[1], 'in')) { $item[1] = str_replace('in', '', $item[1]); $item[1] = (int) Font::inchSizeToPixels((float) $item[1]); } elseif (str_contains($item[1], 'cm')) { $item[1] = str_replace('cm', '', $item[1]); $item[1] = (int) Font::centimeterSizeToPixels((float) $item[1]); } elseif (str_contains($item[1], 'mm')) { $item[1] = str_replace('mm', '', $item[1]); $item[1] = (int) Font::centimeterSizeToPixels((float) $item[1] / 10); } $style[$item[0]] = $item[1]; } return $style; } public static function stripWhiteSpaceFromStyleString(string $string): string { return trim(str_replace(["\r", "\n", ' '], '', $string), ';'); } private static function boolean(string $value): bool { if (is_numeric($value)) { return (bool) $value; } return $value === 'true' || $value === 'TRUE'; } /** @param string[] $hyperlinks */ private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, array $hyperlinks): void { $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; if ($hlinkClick->count() === 0) { return; } $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id']; $hyperlink = new Hyperlink( Preg::replace('/^#/', 'sheet://', $hyperlinks[$hlinkId]), self::getArrayItemString( self::getAttributes( $cellAnchor->pic->nvPicPr->cNvPr ), 'name' ) ); $objDrawing->setHyperlink($hyperlink); } private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void { if (!$xmlWorkbook->workbookProtection) { return; } $security = $excel->getSecurity(); $security->setLockRevision( self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision') ); $security->setLockStructure( self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure') ); $security->setLockWindows( self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows') ); if ($xmlWorkbook->workbookProtection['revisionsPassword']) { $security->setRevisionsPassword( (string) $xmlWorkbook->workbookProtection['revisionsPassword'], true ); } if ($xmlWorkbook->workbookProtection['revisionsAlgorithmName']) { $security->setRevisionsAlgorithmName( (string) $xmlWorkbook->workbookProtection['revisionsAlgorithmName'] ); } if ($xmlWorkbook->workbookProtection['revisionsSaltValue']) { $security->setRevisionsSaltValue( (string) $xmlWorkbook->workbookProtection['revisionsSaltValue'], false ); } if ($xmlWorkbook->workbookProtection['revisionsSpinCount']) { $security->setRevisionsSpinCount( (int) $xmlWorkbook->workbookProtection['revisionsSpinCount'] ); } if ($xmlWorkbook->workbookProtection['revisionsHashValue']) { if ($security->advancedRevisionsPassword()) { $security->setRevisionsPassword( (string) $xmlWorkbook->workbookProtection['revisionsHashValue'], true ); } } if ($xmlWorkbook->workbookProtection['workbookPassword']) { $security->setWorkbookPassword( (string) $xmlWorkbook->workbookProtection['workbookPassword'], true ); } if ($xmlWorkbook->workbookProtection['workbookAlgorithmName']) { $security->setWorkbookAlgorithmName( (string) $xmlWorkbook->workbookProtection['workbookAlgorithmName'] ); } if ($xmlWorkbook->workbookProtection['workbookSaltValue']) { $security->setWorkbookSaltValue( (string) $xmlWorkbook->workbookProtection['workbookSaltValue'], false ); } if ($xmlWorkbook->workbookProtection['workbookSpinCount']) { $security->setWorkbookSpinCount( (int) $xmlWorkbook->workbookProtection['workbookSpinCount'] ); } if ($xmlWorkbook->workbookProtection['workbookHashValue']) { if ($security->advancedPassword()) { $security->setWorkbookPassword( (string) $xmlWorkbook->workbookProtection['workbookHashValue'], true ); } } } private static function getLockValue(SimpleXMLElement $protection, string $key): ?bool { $returnValue = null; $protectKey = $protection[$key]; if (!empty($protectKey)) { $protectKey = (string) $protectKey; $returnValue = $protectKey !== 'false' && (bool) $protectKey; } return $returnValue; } /** @param mixed[][][][] $unparsedLoadedData */ private function readFormControlProperties(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void { $zip = $this->zip; if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) { return; } $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $ctrlProps = []; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') { $ctrlProps[(string) $ele['Id']] = $ele; } } /** @var mixed[][] */ $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps']; foreach ($ctrlProps as $rId => $ctrlProp) { $rId = substr($rId, 3); // rIdXXX $unparsedCtrlProps[$rId] = []; $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']); $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target']; $unparsedCtrlProps[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath'])); } unset($unparsedCtrlProps); } /** @param mixed[][][][] $unparsedLoadedData */ private function readPrinterSettings(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void { if ($this->readDataOnly) { return; } $zip = $this->zip; if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) { return; } $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $sheetPrinterSettings = []; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') { $sheetPrinterSettings[(string) $ele['Id']] = $ele; } } /** @var mixed[][] */ $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings']; foreach ($sheetPrinterSettings as $rId => $printerSettings) { $rId = substr($rId, 3); // rIdXXX if (!str_ends_with($rId, 'ps')) { $rId = $rId . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing } $unparsedPrinterSettings[$rId] = []; $target = (string) str_replace('/xl/', '../', (string) $printerSettings['Target']); $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $target); $unparsedPrinterSettings[$rId]['relFilePath'] = $target; $unparsedPrinterSettings[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath'])); } unset($unparsedPrinterSettings); } /** @return array{string, string} */ private function getWorkbookBaseName(): array { $workbookBasename = ''; $xmlNamespaceBase = ''; // check if it is an OOXML archive $rels = $this->loadZip(self::INITIAL_FILE); foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) { $rel = self::getAttributes($rel); $type = (string) $rel['Type']; switch ($type) { case Namespaces::OFFICE_DOCUMENT: case Namespaces::PURL_OFFICE_DOCUMENT: $basename = basename((string) $rel['Target']); $xmlNamespaceBase = dirname($type); if (Preg::isMatch('/workbook.*\.xml/', $basename)) { $workbookBasename = $basename; } break; } } return [$workbookBasename, $xmlNamespaceBase]; } private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void { if ($this->readDataOnly || !$xmlSheet->sheetProtection) { return; } $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName']; $protection = $docSheet->getProtection(); $protection->setAlgorithm($algorithmName); if ($algorithmName) { $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true); $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']); $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']); } else { $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true); } if ($xmlSheet->protectedRanges->protectedRange) { foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true, (string) $protectedRange['name'], (string) $protectedRange['securityDescriptor']); } } } private function readAutoFilter( SimpleXMLElement $xmlSheet, Worksheet $docSheet ): void { if ($xmlSheet && $xmlSheet->autoFilter) { (new AutoFilter($docSheet, $xmlSheet))->load(); } } private function readBackgroundImage( SimpleXMLElement $xmlSheet, Worksheet $docSheet, string $relsName ): void { if ($xmlSheet && $xmlSheet->picture) { $id = (string) self::getArrayItemString(self::getAttributes($xmlSheet->picture, Namespaces::SCHEMA_OFFICE_DOCUMENT), 'id'); $rels = $this->loadZip($relsName); foreach ($rels->Relationship as $rel) { $attrs = $rel->attributes() ?? []; $rid = (string) ($attrs['Id'] ?? ''); $target = (string) ($attrs['Target'] ?? ''); if ($rid === $id && str_starts_with($target, '..')) { $target = 'xl' . substr($target, 2); $content = $this->getFromZipArchive($this->zip, $target); $docSheet->setBackgroundImage($content); } } } } /** * @param TableDxfsStyle[] $tableStyles * @param Style[] $dxfs */ private function readTables( SimpleXMLElement $xmlSheet, Worksheet $docSheet, string $dir, string $fileWorksheet, ZipArchive $zip, string $namespaceTable, array $tableStyles, array $dxfs ): void { if ($xmlSheet && $xmlSheet->tableParts) { /** @var array{count: scalar} */ $attributes = $xmlSheet->tableParts->attributes() ?? ['count' => 0]; if (((int) $attributes['count']) > 0) { $this->readTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet, $namespaceTable, $tableStyles, $dxfs); } } } /** * @param TableDxfsStyle[] $tableStyles * @param Style[] $dxfs */ private function readTablesInTablesFile( SimpleXMLElement $xmlSheet, string $dir, string $fileWorksheet, ZipArchive $zip, Worksheet $docSheet, string $namespaceTable, array $tableStyles, array $dxfs ): void { foreach ($xmlSheet->tableParts->tablePart as $tablePart) { $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT); $tablePartRel = (string) $relation['id']; $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($relationsFileName) !== false) { $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); foreach ($relsTableReferences->Relationship as $relationship) { $relationshipAttributes = self::getAttributes($relationship, ''); if ((string) $relationshipAttributes['Id'] === $tablePartRel) { $relationshipFileName = (string) $relationshipAttributes['Target']; $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName; $relationshipFilePath = File::realpath($relationshipFilePath); if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) { $tableXml = $this->loadZip($relationshipFilePath, $namespaceTable); (new TableReader($docSheet, $tableXml))->load($tableStyles, $dxfs); } } } } } } /** @return mixed[] */ private static function extractStyles(?SimpleXMLElement $sxml, string $node1, string $node2): array { $array = []; if ($sxml && $sxml->{$node1}->{$node2}) { /** @var SimpleXMLElement */ $temp = $sxml->{$node1}->{$node2}; foreach ($temp as $node) { $array[] = $node; } } return $array; } /** @return string[] */ private static function extractPalette(?SimpleXMLElement $sxml): array { $array = []; if ($sxml && $sxml->colors->indexedColors) { foreach ($sxml->colors->indexedColors->rgbColor as $node) { $attr = $node->attributes(); if (isset($attr['rgb'])) { $array[] = (string) $attr['rgb']; } } } return $array; } private function processIgnoredErrors(SimpleXMLElement $xml, Worksheet $sheet): void { $cellCollection = $sheet->getCellCollection(); $attributes = self::getAttributes($xml); $sqref = (string) ($attributes['sqref'] ?? ''); $numberStoredAsText = (string) ($attributes['numberStoredAsText'] ?? ''); $formula = (string) ($attributes['formula'] ?? ''); $formulaRange = (string) ($attributes['formulaRange'] ?? ''); $twoDigitTextYear = (string) ($attributes['twoDigitTextYear'] ?? ''); $evalError = (string) ($attributes['evalError'] ?? ''); if (!empty($sqref)) { $explodedSqref = explode(' ', $sqref); $pattern1 = '/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/'; foreach ($explodedSqref as $sqref1) { if (Preg::isMatch($pattern1, $sqref1, $matches)) { $firstRow = $matches[2]; $firstCol = $matches[1]; if ($matches[3] !== null) { $lastCol = (string) $matches[4]; $lastRow = (string) $matches[5]; } else { $lastCol = $firstCol; $lastRow = $firstRow; } StringHelper::stringIncrement($lastCol); for ($row = $firstRow; $row <= $lastRow; ++$row) { for ($col = $firstCol; $col !== $lastCol; StringHelper::stringIncrement($col)) { if (!$cellCollection->has2("$col$row")) { continue; } if ($numberStoredAsText === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setNumberStoredAsText(true); } if ($formula === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setFormula(true); } if ($formulaRange === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setFormulaRange(true); } if ($twoDigitTextYear === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setTwoDigitTextYear(true); } if ($evalError === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setEvalError(true); } } } } } } } private static function storeFormulaAttributes(SimpleXMLElement $f, Worksheet $docSheet, string $r): void { $formulaAttributes = []; $attributes = $f->attributes(); if (isset($attributes['t'])) { $formulaAttributes['t'] = (string) $attributes['t']; } if (isset($attributes['ref'])) { $formulaAttributes['ref'] = (string) $attributes['ref']; } if (!empty($formulaAttributes)) { $docSheet->getCell($r)->setFormulaAttributes($formulaAttributes); } } private static function onlyNoteVml(string $data): bool { $data = str_replace('
', '
', $data); try { $sxml = @simplexml_load_string($data); } catch (Throwable) { $sxml = false; } if ($sxml === false) { return false; } $shapes = $sxml->children(Namespaces::URN_VML); foreach ($shapes->shape as $shape) { $clientData = $shape->children(Namespaces::URN_EXCEL); if (!isset($clientData->ClientData)) { return false; } $attrs = $clientData->ClientData->attributes(); if (!isset($attrs['ObjectType'])) { return false; } $objectType = (string) $attrs['ObjectType']; if ($objectType !== 'Note') { return false; } } return true; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/DataValidations.php ================================================ DataValidation::OPERATOR_BETWEEN, 'equal' => DataValidation::OPERATOR_EQUAL, 'greater' => DataValidation::OPERATOR_GREATERTHAN, 'greaterorequal' => DataValidation::OPERATOR_GREATERTHANOREQUAL, 'less' => DataValidation::OPERATOR_LESSTHAN, 'lessorequal' => DataValidation::OPERATOR_LESSTHANOREQUAL, 'notbetween' => DataValidation::OPERATOR_NOTBETWEEN, 'notequal' => DataValidation::OPERATOR_NOTEQUAL, ]; private const TYPE_MAPPINGS = [ 'textlength' => DataValidation::TYPE_TEXTLENGTH, ]; private int $thisRow = 0; private int $thisColumn = 0; /** @param string[] $matches */ private function replaceR1C1(array $matches): string { return AddressHelper::convertToA1($matches[0], $this->thisRow, $this->thisColumn, false); } public function loadDataValidations(SimpleXMLElement $worksheet, Spreadsheet $spreadsheet): void { $xmlX = $worksheet->children(Namespaces::URN_EXCEL); $sheet = $spreadsheet->getActiveSheet(); /** @var callable $pregCallback */ $pregCallback = [$this, 'replaceR1C1']; foreach ($xmlX->DataValidation as $dataValidation) { $combinedCells = ''; $separator = ''; $validation = new DataValidation(); // set defaults $validation->setShowDropDown(true); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setShowDropDown(true); $this->thisRow = 1; $this->thisColumn = 1; foreach ($dataValidation as $tagName => $tagValue) { $tagValue = (string) $tagValue; $tagValueLower = strtolower($tagValue); switch ($tagName) { case 'Range': foreach (explode(',', $tagValue) as $range) { $cell = ''; if (preg_match('/^R(\d+)C(\d+):R(\d+)C(\d+)$/', (string) $range, $selectionMatches) === 1) { // range $firstCell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) . $selectionMatches[1]; $cell = $firstCell . ':' . Coordinate::stringFromColumnIndex((int) $selectionMatches[4]) . $selectionMatches[3]; $this->thisRow = (int) $selectionMatches[1]; $this->thisColumn = (int) $selectionMatches[2]; $sheet->getCell($firstCell); $combinedCells .= "$separator$cell"; $separator = ' '; } elseif (preg_match('/^R(\d+)C(\d+)$/', (string) $range, $selectionMatches) === 1) { // cell $cell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) . $selectionMatches[1]; $sheet->getCell($cell); $this->thisRow = (int) $selectionMatches[1]; $this->thisColumn = (int) $selectionMatches[2]; $combinedCells .= "$separator$cell"; $separator = ' '; } elseif (preg_match('/^C(\d+)(:C(]\d+))?$/', (string) $range, $selectionMatches) === 1) { // column $firstCol = $selectionMatches[1]; $firstColString = Coordinate::stringFromColumnIndex((int) $firstCol); $lastCol = $selectionMatches[3] ?? $firstCol; $lastColString = Coordinate::stringFromColumnIndex((int) $lastCol); $firstCell = "{$firstColString}1"; $cell = "$firstColString:$lastColString"; $this->thisColumn = (int) $firstCol; $sheet->getCell($firstCell); $combinedCells .= "$separator$cell"; $separator = ' '; } elseif (preg_match('/^R(\d+)(:R(]\d+))?$/', (string) $range, $selectionMatches)) { // row $firstRow = $selectionMatches[1]; $lastRow = $selectionMatches[3] ?? $firstRow; $firstCell = "A$firstRow"; $cell = "$firstRow:$lastRow"; $this->thisRow = (int) $firstRow; $sheet->getCell($firstCell); $combinedCells .= "$separator$cell"; $separator = ' '; } } break; case 'Type': $validation->setType(self::TYPE_MAPPINGS[$tagValueLower] ?? $tagValueLower); break; case 'Qualifier': $validation->setOperator(self::OPERATOR_MAPPINGS[$tagValueLower] ?? $tagValueLower); break; case 'InputTitle': $validation->setPromptTitle($tagValue); break; case 'InputMessage': $validation->setPrompt($tagValue); break; case 'InputHide': $validation->setShowInputMessage(false); break; case 'ErrorStyle': $validation->setErrorStyle($tagValueLower); break; case 'ErrorTitle': $validation->setErrorTitle($tagValue); break; case 'ErrorMessage': $validation->setError($tagValue); break; case 'ErrorHide': $validation->setShowErrorMessage(false); break; case 'ComboHide': $validation->setShowDropDown(false); break; case 'UseBlank': $validation->setAllowBlank(true); break; case 'CellRangeList': // FIXME missing FIXME break; case 'Min': case 'Value': $tagValue = (string) preg_replace_callback(AddressHelper::R1C1_COORDINATE_REGEX, $pregCallback, $tagValue); $validation->setFormula1($tagValue); break; case 'Max': $tagValue = (string) preg_replace_callback(AddressHelper::R1C1_COORDINATE_REGEX, $pregCallback, $tagValue); $validation->setFormula2($tagValue); break; } } $sheet->setDataValidation($combinedCells, $validation); } } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/PageSettings.php ================================================ pageSetup($xmlX, $this->getPrintDefaults()); $this->printSettings = $this->printSetup($xmlX, $printSettings); //* @phpstan-ignore-line } public function loadPageSettings(Spreadsheet $spreadsheet): void { $spreadsheet->getActiveSheet()->getPageSetup() ->setPaperSize($this->printSettings->paperSize) ->setOrientation($this->printSettings->orientation) ->setScale($this->printSettings->scale) ->setVerticalCentered($this->printSettings->verticalCentered) ->setHorizontalCentered($this->printSettings->horizontalCentered) ->setPageOrder($this->printSettings->printOrder); $spreadsheet->getActiveSheet()->getPageMargins() ->setTop($this->printSettings->topMargin) ->setHeader($this->printSettings->headerMargin) ->setLeft($this->printSettings->leftMargin) ->setRight($this->printSettings->rightMargin) ->setBottom($this->printSettings->bottomMargin) ->setFooter($this->printSettings->footerMargin); } private function getPrintDefaults(): stdClass { return (object) [ 'paperSize' => 9, 'orientation' => PageSetup::ORIENTATION_DEFAULT, 'scale' => 100, 'horizontalCentered' => false, 'verticalCentered' => false, 'printOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER, 'topMargin' => 0.75, 'headerMargin' => 0.3, 'leftMargin' => 0.7, 'rightMargin' => 0.7, 'bottomMargin' => 0.75, 'footerMargin' => 0.3, ]; } private function pageSetup(SimpleXMLElement $xmlX, stdClass $printDefaults): stdClass { if (isset($xmlX->WorksheetOptions->PageSetup)) { foreach ($xmlX->WorksheetOptions->PageSetup as $pageSetupData) { foreach ($pageSetupData as $pageSetupKey => $pageSetupValue) { $pageSetupAttributes = $pageSetupValue->attributes(Namespaces::URN_EXCEL); if ($pageSetupAttributes !== null) { switch ($pageSetupKey) { case 'Layout': $this->setLayout($printDefaults, $pageSetupAttributes); break; case 'Header': $printDefaults->headerMargin = (float) $pageSetupAttributes->Margin ?: 1.0; break; case 'Footer': $printDefaults->footerMargin = (float) $pageSetupAttributes->Margin ?: 1.0; break; case 'PageMargins': $this->setMargins($printDefaults, $pageSetupAttributes); break; } } } } } return $printDefaults; } private function printSetup(SimpleXMLElement $xmlX, stdClass $printDefaults): stdClass { if (isset($xmlX->WorksheetOptions->Print)) { foreach ($xmlX->WorksheetOptions->Print as $printData) { foreach ($printData as $printKey => $printValue) { switch ($printKey) { case 'LeftToRight': $printDefaults->printOrder = PageSetup::PAGEORDER_OVER_THEN_DOWN; break; case 'PaperSizeIndex': $printDefaults->paperSize = (int) $printValue ?: 9; break; case 'Scale': $printDefaults->scale = (int) $printValue ?: 100; break; } } } } return $printDefaults; } private function setLayout(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void { $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation ?? '') ?: PageSetup::ORIENTATION_PORTRAIT; $printDefaults->horizontalCentered = (bool) $pageSetupAttributes->CenterHorizontal ?: false; $printDefaults->verticalCentered = (bool) $pageSetupAttributes->CenterVertical ?: false; } private function setMargins(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void { $printDefaults->leftMargin = (float) $pageSetupAttributes->Left ?: 1.0; $printDefaults->rightMargin = (float) $pageSetupAttributes->Right ?: 1.0; $printDefaults->topMargin = (float) $pageSetupAttributes->Top ?: 1.0; $printDefaults->bottomMargin = (float) $pageSetupAttributes->Bottom ?: 1.0; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Properties.php ================================================ spreadsheet = $spreadsheet; } /** @param string[] $namespaces */ public function readProperties(SimpleXMLElement $xml, array $namespaces): void { $this->readStandardProperties($xml); $this->readCustomProperties($xml, $namespaces); } protected function readStandardProperties(SimpleXMLElement $xml): void { if (isset($xml->DocumentProperties[0])) { $docProps = $this->spreadsheet->getProperties(); foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { $propertyValue = (string) $propertyValue; $this->processStandardProperty($docProps, $propertyName, $propertyValue); } } } /** @param string[] $namespaces */ protected function readCustomProperties(SimpleXMLElement $xml, array $namespaces): void { if (isset($xml->CustomDocumentProperties) && is_iterable($xml->CustomDocumentProperties[0])) { $docProps = $this->spreadsheet->getProperties(); foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { $propertyAttributes = self::getAttributes($propertyValue, $namespaces['dt']); $propertyName = (string) preg_replace_callback('/_x([0-9a-f]{4})_/i', [$this, 'hex2str'], $propertyName); $this->processCustomProperty($docProps, $propertyName, $propertyValue, $propertyAttributes); } } } protected function processStandardProperty( DocumentProperties $docProps, string $propertyName, string $stringValue ): void { switch ($propertyName) { case 'Title': $docProps->setTitle($stringValue); break; case 'Subject': $docProps->setSubject($stringValue); break; case 'Author': $docProps->setCreator($stringValue); break; case 'Created': $docProps->setCreated($stringValue); break; case 'LastAuthor': $docProps->setLastModifiedBy($stringValue); break; case 'LastSaved': $docProps->setModified($stringValue); break; case 'Company': $docProps->setCompany($stringValue); break; case 'Category': $docProps->setCategory($stringValue); break; case 'Manager': $docProps->setManager($stringValue); break; case 'HyperlinkBase': $docProps->setHyperlinkBase($stringValue); break; case 'Keywords': $docProps->setKeywords($stringValue); break; case 'Description': $docProps->setDescription($stringValue); break; } } protected function processCustomProperty( DocumentProperties $docProps, string $propertyName, ?SimpleXMLElement $propertyValue, SimpleXMLElement $propertyAttributes ): void { switch ((string) $propertyAttributes) { case 'boolean': $propertyType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; $propertyValue = (bool) (string) $propertyValue; break; case 'integer': $propertyType = DocumentProperties::PROPERTY_TYPE_INTEGER; $propertyValue = (int) $propertyValue; break; case 'float': $propertyType = DocumentProperties::PROPERTY_TYPE_FLOAT; $propertyValue = (float) $propertyValue; break; case 'dateTime.tz': case 'dateTime.iso8601tz': $propertyType = DocumentProperties::PROPERTY_TYPE_DATE; $propertyValue = trim((string) $propertyValue); break; default: $propertyType = DocumentProperties::PROPERTY_TYPE_STRING; $propertyValue = trim((string) $propertyValue); break; } $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); } /** @param string[] $hex */ protected function hex2str(array $hex): string { return mb_chr((int) hexdec($hex[1]), 'UTF-8'); } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('') : ($simple->attributes($node) ?? new SimpleXMLElement('')); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php ================================================ $styleAttributeValue) { $styleAttributeValue = (string) $styleAttributeValue; switch ($styleAttributeKey) { case 'Vertical': if (self::identifyFixedStyleValue(self::VERTICAL_ALIGNMENT_STYLES, $styleAttributeValue)) { $style['alignment']['vertical'] = $styleAttributeValue; } break; case 'Horizontal': if (self::identifyFixedStyleValue(self::HORIZONTAL_ALIGNMENT_STYLES, $styleAttributeValue)) { $style['alignment']['horizontal'] = $styleAttributeValue; } break; case 'WrapText': $style['alignment']['wrapText'] = true; break; case 'Rotate': $style['alignment']['textRotation'] = $styleAttributeValue; break; case 'Indent': $style['alignment']['indent'] = $styleAttributeValue; break; case 'ReadingOrder': if ($styleAttributeValue === 'RightToLeft') { $style['alignment']['readOrder'] = AlignmentStyles::READORDER_RTL; } elseif ($styleAttributeValue === 'LeftToRight') { $style['alignment']['readOrder'] = AlignmentStyles::READORDER_LTR; } break; } } return $style; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style/Border.php ================================================ [ 'continuous' => BorderStyle::BORDER_HAIR, 'dash' => BorderStyle::BORDER_DASHED, 'dashdot' => BorderStyle::BORDER_DASHDOT, 'dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, 'dot' => BorderStyle::BORDER_DOTTED, 'double' => BorderStyle::BORDER_DOUBLE, '0continuous' => BorderStyle::BORDER_HAIR, '0dash' => BorderStyle::BORDER_DASHED, '0dashdot' => BorderStyle::BORDER_DASHDOT, '0dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, '0dot' => BorderStyle::BORDER_DOTTED, '0double' => BorderStyle::BORDER_DOUBLE, '1continuous' => BorderStyle::BORDER_THIN, '1dash' => BorderStyle::BORDER_DASHED, '1dashdot' => BorderStyle::BORDER_DASHDOT, '1dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, '1dot' => BorderStyle::BORDER_DOTTED, '1double' => BorderStyle::BORDER_DOUBLE, '2continuous' => BorderStyle::BORDER_MEDIUM, '2dash' => BorderStyle::BORDER_MEDIUMDASHED, '2dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, '2dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, '2dot' => BorderStyle::BORDER_DOTTED, '2double' => BorderStyle::BORDER_DOUBLE, '3continuous' => BorderStyle::BORDER_THICK, '3dash' => BorderStyle::BORDER_MEDIUMDASHED, '3dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, '3dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, '3dot' => BorderStyle::BORDER_DOTTED, '3double' => BorderStyle::BORDER_DOUBLE, ], ]; /** * @param string[] $namespaces * * @return mixed[] */ public function parseStyle(SimpleXMLElement $styleData, array $namespaces): array { $style = []; $diagonalDirection = Borders::DIAGONAL_NONE; foreach ($styleData->Border as $borderStyle) { $borderAttributes = self::getAttributes($borderStyle, $namespaces['ss']); /** @var array{color?: array{rgb: string}, borderStyle: string} */ $thisBorder = []; $styleType = (string) $borderAttributes->Weight; $styleType .= strtolower((string) $borderAttributes->LineStyle); $thisBorder['borderStyle'] = self::BORDER_MAPPINGS['borderStyle'][$styleType] ?? BorderStyle::BORDER_NONE; $color = (string) ($borderAttributes['Color'] ?? ''); if ($color !== '') { $thisBorder['color']['rgb'] = substr($color, 1); } $position = (string) ($borderAttributes['Position'] ?? ''); if ($position !== '') { [$borderPosition, $diagonalDirection] = $this->parsePosition($position, $diagonalDirection); if ($borderPosition) { $style['borders'][$borderPosition] = $thisBorder; } elseif ($diagonalDirection !== Borders::DIAGONAL_NONE) { $style['borders']['diagonalDirection'] = $diagonalDirection; $style['borders']['diagonal'] = $thisBorder; } } } return $style; } /** @return array{0: string, 1: int} */ protected function parsePosition(string $borderStyleValue, int $diagonalDirection): array { $borderStyleValue = strtolower($borderStyleValue); $borderPosition = ''; if (in_array($borderStyleValue, self::BORDER_POSITIONS)) { $borderPosition = $borderStyleValue; } elseif ($borderStyleValue === 'diagonalleft') { $diagonalDirection = ($diagonalDirection !== Borders::DIAGONAL_NONE) ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN; } elseif ($borderStyleValue === 'diagonalright') { $diagonalDirection = ($diagonalDirection !== Borders::DIAGONAL_NONE) ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP; } return [$borderPosition, $diagonalDirection]; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style/Fill.php ================================================ [ 'solid' => FillStyles::FILL_SOLID, 'gray75' => FillStyles::FILL_PATTERN_DARKGRAY, 'gray50' => FillStyles::FILL_PATTERN_MEDIUMGRAY, 'gray25' => FillStyles::FILL_PATTERN_LIGHTGRAY, 'gray125' => FillStyles::FILL_PATTERN_GRAY125, 'gray0625' => FillStyles::FILL_PATTERN_GRAY0625, 'horzstripe' => FillStyles::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe 'vertstripe' => FillStyles::FILL_PATTERN_DARKVERTICAL, // vertical stripe 'reversediagstripe' => FillStyles::FILL_PATTERN_DARKUP, // reverse diagonal stripe 'diagstripe' => FillStyles::FILL_PATTERN_DARKDOWN, // diagonal stripe 'diagcross' => FillStyles::FILL_PATTERN_DARKGRID, // diagoanl crosshatch 'thickdiagcross' => FillStyles::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch 'thinhorzstripe' => FillStyles::FILL_PATTERN_LIGHTHORIZONTAL, 'thinvertstripe' => FillStyles::FILL_PATTERN_LIGHTVERTICAL, 'thinreversediagstripe' => FillStyles::FILL_PATTERN_LIGHTUP, 'thindiagstripe' => FillStyles::FILL_PATTERN_LIGHTDOWN, 'thinhorzcross' => FillStyles::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch 'thindiagcross' => FillStyles::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch ], ]; /** @return mixed[] */ public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValuex) { $styleAttributeValue = (string) $styleAttributeValuex; switch ($styleAttributeKey) { case 'Color': $style['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1); $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); break; case 'PatternColor': $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); break; case 'Pattern': $lcStyleAttributeValue = strtolower((string) $styleAttributeValue); $style['fill']['fillType'] = self::FILL_MAPPINGS['fillType'][$lcStyleAttributeValue] ?? FillStyles::FILL_NONE; break; } } return $style; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style/Font.php ================================================ $styleAttributeValue) { $styleAttributeValue = (string) $styleAttributeValue; switch ($styleAttributeKey) { case 'FontName': $style['font']['name'] = $styleAttributeValue; break; case 'Size': $style['font']['size'] = $styleAttributeValue; break; case 'Color': /** @var string[][][] $style */ $style['font']['color']['rgb'] = substr($styleAttributeValue, 1); break; case 'Bold': $style['font']['bold'] = $styleAttributeValue === '1'; break; case 'Italic': $style['font']['italic'] = $styleAttributeValue === '1'; break; case 'Underline': $style = $this->parseUnderline($style, $styleAttributeValue); break; case 'VerticalAlign': $style = $this->parseVerticalAlign($style, $styleAttributeValue); break; } } return $style; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php ================================================ $styleAttributeValue) { $styleAttributeValue = str_replace($fromFormats, $toFormats, (string) $styleAttributeValue); switch ($styleAttributeValue) { case 'Short Date': $styleAttributeValue = 'dd/mm/yyyy'; break; } if ($styleAttributeValue > '') { $style['numberFormat']['formatCode'] = $styleAttributeValue; } } return $style; } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php ================================================ ') : ($simple->attributes($node) ?? new SimpleXMLElement('')); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml/Style.php ================================================ children('urn:schemas-microsoft-com:office:spreadsheet'); $stylesXml = $children->Styles[0]; if (!isset($stylesXml)) { return []; } $alignmentStyleParser = new Style\Alignment(); $borderStyleParser = new Style\Border(); $fontStyleParser = new Style\Font(); $fillStyleParser = new Style\Fill(); $numberFormatStyleParser = new Style\NumberFormat(); foreach ($stylesXml as $style) { /** @var SimpleXMLElement $style */ $style_ss = self::getAttributes($style, $namespaces['ss']); $styleID = (string) $style_ss['ID']; $this->styles[$styleID] = $this->styles['Default'] ?? []; $alignment = $border = $font = $fill = $numberFormat = $protection = []; foreach ($style as $styleType => $styleDatax) { $styleData = self::getSxml($styleDatax); $styleAttributes = $styleData->attributes($namespaces['ss']); switch ($styleType) { case 'Alignment': if ($styleAttributes) { $alignment = $alignmentStyleParser->parseStyle($styleAttributes); } break; case 'Borders': $border = $borderStyleParser->parseStyle($styleData, $namespaces); break; case 'Font': if ($styleAttributes) { $font = $fontStyleParser->parseStyle($styleAttributes); } break; case 'Interior': if ($styleAttributes) { $fill = $fillStyleParser->parseStyle($styleAttributes); } break; case 'NumberFormat': if ($styleAttributes) { $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes); } break; case 'Protection': $locked = $hidden = null; $styleAttributesP = array_key_exists('x', $namespaces) ? $styleData->attributes($namespaces['x']) : []; if (isset($styleAttributes['Protected'])) { $locked = ((bool) (string) $styleAttributes['Protected']) ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED; } if (isset($styleAttributesP['HideFormula'])) { $hidden = ((bool) (string) $styleAttributesP['HideFormula']) ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED; } if ($locked !== null || $hidden !== null) { $protection['protection'] = []; if ($locked !== null) { $protection['protection']['locked'] = $locked; } if ($hidden !== null) { $protection['protection']['hidden'] = $hidden; } } break; } } $this->styles[$styleID] = array_merge($alignment, $border, $font, $fill, $numberFormat, $protection); } return $this->styles; } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('') : ($simple->attributes($node) ?? new SimpleXMLElement('')); } private static function getSxml(?SimpleXMLElement $simple): SimpleXMLElement { return ($simple !== null) ? $simple : new SimpleXMLElement(''); } } ================================================ FILE: src/PhpSpreadsheet/Reader/Xml.php ================================================ securityScanner = XmlScanner::getInstance($this); /** @var callable */ $unentity = [self::class, 'unentity']; $this->securityScanner->setAdditionalCallback($unentity); } public static function unentity(string $contents): string { $contents = preg_replace('/&(amp|lt|gt|quot|apos);/', "\u{fffe}\u{feff}\$1;", trim($contents)) ?? $contents; $contents = html_entity_decode($contents, ENT_NOQUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8'); $contents = str_replace("\u{fffe}\u{feff}", '&', $contents); return $contents; } private string $fileContents = ''; private string $xmlFailMessage = ''; /** @return mixed[] */ public static function xmlMappings(): array { return array_merge( Style\Fill::FILL_MAPPINGS, Style\Border::BORDER_MAPPINGS ); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { // Office xmlns:o="urn:schemas-microsoft-com:office:office" // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" // XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" // Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet" // XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" // XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" // MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset" // Rowset xmlns:z="#RowsetSchema" // $signature = [ 'getSecurityScannerOrThrow()->scan($data); // Why? //$data = str_replace("'", '"', $data); // fix headers with single quote $valid = true; foreach ($signature as $match) { // every part of the signature must be present if (!str_contains($data, $match)) { $valid = false; break; } } $this->fileContents = $data; return $valid; } /** @return false|SimpleXMLElement */ private function trySimpleXMLLoadStringPrivate(string $filename, string $fileOrString = 'file'): SimpleXMLElement|bool { $this->xmlFailMessage = "Cannot load invalid XML $fileOrString: " . $filename; $xml = false; try { $data = $this->fileContents; $continue = true; if ($data === '' && $fileOrString === 'file') { if ($filename === '') { $this->xmlFailMessage = 'Cannot load empty path'; $continue = false; } else { $datax = @file_get_contents($filename); $data = $datax ?: ''; $continue = $datax !== false; } } if ($continue) { $xml = @simplexml_load_string( $this->getSecurityScannerOrThrow() ->scan($data) ); } } catch (Throwable $e) { throw new Exception($this->xmlFailMessage, 0, $e); } $this->fileContents = ''; return $xml; } /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * * @return string[] */ public function listWorksheetNames(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetNames = []; $xml = $this->trySimpleXMLLoadStringPrivate($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $xml_ss = $xml->children(self::NAMESPACES_SS); foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); $worksheetNames[] = (string) $worksheet_ss['Name']; } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @return array */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetInfo = []; $xml = $this->trySimpleXMLLoadStringPrivate($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $worksheetID = 1; $xml_ss = $xml->children(self::NAMESPACES_SS); foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); $tmpInfo = []; $tmpInfo['worksheetName'] = ''; $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; $tmpInfo['totalColumns'] = 0; $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; if (isset($worksheet_ss['Name'])) { $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name']; } if (isset($worksheet->Table->Row)) { $rowIndex = 0; foreach ($worksheet->Table->Row as $rowData) { $columnIndex = 0; $rowHasData = false; foreach ($rowData->Cell as $cell) { if (isset($cell->Data)) { $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); $rowHasData = true; } ++$columnIndex; } ++$rowIndex; if ($rowHasData) { $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); } } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1, true); $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; $tmpInfo['sheetState'] = Worksheet::SHEETSTATE_VISIBLE; $worksheetInfo[] = $tmpInfo; ++$worksheetID; } return $worksheetInfo; } /** * Loads Spreadsheet from string. */ public function loadSpreadsheetFromString(string $contents): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($contents, $spreadsheet, true); } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { $spreadsheet = $this->newSpreadsheet(); $spreadsheet->setValueBinder($this->valueBinder); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file or contents into Spreadsheet instance. * * @param string $filename file name if useContents is false else file contents */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet, bool $useContents = false): Spreadsheet { if ($useContents) { $this->fileContents = $filename; $fileOrString = 'string'; } else { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $fileOrString = 'file'; } $xml = $this->trySimpleXMLLoadStringPrivate($filename, $fileOrString); if ($xml === false) { throw new Exception($this->xmlFailMessage); } $namespaces = $xml->getNamespaces(true); (new Properties($spreadsheet))->readProperties($xml, $namespaces); $this->styles = (new Style())->parseStyles($xml, $namespaces); if (isset($this->styles['Default']) && is_array($this->styles['Default'])) { $spreadsheet->getCellXfCollection()[0]->applyFromArray($this->styles['Default']); } $worksheetID = 0; $xml_ss = $xml->children(self::NAMESPACES_SS); $sheetCreated = false; /** @var null|SimpleXMLElement $worksheetx */ foreach ($xml_ss->Worksheet as $worksheetx) { $worksheet = $worksheetx ?? new SimpleXMLElement(''); $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); if ( isset($this->loadSheetsOnly, $worksheet_ss['Name']) && (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly)) ) { continue; } // Create new Worksheet $spreadsheet->createSheet(); $sheetCreated = true; $spreadsheet->setActiveSheetIndex($worksheetID); $worksheetName = ''; if (isset($worksheet_ss['Name'])) { $worksheetName = (string) $worksheet_ss['Name']; // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in // formula cells... during the load, all formulae should be correct, and we're simply bringing // the worksheet name in line with the formula, not the reverse $spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); } if (isset($worksheet_ss['Protected'])) { $protection = (string) $worksheet_ss['Protected'] === '1'; $spreadsheet->getActiveSheet()->getProtection()->setSheet($protection); } // locally scoped defined names if (isset($worksheet->Names[0])) { foreach ($worksheet->Names[0] as $definedName) { $definedName_ss = self::getAttributes($definedName, self::NAMESPACES_SS); $name = (string) $definedName_ss['Name']; $definedValue = (string) $definedName_ss['RefersTo']; $convertedValue = AddressHelper::convertFormulaToA1($definedValue); if ($convertedValue[0] === '=') { $convertedValue = substr($convertedValue, 1); } $spreadsheet->addDefinedName(DefinedName::createInstance($name, $spreadsheet->getActiveSheet(), $convertedValue, true)); } } $columnID = 'A'; if (isset($worksheet->Table->Column)) { foreach ($worksheet->Table->Column as $columnData) { $columnData_ss = self::getAttributes($columnData, self::NAMESPACES_SS); $colspan = 0; if (isset($columnData_ss['Span'])) { $spanAttr = (string) $columnData_ss['Span']; if (is_numeric($spanAttr)) { $colspan = max(0, (int) $spanAttr); } } if (isset($columnData_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $columnData_ss['Index']); } $columnWidth = null; if (isset($columnData_ss['Width'])) { $columnWidth = $columnData_ss['Width']; } $columnVisible = null; if (isset($columnData_ss['Hidden'])) { $columnVisible = ((string) $columnData_ss['Hidden']) !== '1'; } while ($colspan >= 0) { /** @var string $columnID */ if (isset($columnWidth)) { $spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4); } if (isset($columnVisible)) { $spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setVisible($columnVisible); } StringHelper::stringIncrement($columnID); --$colspan; } } } $rowID = 1; if (isset($worksheet->Table->Row)) { $additionalMergedCells = 0; foreach ($worksheet->Table->Row as $rowData) { $rowHasData = false; $row_ss = self::getAttributes($rowData, self::NAMESPACES_SS); if (isset($row_ss['Index'])) { $rowID = (int) $row_ss['Index']; } if (isset($row_ss['Hidden'])) { $rowVisible = ((string) $row_ss['Hidden']) !== '1'; $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setVisible($rowVisible); } $columnID = 'A'; foreach ($rowData->Cell as $cell) { $arrayRef = ''; $cell_ss = self::getAttributes($cell, self::NAMESPACES_SS); if (isset($cell_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $cell_ss['Index']); } $cellRange = $columnID . $rowID; if (isset($cell_ss['ArrayRange'])) { $arrayRange = (string) $cell_ss['ArrayRange']; $arrayRef = AddressHelper::convertFormulaToA1($arrayRange, $rowID, Coordinate::columnIndexFromString($columnID)); } if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { StringHelper::stringIncrement($columnID); continue; } if (isset($cell_ss['HRef'])) { $spreadsheet->getActiveSheet()->getCell($cellRange)->getHyperlink()->setUrl((string) $cell_ss['HRef']); } if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { $columnTo = $columnID; if (isset($cell_ss['MergeAcross'])) { $additionalMergedCells += (int) $cell_ss['MergeAcross']; $columnTo = Coordinate::stringFromColumnIndex((int) (Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross'])); } $rowTo = $rowID; if (isset($cell_ss['MergeDown'])) { $rowTo = $rowTo + $cell_ss['MergeDown']; } $cellRange .= ':' . $columnTo . $rowTo; $spreadsheet->getActiveSheet()->mergeCells($cellRange, Worksheet::MERGE_CELL_CONTENT_HIDE); } $hasCalculatedValue = false; $cellDataFormula = ''; if (isset($cell_ss['Formula'])) { $cellDataFormula = $cell_ss['Formula']; $hasCalculatedValue = true; if ($arrayRef !== '') { $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setFormulaAttributes(['t' => 'array', 'ref' => $arrayRef]); } } if (isset($cell->Data)) { $cellData = $cell->Data; $cellValue = (string) $cellData; $type = DataType::TYPE_NULL; $cellData_ss = self::getAttributes($cellData, self::NAMESPACES_SS); if (isset($cellData_ss['Type'])) { $cellDataType = $cellData_ss['Type']; switch ($cellDataType) { /* const TYPE_STRING = 's'; const TYPE_FORMULA = 'f'; const TYPE_NUMERIC = 'n'; const TYPE_BOOL = 'b'; const TYPE_NULL = 'null'; const TYPE_INLINE = 'inlineStr'; const TYPE_ERROR = 'e'; */ case 'String': $type = DataType::TYPE_STRING; $rich = $cellData->children('http://www.w3.org/TR/REC-html40'); if ($rich) { // in case of HTML content we extract the payload // and convert it into a rich text object $content = $cellData->asXML() ?: ''; $html = new HelperHtml(); $cellValue = $html->toRichTextObject($content, true); } break; case 'Number': $type = DataType::TYPE_NUMERIC; $cellValue = (float) $cellValue; if (floor($cellValue) == $cellValue) { $cellValue = (int) $cellValue; } break; case 'Boolean': $type = DataType::TYPE_BOOL; $cellValue = ($cellValue != 0); break; case 'DateTime': $type = DataType::TYPE_NUMERIC; $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); $cellValue = Date::PHPToExcel($dateTime); break; case 'Error': $type = DataType::TYPE_ERROR; $hasCalculatedValue = false; break; } } $originalType = $type; if ($hasCalculatedValue) { $type = DataType::TYPE_FORMULA; $columnNumber = Coordinate::columnIndexFromString($columnID); $cellDataFormula = AddressHelper::convertFormulaToA1($cellDataFormula, $rowID, $columnNumber); } $hyperlink = null; if ($spreadsheet->getActiveSheet()->hyperlinkExists($columnID . $rowID)) { $hyperlink = $spreadsheet->getActiveSheet()->getHyperlink($columnID . $rowID); } $spreadsheet->getActiveSheet() ->getCell($columnID . $rowID) ->setValueExplicit( $hasCalculatedValue ? $cellDataFormula : $cellValue, $type ); $spreadsheet->getActiveSheet() ->setHyperlink($columnID . $rowID, $hyperlink); if ($hasCalculatedValue) { $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($cellValue, $originalType === DataType::TYPE_NUMERIC); } $rowHasData = true; } if (isset($cell->Comment)) { $this->parseCellComment($cell->Comment, $spreadsheet, $columnID, $rowID); } if (isset($cell_ss['StyleID'])) { $style = (string) $cell_ss['StyleID']; if ((isset($this->styles[$style])) && is_array($this->styles[$style]) && (!empty($this->styles[$style]))) { $spreadsheet->getActiveSheet()->getStyle($cellRange) ->applyFromArray($this->styles[$style]); } } StringHelper::stringIncrement($columnID); while ($additionalMergedCells > 0) { StringHelper::stringIncrement($columnID); --$additionalMergedCells; } } if ($rowHasData) { if (isset($row_ss['Height'])) { $rowHeight = $row_ss['Height']; $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight((float) $rowHeight); } } ++$rowID; } } $dataValidations = new Xml\DataValidations(); $dataValidations->loadDataValidations($worksheet, $spreadsheet); $xmlX = $worksheet->children(Namespaces::URN_EXCEL); if (isset($xmlX->WorksheetOptions)) { if (isset($xmlX->WorksheetOptions->ShowPageBreakZoom)) { $spreadsheet->getActiveSheet()->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW); } if (isset($xmlX->WorksheetOptions->Zoom)) { $zoomScaleNormal = (int) $xmlX->WorksheetOptions->Zoom; if ($zoomScaleNormal > 0) { $spreadsheet->getActiveSheet()->getSheetView()->setZoomScaleNormal($zoomScaleNormal); $spreadsheet->getActiveSheet()->getSheetView()->setZoomScale($zoomScaleNormal); } } if (isset($xmlX->WorksheetOptions->PageBreakZoom)) { $zoomScaleNormal = (int) $xmlX->WorksheetOptions->PageBreakZoom; if ($zoomScaleNormal > 0) { $spreadsheet->getActiveSheet()->getSheetView()->setZoomScaleSheetLayoutView($zoomScaleNormal); } } if (isset($xmlX->WorksheetOptions->ShowPageBreakZoom)) { $spreadsheet->getActiveSheet()->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW); } if (isset($xmlX->WorksheetOptions->FreezePanes)) { $freezeRow = $freezeColumn = 1; if (isset($xmlX->WorksheetOptions->SplitHorizontal)) { $freezeRow = (int) $xmlX->WorksheetOptions->SplitHorizontal + 1; } if (isset($xmlX->WorksheetOptions->SplitVertical)) { $freezeColumn = (int) $xmlX->WorksheetOptions->SplitVertical + 1; } $leftTopRow = (string) $xmlX->WorksheetOptions->TopRowBottomPane; $leftTopColumn = (string) $xmlX->WorksheetOptions->LeftColumnRightPane; if (is_numeric($leftTopRow) && is_numeric($leftTopColumn)) { $leftTopCoordinate = Coordinate::stringFromColumnIndex((int) $leftTopColumn + 1) . (string) ($leftTopRow + 1); $spreadsheet->getActiveSheet()->freezePane(Coordinate::stringFromColumnIndex($freezeColumn) . (string) $freezeRow, $leftTopCoordinate, !isset($xmlX->WorksheetOptions->FrozenNoSplit)); } else { $spreadsheet->getActiveSheet()->freezePane(Coordinate::stringFromColumnIndex($freezeColumn) . (string) $freezeRow, null, !isset($xmlX->WorksheetOptions->FrozenNoSplit)); } } elseif (isset($xmlX->WorksheetOptions->SplitVertical) || isset($xmlX->WorksheetOptions->SplitHorizontal)) { if (isset($xmlX->WorksheetOptions->SplitHorizontal)) { $ySplit = (int) $xmlX->WorksheetOptions->SplitHorizontal; $spreadsheet->getActiveSheet()->setYSplit($ySplit); } if (isset($xmlX->WorksheetOptions->SplitVertical)) { $xSplit = (int) $xmlX->WorksheetOptions->SplitVertical; $spreadsheet->getActiveSheet()->setXSplit($xSplit); } if (isset($xmlX->WorksheetOptions->LeftColumnVisible) || isset($xmlX->WorksheetOptions->TopRowVisible)) { $leftTopColumn = $leftTopRow = 1; if (isset($xmlX->WorksheetOptions->LeftColumnVisible)) { $leftTopColumn = 1 + (int) $xmlX->WorksheetOptions->LeftColumnVisible; } if (isset($xmlX->WorksheetOptions->TopRowVisible)) { $leftTopRow = 1 + (int) $xmlX->WorksheetOptions->TopRowVisible; } $leftTopCoordinate = Coordinate::stringFromColumnIndex($leftTopColumn) . "$leftTopRow"; $spreadsheet->getActiveSheet()->setTopLeftCell($leftTopCoordinate); } $leftTopColumn = $leftTopRow = 1; if (isset($xmlX->WorksheetOptions->LeftColumnRightPane)) { $leftTopColumn = 1 + (int) $xmlX->WorksheetOptions->LeftColumnRightPane; } if (isset($xmlX->WorksheetOptions->TopRowBottomPane)) { $leftTopRow = 1 + (int) $xmlX->WorksheetOptions->TopRowBottomPane; } $leftTopCoordinate = Coordinate::stringFromColumnIndex($leftTopColumn) . "$leftTopRow"; $spreadsheet->getActiveSheet()->setPaneTopLeftCell($leftTopCoordinate); } (new PageSettings($xmlX))->loadPageSettings($spreadsheet); if (isset($xmlX->WorksheetOptions->TopRowVisible, $xmlX->WorksheetOptions->LeftColumnVisible)) { $leftTopRow = (string) $xmlX->WorksheetOptions->TopRowVisible; $leftTopColumn = (string) $xmlX->WorksheetOptions->LeftColumnVisible; if (is_numeric($leftTopRow) && is_numeric($leftTopColumn)) { $leftTopCoordinate = Coordinate::stringFromColumnIndex((int) $leftTopColumn + 1) . (string) ($leftTopRow + 1); $spreadsheet->getActiveSheet()->setTopLeftCell($leftTopCoordinate); } } $rangeCalculated = false; if (isset($xmlX->WorksheetOptions->Panes->Pane->RangeSelection)) { if (1 === preg_match('/^R(\d+)C(\d+):R(\d+)C(\d+)$/', (string) $xmlX->WorksheetOptions->Panes->Pane->RangeSelection, $selectionMatches)) { $selectedCell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) . $selectionMatches[1] . ':' . Coordinate::stringFromColumnIndex((int) $selectionMatches[4]) . $selectionMatches[3]; $spreadsheet->getActiveSheet()->setSelectedCells($selectedCell); $rangeCalculated = true; } } if (!$rangeCalculated) { if (isset($xmlX->WorksheetOptions->Panes->Pane->ActiveRow)) { $activeRow = (string) $xmlX->WorksheetOptions->Panes->Pane->ActiveRow; } else { $activeRow = 0; } if (isset($xmlX->WorksheetOptions->Panes->Pane->ActiveCol)) { $activeColumn = (string) $xmlX->WorksheetOptions->Panes->Pane->ActiveCol; } else { $activeColumn = 0; } if (is_numeric($activeRow) && is_numeric($activeColumn)) { $selectedCell = Coordinate::stringFromColumnIndex((int) $activeColumn + 1) . (string) ($activeRow + 1); $spreadsheet->getActiveSheet()->setSelectedCells($selectedCell); } } } if (isset($xmlX->PageBreaks)) { if (isset($xmlX->PageBreaks->ColBreaks)) { foreach ($xmlX->PageBreaks->ColBreaks->ColBreak as $colBreak) { $colBreak = (string) $colBreak->Column; $spreadsheet->getActiveSheet()->setBreak([1 + (int) $colBreak, 1], Worksheet::BREAK_COLUMN); } } if (isset($xmlX->PageBreaks->RowBreaks)) { foreach ($xmlX->PageBreaks->RowBreaks->RowBreak as $rowBreak) { $rowBreak = (string) $rowBreak->Row; $spreadsheet->getActiveSheet()->setBreak([1, (int) $rowBreak], Worksheet::BREAK_ROW); } } } ++$worksheetID; } if ($this->createBlankSheetIfNoneRead && !$sheetCreated) { $spreadsheet->createSheet(); } // Globally scoped defined names $activeSheetIndex = 0; if (isset($xml->ExcelWorkbook->ActiveSheet)) { $activeSheetIndex = (int) (string) $xml->ExcelWorkbook->ActiveSheet; } $activeWorksheet = $spreadsheet->setActiveSheetIndex($activeSheetIndex); if (isset($xml->Names[0])) { foreach ($xml->Names[0] as $definedName) { $definedName_ss = self::getAttributes($definedName, self::NAMESPACES_SS); $name = (string) $definedName_ss['Name']; $definedValue = (string) $definedName_ss['RefersTo']; $convertedValue = AddressHelper::convertFormulaToA1($definedValue); if ($convertedValue[0] === '=') { $convertedValue = substr($convertedValue, 1); } $spreadsheet->addDefinedName(DefinedName::createInstance($name, $activeWorksheet, $convertedValue)); } } // Return return $spreadsheet; } protected function parseCellComment( SimpleXMLElement $comment, Spreadsheet $spreadsheet, string $columnID, int $rowID ): void { $commentAttributes = $comment->attributes(self::NAMESPACES_SS); $author = 'unknown'; if (isset($commentAttributes->Author)) { $author = (string) $commentAttributes->Author; } $node = $comment->Data->asXML(); $annotation = strip_tags((string) $node); $spreadsheet->getActiveSheet()->getComment($columnID . $rowID) ->setAuthor($author) ->setText($this->parseRichText($annotation)); } protected function parseRichText(string $annotation): RichText { $value = new RichText(); $value->createText($annotation); return $value; } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('') : ($simple->attributes($node) ?? new SimpleXMLElement('')); } } ================================================ FILE: src/PhpSpreadsheet/ReferenceHelper.php ================================================ getBreaks(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aBreaks, [self::class, 'cellReverseSort']) : uksort($aBreaks, [self::class, 'cellSort']); foreach ($aBreaks as $cellAddress => $value) { /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { // If we're deleting, then clear any defined breaks that are within the range // of rows/columns that we're deleting $worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE); } else { // Otherwise update any affected breaks by inserting a new break at the appropriate point // and removing the old affected break $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $worksheet->setBreak($newReference, $value) ->setBreak($cellAddress, Worksheet::BREAK_NONE); } } } } /** * Update cell comments when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustComments(Worksheet $worksheet): void { $aComments = $worksheet->getComments(); $aNewComments = []; // the new array of all comments foreach ($aComments as $cellAddress => &$value) { // Any comments inside a deleted range will be ignored /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) { // Otherwise build a new array of comments indexed by the adjusted cell reference $newReference = $this->updateCellReference($cellAddress); $aNewComments[$newReference] = $value; } } // Replace the comments array with the new set of comments $worksheet->setComments($aNewComments); } /** * Update hyperlinks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustHyperlinks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aHyperlinkCollection = $worksheet->getHyperlinkCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort']) : uksort($aHyperlinkCollection, [self::class, 'cellSort']); foreach ($aHyperlinkCollection as $cellAddress => $value) { $newReference = $this->updateCellReference($cellAddress); /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { $worksheet->setHyperlink($cellAddress, null); } elseif ($cellAddress !== $newReference) { $worksheet->setHyperlink($cellAddress, null); if ($newReference) { $worksheet->setHyperlink($newReference, $value); } } } } /** * Update conditional formatting styles when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustConditionalFormatting(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aStyles = $worksheet->getConditionalStylesCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aStyles, [self::class, 'cellReverseSort']) : uksort($aStyles, [self::class, 'cellSort']); foreach ($aStyles as $cellAddress => $cfRules) { $worksheet->removeConditionalStyles($cellAddress); $newReference = $this->updateCellReference($cellAddress); foreach ($cfRules as &$cfRule) { /** @var Conditional $cfRule */ $conditions = $cfRule->getConditions(); foreach ($conditions as &$condition) { if (is_string($condition)) { /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; $condition = $this->updateFormulaReferences( $condition, $cellReferenceHelper->beforeCellAddress(), $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ); } } $cfRule->setConditions($conditions); } $worksheet->setConditionalStyles($newReference, $cfRules); } } /** * Update data validations when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows, string $beforeCellAddress): void { $aDataValidationCollection = $worksheet->getDataValidationCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort']) : uksort($aDataValidationCollection, [self::class, 'cellSort']); foreach ($aDataValidationCollection as $cellAddress => $dataValidation) { $formula = $dataValidation->getFormula1(); if ($formula !== '') { $dataValidation->setFormula1( $this->updateFormulaReferences( $formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ) ); } $formula = $dataValidation->getFormula2(); if ($formula !== '') { $dataValidation->setFormula2( $this->updateFormulaReferences( $formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ) ); } $addressParts = explode(' ', $cellAddress); $newReference = ''; $separator = ''; foreach ($addressParts as $addressPart) { $newReference .= $separator . $this->updateCellReference($addressPart); $separator = ' '; } if ($cellAddress !== $newReference) { $worksheet->setDataValidation($newReference, $dataValidation); $worksheet->setDataValidation($cellAddress, null); if ($newReference) { $worksheet->setDataValidation($newReference, $dataValidation); } } } } /** * Update merged cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustMergeCells(Worksheet $worksheet): void { $aMergeCells = $worksheet->getMergeCells(); $aNewMergeCells = []; // the new array of all merge cells foreach ($aMergeCells as $cellAddress => &$value) { $newReference = $this->updateCellReference($cellAddress); if ($newReference) { $aNewMergeCells[$newReference] = $newReference; } } $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array } /** * Update protected cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aProtectedCells = $worksheet->getProtectedCellRanges(); /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($numberOfRows >= 0 && $numberOfColumns >= 0) { foreach ($aProtectedCells as $key2 => $value) { $ranges = $value->allRanges(); $newKey = $separator = ''; foreach ($ranges as $key => $range) { $oldKey = $range[0] . (array_key_exists(1, $range) ? (':' . $range[1]) : ''); $newKey .= $separator . $this->updateCellReference($oldKey); $separator = ' '; } if ($key2 !== $newKey) { $worksheet->unprotectCells($key2); $worksheet->protectCells($newKey, $value->getPassword(), true, $value->getName(), $value->getSecurityDescriptor()); } } } else { foreach ($aProtectedCells as $key2 => $value) { $range = str_replace([' ', ',', "\0"], ["\0", ' ', ','], $key2); $extracted = Coordinate::extractAllCellReferencesInRange($range); $outArray = []; foreach ($extracted as $cellAddress) { if (!$cellReferenceHelper->cellAddressInDeleteRange($cellAddress)) { $outArray[$this->updateCellReference($cellAddress)] = 'x'; } } $outArray2 = Coordinate::mergeRangesInCollection($outArray); $newKey = implode(' ', array_keys($outArray2)); if ($key2 !== $newKey) { $worksheet->unprotectCells($key2); $worksheet->protectCells($newKey, $value->getPassword(), true, $value->getName(), $value->getSecurityDescriptor()); } } } } /** * Update column dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustColumnDimensions(Worksheet $worksheet): void { $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true); if (!empty($aColumnDimensions)) { foreach ($aColumnDimensions as $objColumnDimension) { $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1'); [$newReference] = Coordinate::coordinateFromString($newReference); if ($objColumnDimension->getColumnIndex() !== $newReference) { $objColumnDimension->setColumnIndex($newReference); } } $worksheet->refreshColumnDimensions(); } } /** * Update row dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustRowDimensions(Worksheet $worksheet, int $beforeRow, int $numberOfRows): void { $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true); if (!empty($aRowDimensions)) { foreach ($aRowDimensions as $objRowDimension) { $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex()); [, $newReference] = Coordinate::coordinateFromString($newReference); $newRoweference = (int) $newReference; if ($objRowDimension->getRowIndex() !== $newRoweference) { $objRowDimension->setRowIndex($newRoweference); } } $worksheet->refreshRowDimensions(); $copyDimension = $worksheet->getRowDimension($beforeRow - 1); for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) { $newDimension = $worksheet->getRowDimension($i); $newDimension->setRowHeight($copyDimension->getRowHeight()); $newDimension->setVisible($copyDimension->getVisible()); $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); $newDimension->setCollapsed($copyDimension->getCollapsed()); } } } /** * Insert a new column or row, updating all possible related data. * * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1') * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) * @param Worksheet $worksheet The worksheet that we're editing */ public function insertNewBefore( string $beforeCellAddress, int $numberOfColumns, int $numberOfRows, Worksheet $worksheet ): void { $remove = ($numberOfColumns < 0 || $numberOfRows < 0); if ( $this->cellReferenceHelper === null || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) ) { $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); } // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow, $beforeColumnString] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows $highestColumn = $worksheet->getHighestColumn(); $highestDataColumn = $worksheet->getHighestDataColumn(); $highestRow = $worksheet->getHighestRow(); $highestDataRow = $worksheet->getHighestDataRow(); // 1. Clear column strips if we are removing columns if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) { $this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet); } // 2. Clear row strips if we are removing rows if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) { $this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet); } // Find missing coordinates. This is important when inserting or deleting column before the last column $startRow = $startCol = 1; $startColString = 'A'; if ($numberOfRows === 0) { $startCol = $beforeColumn; $startColString = $beforeColumnString; } elseif ($numberOfColumns === 0) { $startRow = $beforeRow; } $highColumn = Coordinate::columnIndexFromString($highestDataColumn); for ($row = $startRow; $row <= $highestDataRow; ++$row) { for ($col = $startCol, $colString = $startColString; $col <= $highColumn; ++$col, StringHelper::stringIncrement($colString)) { $worksheet->getCell("$colString$row"); // create cell if it doesn't exist } } $allCoordinates = $worksheet->getCoordinates(); if ($remove) { // It's faster to reverse and pop than to use unshift, especially with large cell collections $allCoordinates = array_reverse($allCoordinates); } // Loop through cells, bottom-up, and change cell coordinate while ($coordinate = array_pop($allCoordinates)) { $cell = $worksheet->getCell($coordinate); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); // Don't update cells that are being removed if ($numberOfColumns < 0 && $cellIndex >= $beforeColumn + $numberOfColumns && $cellIndex < $beforeColumn) { continue; } // Should the cell be updated? Move value and cellXf index from one cell to another. if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // New coordinate $newColumn = $cellIndex + $numberOfColumns; $newRow = $cell->getRow() + $numberOfRows; if ($newColumn > 0 && $newRow > 0 && $newColumn <= AddressRange::MAX_COLUMN_INT && $newRow <= AddressRange::MAX_ROW) { $newCoordinate = Coordinate::stringFromColumnIndex($newColumn) . $newRow; // Update cell styles $worksheet->getCell($newCoordinate) ->setXfIndex($cell->getXfIndex()); // Insert this cell at its new location if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted $worksheet->getCell($newCoordinate) ->setValue( $this->updateFormulaReferences( $cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ) ); } else { // Cell value should not be adjusted $worksheet->getCell($newCoordinate) ->setValueExplicit($cell->getValue(), $cell->getDataType()); } } // Clear the original cell $worksheet->getCellCollection() ->delete($coordinate); } else { /* We don't need to update styles for rows/columns before our insertion position, but we do still need to adjust any formulae in those cells */ if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted $cell->setValue( $this->updateFormulaReferences( $cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ) ); } } } // Duplicate styles for the newly inserted cells $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); if ($numberOfColumns > 0 && $beforeColumn > 1) { $this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns); } if ($numberOfRows > 0 && $beforeRow - 1 > 0) { $this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows); } // Update worksheet: column dimensions $this->adjustColumnDimensions($worksheet); // Update worksheet: row dimensions $this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows); // Update worksheet: page breaks $this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: comments $this->adjustComments($worksheet); // Update worksheet: hyperlinks $this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: conditional formatting styles $this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: data validations $this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows, $beforeCellAddress); // Update worksheet: merge cells $this->adjustMergeCells($worksheet); // Update worksheet: protected cells $this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: autofilter $this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: table $this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: freeze pane if ($worksheet->getFreezePane()) { $splitCell = $worksheet->getFreezePane(); $topLeftCell = $worksheet->getTopLeftCell() ?? ''; $splitCell = $this->updateCellReference($splitCell); $topLeftCell = $this->updateCellReference($topLeftCell); $worksheet->freezePane($splitCell, $topLeftCell); } $this->updatePrintAreas($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: drawings $aDrawings = $worksheet->getDrawingCollection(); foreach ($aDrawings as $objDrawing) { $newReference = $this->updateCellReference($objDrawing->getCoordinates()); if ($objDrawing->getCoordinates() != $newReference) { $objDrawing->setCoordinates($newReference); } if ($objDrawing->getCoordinates2() !== '') { $newReference = $this->updateCellReference($objDrawing->getCoordinates2()); if ($objDrawing->getCoordinates2() != $newReference) { $objDrawing->setCoordinates2($newReference); } } } // Update workbook: define names if (count($worksheet->getParentOrThrow()->getDefinedNames()) > 0) { $this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } // Garbage collect $worksheet->garbageCollect(); } private function updatePrintAreas(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { $pageSetup = $worksheet->getPageSetup(); if (!$pageSetup->isPrintAreaSet()) { return; } $printAreas = explode(',', $pageSetup->getPrintArea()); $newPrintAreas = []; foreach ($printAreas as $printArea) { $result = $this->updatePrintArea($printArea, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($result !== '') { $newPrintAreas[] = $result; } } $result = implode(',', $newPrintAreas); if ($result === '') { $pageSetup->clearPrintArea(); } else { $pageSetup->setPrintArea($result); } } private function updatePrintArea(string $printArea, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): string { $coordinates = Coordinate::indexesFromString($beforeCellAddress); if (preg_match('/^([A-Z]{1,3})(\d{1,7}):([A-Z]{1,3})(\d{1,7})$/i', $printArea, $matches) === 1) { $firstRow = (int) $matches[2]; $lastRow = (int) $matches[4]; $firstColumnString = $matches[1]; $lastColumnString = $matches[3]; if ($numberOfRows < 0) { $affectedRow = $coordinates[1] + $numberOfRows - 1; $lastAffectedRow = $coordinates[1] - 1; if ($affectedRow >= $firstRow && $affectedRow <= $lastRow) { $newLastRow = max($affectedRow, $lastRow + $numberOfRows); if ($newLastRow >= $firstRow) { return $matches[1] . $matches[2] . ':' . $matches[3] . $newLastRow; } return ''; } if ($lastAffectedRow >= $firstRow && $affectedRow <= $lastRow) { $newFirstRow = $affectedRow + 1; $newLastRow = $lastRow + $numberOfRows; if ($newFirstRow >= 1 && $newLastRow >= $newFirstRow) { return $matches[1] . $newFirstRow . ':' . $matches[3] . $newLastRow; } return ''; } } if ($numberOfColumns < 0) { $firstColumnInt = Coordinate::columnIndexFromString($firstColumnString); $lastColumnInt = Coordinate::columnIndexFromString($lastColumnString); $affectedColumn = $coordinates[0] + $numberOfColumns - 1; $lastAffectedColumn = $coordinates[0] - 1; if ($affectedColumn >= $firstColumnInt && $affectedColumn <= $lastColumnInt) { $newLastColumnInt = max($affectedColumn, $lastColumnInt + $numberOfColumns); if ($newLastColumnInt >= $firstColumnInt) { $newLastColumnString = Coordinate::stringFromColumnIndex($newLastColumnInt); return $matches[1] . $matches[2] . ':' . $newLastColumnString . $matches[4]; } return ''; } if ($affectedColumn < $firstColumnInt && $lastAffectedColumn > $lastColumnInt) { return ''; } if ($lastAffectedColumn >= $firstColumnInt && $lastAffectedColumn <= $lastColumnInt) { $newFirstColumn = $affectedColumn + 1; $newLastColumn = $lastColumnInt + $numberOfColumns; if ($newFirstColumn >= 1 && $newLastColumn >= $newFirstColumn) { $firstString = Coordinate::stringFromColumnIndex($newFirstColumn); $lastString = Coordinate::stringFromColumnIndex($newLastColumn); return $firstString . $matches[2] . ':' . $lastString . $matches[4]; } return ''; } } } return $this->updateCellReference($printArea); } private static function matchSheetName(?string $match, string $worksheetName): bool { return $match === null || $match === '' || $match === "'\u{fffc}'" || $match === "'\u{fffb}'" || strcasecmp(trim($match, "'"), $worksheetName) === 0; } private static function sheetnameBeforeCells(string $match, string $worksheetName, string $cells): string { $toString = ($match > '') ? "$match!" : ''; return str_replace(["\u{fffc}", "'\u{fffb}'"], $worksheetName, $toString) . $cells; } /** * Update references within formulas. * * @param string $formula Formula to update * @param string $beforeCellAddress Insert before this one * @param int $numberOfColumns Number of columns to insert * @param int $numberOfRows Number of rows to insert * @param string $worksheetName Worksheet name/title * * @return string Updated formula */ public function updateFormulaReferences( string $formula = '', string $beforeCellAddress = 'A1', int $numberOfColumns = 0, int $numberOfRows = 0, string $worksheetName = '', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false ): string { $callback = fn (array $matches): string => (strcasecmp(trim($matches[2], "'"), $worksheetName) === 0) ? (($matches[2][0] === "'") ? "'\u{fffc}'!" : "'\u{fffb}'!") : "'\u{fffd}'!"; if ( $this->cellReferenceHelper === null || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) ) { $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); } // Update cell references in the formula $formulaBlocks = explode('"', $formula); $i = false; foreach ($formulaBlocks as &$formulaBlock) { // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) $i = $i === false; if ($i) { $adjustCount = 0; $newCellTokens = $cellTokens = []; // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' '; $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}"); $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences, true), 2); $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences, false), 2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4"); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = 100000; $row = 10000000 + (int) trim($match[3], '$'); $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(? 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}"); $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences, true), 0, -2); $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences, false), 0, -2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4"); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000; $row = 10000000; $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(? 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}"); $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences, true); $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences, false); if ($match[3] . $match[4] !== $modified3 . $modified4) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4"); [$column, $row] = Coordinate::coordinateFromString($match[3]); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; $row = (int) trim($row, '$') + 10000000; $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(? 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}"); $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences, null); if ($match[3] !== $modified3) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3"); [$column, $row] = Coordinate::coordinateFromString($match[3]); $columnAdditionalIndex = $column[0] === '$' ? 1 : 0; $rowAdditionalIndex = $row[0] === '$' ? 1 : 0; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; $row = (int) trim($row, '$') + 10000000; $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(? 0) { if ($numberOfColumns > 0 || $numberOfRows > 0) { krsort($cellTokens); krsort($newCellTokens); } else { ksort($cellTokens); ksort($newCellTokens); } // Update cell references in the formula $formulaBlock = str_replace('\\', '', (string) preg_replace($cellTokens, $newCellTokens, $formulaBlock)); } } } unset($formulaBlock); // Then rebuild the formula string return implode('"', $formulaBlocks); } /** * Update all cell references within a formula, irrespective of worksheet. */ public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string { $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows); if ($numberOfColumns !== 0) { $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns); } if ($numberOfRows !== 0) { $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows); } return $formula; } private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $columnLengths = array_map('strlen', array_column($splitRanges[6], 0)); $rowLengths = array_map('strlen', array_column($splitRanges[7], 0)); $columnOffsets = array_column($splitRanges[6], 1); $rowOffsets = array_column($splitRanges[7], 1); $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $columnLength = $columnLengths[$splitCount]; $rowLength = $rowLengths[$splitCount]; $columnOffset = $columnOffsets[$splitCount]; $rowOffset = $rowOffsets[$splitCount]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; if ($column[0] !== '$') { $column = ((Coordinate::columnIndexFromString($column) + $numberOfColumns) % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT; $column = Coordinate::stringFromColumnIndex($column); $rowOffset -= ($columnLength - strlen($column)); $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength); } if (!empty($row) && $row[0] !== '$') { $row = (((int) $row + $numberOfRows) % AddressRange::MAX_ROW) ?: AddressRange::MAX_ROW; $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength); } } return $formula; } private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0)); $fromColumnOffsets = array_column($splitRanges[1], 1); $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0)); $toColumnOffsets = array_column($splitRanges[2], 1); $fromColumns = $splitRanges[1]; $toColumns = $splitRanges[2]; while ($splitCount > 0) { --$splitCount; $fromColumnLength = $fromColumnLengths[$splitCount]; $toColumnLength = $toColumnLengths[$splitCount]; $fromColumnOffset = $fromColumnOffsets[$splitCount]; $toColumnOffset = $toColumnOffsets[$splitCount]; $fromColumn = $fromColumns[$splitCount][0]; $toColumn = $toColumns[$splitCount][0]; if (!empty($fromColumn) && $fromColumn[0] !== '$') { $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns); $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength); } if (!empty($toColumn) && $toColumn[0] !== '$') { $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns); $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength); } } return $formula; } private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0)); $fromRowOffsets = array_column($splitRanges[1], 1); $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0)); $toRowOffsets = array_column($splitRanges[2], 1); $fromRows = $splitRanges[1]; $toRows = $splitRanges[2]; while ($splitCount > 0) { --$splitCount; $fromRowLength = $fromRowLengths[$splitCount]; $toRowLength = $toRowLengths[$splitCount]; $fromRowOffset = $fromRowOffsets[$splitCount]; $toRowOffset = $toRowOffsets[$splitCount]; $fromRow = $fromRows[$splitCount][0]; $toRow = $toRows[$splitCount][0]; if (!empty($fromRow) && $fromRow[0] !== '$') { $fromRow = (int) $fromRow + $numberOfRows; $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength); } if (!empty($toRow) && $toRow[0] !== '$') { $toRow = (int) $toRow + $numberOfRows; $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength); } } return $formula; } /** * Update cell reference. * * @param string $cellReference Cell address or range of addresses * * @return string Updated cell range */ private function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false, ?bool $topLeft = null) { // Is it in another worksheet? Will not have to update anything. if (str_contains($cellReference, '!')) { return $cellReference; } // Is it a range or a single cell? if (!Coordinate::coordinateIsRange($cellReference)) { // Single cell /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; return $cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences, $topLeft); } // Range return $this->updateCellRange($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences); } /** * Update named formulae (i.e. containing worksheet references / named ranges). * * @param Spreadsheet $spreadsheet Object to update * @param string $oldName Old name (name to replace) * @param string $newName New name */ public function updateNamedFormulae(Spreadsheet $spreadsheet, string $oldName = '', string $newName = ''): void { if ($oldName == '') { return; } foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValueString(); if (str_contains($formula, $oldName)) { $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); $formula = str_replace($oldName . '!', $newName . '!', $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } } private function updateDefinedNames(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { foreach ($worksheet->getParentOrThrow()->getDefinedNames() as $definedName) { if ($definedName->isFormula() === false) { $this->updateNamedRange($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } else { $this->updateNamedFormula($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } } } private function updateNamedRange(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { $cellAddress = $definedName->getValue(); $asFormula = ($cellAddress[0] === '='); if ($definedName->getWorksheet() === $worksheet) { /** * If we delete the entire range that is referenced by a Named Range, MS Excel sets the value to #REF! * PhpSpreadsheet still only does a basic adjustment, so the Named Range will still reference Cells. * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF! * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace * them with a #REF! */ if ($asFormula === true) { $formula = $this->updateFormulaReferences($cellAddress, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true, true); $definedName->setValue($formula); } else { $definedName->setValue($this->updateCellReference(ltrim($cellAddress, '='), true)); } } } private function updateNamedFormula(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { if ($definedName->getWorksheet() === $worksheet) { /** * If we delete the entire range that is referenced by a Named Formula, MS Excel sets the value to #REF! * PhpSpreadsheet still only does a basic adjustment, so the Named Formula will still reference Cells. * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF! * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace * them with a #REF! */ $formula = $definedName->getValue(); $formula = $this->updateFormulaReferences($formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true); $definedName->setValue($formula); } } /** * Update cell range. * * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') * * @return string Updated cell range */ private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string { if (!Coordinate::coordinateIsRange($cellRange)) { throw new Exception('Only cell ranges may be passed to this method.'); } // Update range $range = Coordinate::splitRange($cellRange); $ic = count($range); for ($i = 0; $i < $ic; ++$i) { $jc = count($range[$i]); for ($j = 0; $j < $jc; ++$j) { /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if (ctype_alpha($range[$i][$j])) { $range[$i][$j] = Coordinate::coordinateFromString( $cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences, $onlyAbsoluteReferences, null) )[0]; } elseif (ctype_digit($range[$i][$j])) { $range[$i][$j] = Coordinate::coordinateFromString( $cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences, null) )[1]; } else { $range[$i][$j] = $cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences, null); } } } // Recreate range string return Coordinate::buildRange($range); } private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void { $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn + $numberOfColumns); $endColumnId = Coordinate::stringFromColumnIndex($beforeColumn); for ($row = 1; $row <= $highestRow - 1; ++$row) { for ($column = $startColumnId; $column !== $endColumnId; StringHelper::stringIncrement($column)) { $coordinate = $column . $row; $this->clearStripCell($worksheet, $coordinate); } } } private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void { $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn); StringHelper::stringIncrement($highestColumn); for ($column = $startColumnId; $column !== $highestColumn; StringHelper::stringIncrement($column)) { for ($row = $beforeRow + $numberOfRows; $row <= $beforeRow - 1; ++$row) { $coordinate = $column . $row; $this->clearStripCell($worksheet, $coordinate); } } } private function clearStripCell(Worksheet $worksheet, string $coordinate): void { $worksheet->removeConditionalStyles($coordinate); $worksheet->setHyperlink($coordinate, null, false); $worksheet->setDataValidation($coordinate); $worksheet->removeComment($coordinate); if ($worksheet->cellExists($coordinate)) { $worksheet->getCell($coordinate)->setValueExplicit(null, DataType::TYPE_NULL); $worksheet->getCell($coordinate)->setXfIndex(0); } } private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void { $autoFilter = $worksheet->getAutoFilter(); $autoFilterRange = $autoFilter->getRange(); if (!empty($autoFilterRange)) { if ($numberOfColumns !== 0) { $autoFilterColumns = $autoFilter->getColumns(); if (count($autoFilterColumns) > 0) { $column = ''; $row = 0; sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString((string) $column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); if ($columnIndex <= $rangeEnd[0]) { if ($numberOfColumns < 0) { $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter); } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in autofilter range if ($numberOfColumns > 0) { $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); } else { $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); } } } } $worksheet->setAutoFilter( $this->updateCellReference($autoFilterRange) ); } } /** @param mixed[] $autoFilterColumns */ private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void { // If we're actually deleting any columns that fall within the autofilter range, // then we delete any rules for those columns $deleteColumn = $columnIndex + $numberOfColumns - 1; $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); if (isset($autoFilterColumns[$columnName])) { $autoFilter->clearColumn($columnName); } ++$deleteColumn; } } private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void { $startColRef = $startCol; $endColRef = $rangeEnd; $toColRef = $rangeEnd + $numberOfColumns; do { $autoFilter->shiftColumn( Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef) ); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); do { $autoFilter->shiftColumn($startColID, $toColID); StringHelper::stringIncrement($toColID); StringHelper::stringIncrement($startColID); } while ($startColID !== $endColID); } private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void { $tableCollection = $worksheet->getTableCollection(); foreach ($tableCollection as $table) { $tableRange = $table->getRange(); if (!empty($tableRange)) { if ($numberOfColumns !== 0) { $tableColumns = $table->getColumns(); if (count($tableColumns) > 0) { $column = ''; $row = 0; sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString((string) $column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange); if ($columnIndex <= $rangeEnd[0]) { if ($numberOfColumns < 0) { $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table); } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in table range if ($numberOfColumns > 0) { $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table); } else { $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table); } } } } $table->setRange($this->updateCellReference($tableRange)); } } } /** @param mixed[] $tableColumns */ private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void { // If we're actually deleting any columns that fall within the table range, // then we delete any rules for those columns $deleteColumn = $columnIndex + $numberOfColumns - 1; $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); if (isset($tableColumns[$columnName])) { $table->clearColumn($columnName); } ++$deleteColumn; } } private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void { $startColRef = $startCol; $endColRef = $rangeEnd; $toColRef = $rangeEnd + $numberOfColumns; do { $table->shiftColumn( Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef) ); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); do { $table->shiftColumn($startColID, $toColID); StringHelper::stringIncrement($toColID); StringHelper::stringIncrement($startColID); } while ($startColID !== $endColID); } private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void { $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1); for ($i = $beforeRow; $i <= $highestRow; ++$i) { // Style $coordinate = $beforeColumnName . $i; if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { if (!empty($xfIndex) || $worksheet->cellExists([$j, $i])) { $worksheet->getCell([$j, $i])->setXfIndex($xfIndex); } } } } } private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void { $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) { if (!empty($xfIndex) || $worksheet->cellExists([$i, $j])) { $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); } } } } } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning a Singleton is not allowed!'); } } ================================================ FILE: src/PhpSpreadsheet/RichText/ITextElement.php ================================================ richTextElements = []; // Rich-Text string attached to cell? if ($cell !== null) { // Add cell text and style if ($cell->getValueString() !== '') { $objRun = new Run($cell->getValueString()); $objRun->setFont(clone $cell->getWorksheet()->getStyle($cell->getCoordinate())->getFont()); $this->addText($objRun); } // Set parent value $cell->setValueExplicit($this, DataType::TYPE_STRING); } } /** * Add text. * * @param ITextElement $text Rich text element * * @return $this */ public function addText(ITextElement $text): static { $this->richTextElements[] = $text; return $this; } /** * Create text. * * @param string $text Text */ public function createText(string $text): TextElement { $objText = new TextElement($text); $this->addText($objText); return $objText; } /** * Create text run. * * @param string $text Text */ public function createTextRun(string $text): Run { $objText = new Run($text); $this->addText($objText); return $objText; } /** * Get plain text. */ public function getPlainText(): string { // Return value $returnValue = ''; // Loop through all ITextElements foreach ($this->richTextElements as $text) { $returnValue .= $text->getText(); } return $returnValue; } /** * Convert to string. */ public function __toString(): string { return $this->getPlainText(); } /** * Get Rich Text elements. * * @return ITextElement[] */ public function getRichTextElements(): array { return $this->richTextElements; } /** * Set Rich Text elements. * * @param ITextElement[] $textElements Array of elements * * @return $this */ public function setRichTextElements(array $textElements): static { $this->richTextElements = $textElements; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { $hashElements = ''; foreach ($this->richTextElements as $element) { $hashElements .= $element->getHashCode(); } return md5( $hashElements . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { $newValue = is_object($value) ? (clone $value) : $value; if (is_array($value)) { $newValue = []; foreach ($value as $key2 => $value2) { $newValue[$key2] = is_object($value2) ? (clone $value2) : $value2; } } $this->$key = $newValue; } } } ================================================ FILE: src/PhpSpreadsheet/RichText/Run.php ================================================ font = new Font(); } /** * Get font. */ public function getFont(): ?Font { return $this->font; } public function getFontOrThrow(): Font { if ($this->font === null) { throw new SpreadsheetException('unexpected null font'); } return $this->font; } /** * Set font. * * @param ?Font $font Font * * @return $this */ public function setFont(?Font $font = null): static { $this->font = $font; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->getText() . (($this->font === null) ? '' : $this->font->getHashCode()) . __CLASS__ ); } } ================================================ FILE: src/PhpSpreadsheet/RichText/TextElement.php ================================================ text = $text; } /** * Get text. * * @return string Text */ public function getText(): string { return $this->text; } /** * Set text. * * @param string $text Text * * @return $this */ public function setText(string $text): self { $this->text = $text; return $this; } /** * Get font. For this class, the return value is always null. */ public function getFont(): ?Font { return null; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->text . __CLASS__ ); } } ================================================ FILE: src/PhpSpreadsheet/Settings.php ================================================ */ private static ?string $chartRenderer = null; /** * The cache implementation to be used for cell collection. */ private static ?CacheInterface $cache = null; private static mixed $httpClient = null; private static mixed $requestFactory = null; /** * Set the locale code to use for formula translations and any special formatting. * * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") * * @return bool Success or failure */ public static function setLocale(string $locale): bool { return Calculation::getInstance()->setLocale($locale); } public static function getLocale(): string { return Calculation::getInstance()->getLocale(); } /** * Identify to PhpSpreadsheet the external library to use for rendering charts. * * @param class-string $rendererClassName Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function setChartRenderer(string $rendererClassName): void { // We want phpstan to validate caller, but still need this test if (!is_a($rendererClassName, IRenderer::class, true)) { //* @phpstan-ignore-line throw new Exception('Chart renderer must implement ' . IRenderer::class); } self::$chartRenderer = $rendererClassName; } public static function unsetChartRenderer(): void { self::$chartRenderer = null; } /** * Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use. * * @return null|class-string Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function getChartRenderer(): ?string { return self::$chartRenderer; } public static function htmlEntityFlags(): int { return ENT_COMPAT; } /** * Sets the implementation of cache that should be used for cell collection. */ public static function setCache(?CacheInterface $cache): void { self::$cache = $cache; } /** * Gets the implementation of cache that is being used for cell collection. */ public static function getCache(): CacheInterface { if (!self::$cache) { self::$cache = self::useSimpleCacheVersion3() ? new Memory\SimpleCache3() : new Memory\SimpleCache1(); } return self::$cache; } public static function useSimpleCacheVersion3(): bool { return (new ReflectionClass(CacheInterface::class))->getMethod('get')->getReturnType() !== null; } /** * Set the HTTP client implementation to be used for network request. * * @deprecated 5.4.0 No replacement. * * @codeCoverageIgnore */ public static function setHttpClient(mixed $httpClient, mixed $requestFactory): void { self::$httpClient = $httpClient; self::$requestFactory = $requestFactory; } /** * Unset the HTTP client configuration. * * @deprecated 5.4.0 No replacement. * * @codeCoverageIgnore */ public static function unsetHttpClient(): void { self::$httpClient = null; self::$requestFactory = null; } /** * Get the HTTP client implementation to be used for network request. * * @deprecated 5.4.0 No replacement. * * @codeCoverageIgnore */ public static function getHttpClient(): mixed { return self::$httpClient; } /** * Get the HTTP request factory. * * @deprecated 5.4.0 No replacement. * * @codeCoverageIgnore */ public static function getRequestFactory(): mixed { return self::$requestFactory; } } ================================================ FILE: src/PhpSpreadsheet/Shared/CodePage.php ================================================ |string> */ private static array $pageArray = [ 0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program 367 => 'ASCII', // ASCII 437 => 'CP437', // OEM US //720 => 'notsupported', // OEM Arabic 737 => 'CP737', // OEM Greek 775 => 'CP775', // OEM Baltic 850 => 'CP850', // OEM Latin I 852 => 'CP852', // OEM Latin II (Central European) 855 => 'CP855', // OEM Cyrillic 857 => 'CP857', // OEM Turkish 858 => 'CP858', // OEM Multilingual Latin I with Euro 860 => 'CP860', // OEM Portugese 861 => 'CP861', // OEM Icelandic 862 => 'CP862', // OEM Hebrew 863 => 'CP863', // OEM Canadian (French) 864 => 'CP864', // OEM Arabic 865 => 'CP865', // OEM Nordic 866 => 'CP866', // OEM Cyrillic (Russian) 869 => 'CP869', // OEM Greek (Modern) 874 => 'CP874', // ANSI Thai 932 => 'CP932', // ANSI Japanese Shift-JIS 936 => 'CP936', // ANSI Chinese Simplified GBK 949 => 'CP949', // ANSI Korean (Wansung) 950 => 'CP950', // ANSI Chinese Traditional BIG5 1200 => 'UTF-16LE', // UTF-16 (BIFF8) 1250 => 'CP1250', // ANSI Latin II (Central European) 1251 => 'CP1251', // ANSI Cyrillic 1252 => 'CP1252', // ANSI Latin I (BIFF4-BIFF7) 1253 => 'CP1253', // ANSI Greek 1254 => 'CP1254', // ANSI Turkish 1255 => 'CP1255', // ANSI Hebrew 1256 => 'CP1256', // ANSI Arabic 1257 => 'CP1257', // ANSI Baltic 1258 => 'CP1258', // ANSI Vietnamese 1361 => 'CP1361', // ANSI Korean (Johab) 10000 => 'MAC', // Apple Roman 10001 => 'CP932', // Macintosh Japanese 10002 => 'CP950', // Macintosh Chinese Traditional 10003 => 'CP1361', // Macintosh Korean 10004 => 'MACARABIC', // Apple Arabic 10005 => 'MACHEBREW', // Apple Hebrew 10006 => 'MACGREEK', // Macintosh Greek 10007 => 'MACCYRILLIC', // Macintosh Cyrillic 10008 => 'CP936', // Macintosh - Simplified Chinese (GB 2312) 10010 => 'MACROMANIA', // Macintosh Romania 10017 => 'MACUKRAINE', // Macintosh Ukraine 10021 => 'MACTHAI', // Macintosh Thai 10029 => ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], // Macintosh Central Europe 10079 => 'MACICELAND', // Macintosh Icelandic 10081 => 'MACTURKISH', // Macintosh Turkish 10082 => 'MACCROATIAN', // Macintosh Croatian 21010 => 'UTF-16LE', // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE 32768 => 'MAC', // Apple Roman //32769 => 'unsupported', // ANSI Latin I (BIFF2-BIFF3) 65000 => 'UTF-7', // Unicode (UTF-7) 65001 => 'UTF-8', // Unicode (UTF-8) 99999 => ['unsupported'], // Unicode (UTF-8) ]; public static function validate(string $codePage): bool { return in_array($codePage, self::$pageArray, true); } /** * Convert Microsoft Code Page Identifier to Code Page Name which iconv * and mbstring understands. * * @param int $codePage Microsoft Code Page Identifier * * @return string Code Page Name */ public static function numberToName(int $codePage): string { if (array_key_exists($codePage, self::$pageArray)) { $value = self::$pageArray[$codePage]; if (is_array($value)) { foreach ($value as $encoding) { if (@iconv('UTF-8', $encoding, ' ') !== false) { self::$pageArray[$codePage] = $encoding; return $encoding; } } throw new PhpSpreadsheetException("Code page $codePage not implemented on this system."); } else { return $value; } } if ($codePage == 720 || $codePage == 32769) { throw new PhpSpreadsheetException("Code page $codePage not supported."); // OEM Arabic } throw new PhpSpreadsheetException('Unknown codepage: ' . $codePage); } /** @return array|string> */ public static function getEncodings(): array { return self::$pageArray; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Date.php ================================================ 'January', 'Feb' => 'February', 'Mar' => 'March', 'Apr' => 'April', 'May' => 'May', 'Jun' => 'June', 'Jul' => 'July', 'Aug' => 'August', 'Sep' => 'September', 'Oct' => 'October', 'Nov' => 'November', 'Dec' => 'December', ]; /** * @var string[] */ public static array $numberSuffixes = [ 'st', 'nd', 'rd', 'th', ]; /** * Base calendar year to use for calculations * Value is either CALENDAR_WINDOWS_1900 (1900) or CALENDAR_MAC_1904 (1904). */ protected static int $excelCalendar = self::CALENDAR_WINDOWS_1900; /** * Default timezone to use for DateTime objects. */ protected static ?DateTimeZone $defaultTimeZone = null; /** * Set the Excel calendar (Windows 1900 or Mac 1904). * * @param ?int $baseYear Excel base date (1900 or 1904) * * @return bool Success or failure */ public static function setExcelCalendar(?int $baseYear): bool { if ( ($baseYear === self::CALENDAR_WINDOWS_1900) || ($baseYear === self::CALENDAR_MAC_1904) ) { self::$excelCalendar = $baseYear; return true; } return false; } /** * Return the Excel calendar (Windows 1900 or Mac 1904). * * @return int Excel base date (1900 or 1904) */ public static function getExcelCalendar(): int { return self::$excelCalendar; } /** * Set the Default timezone to use for dates. * * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions * * @return bool Success or failure */ public static function setDefaultTimezone($timeZone): bool { try { $timeZone = self::validateTimeZone($timeZone); self::$defaultTimeZone = $timeZone; $retval = true; } catch (PhpSpreadsheetException) { $retval = false; } return $retval; } /** * Return the Default timezone, or UTC if default not set. */ public static function getDefaultTimezone(): DateTimeZone { return self::$defaultTimeZone ?? new DateTimeZone('UTC'); } /** * Return the Default timezone, or local timezone if default is not set. */ public static function getDefaultOrLocalTimezone(): DateTimeZone { return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get()); } /** * Return the Default timezone even if null. */ public static function getDefaultTimezoneOrNull(): ?DateTimeZone { return self::$defaultTimeZone; } /** * Validate a timezone. * * @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object * * @return ?DateTimeZone The timezone as a timezone object */ private static function validateTimeZone($timeZone): ?DateTimeZone { if ($timeZone instanceof DateTimeZone || $timeZone === null) { return $timeZone; } if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) { return new DateTimeZone($timeZone); } throw new PhpSpreadsheetException('Invalid timezone'); } /** * @param mixed $value Converts a date/time in ISO-8601 standard format date string to an Excel * serialized timestamp. * See https://en.wikipedia.org/wiki/ISO_8601 for details of the ISO-8601 standard format. */ public static function convertIsoDate(mixed $value): float|int { if (!is_string($value)) { throw new Exception('Non-string value supplied for Iso Date conversion'); } $date = new DateTime($value); $dateErrors = DateTime::getLastErrors(); if (is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0)) { throw new Exception("Invalid string $value supplied for datatype Date"); } $newValue = self::dateTimeToExcel($date); if (preg_match('/^\s*\d?\d:\d\d(:\d\d([.]\d+)?)?\s*(am|pm)?\s*$/i', $value) == 1) { $newValue = fmod($newValue, 1.0); } return $newValue; } /** * Convert a MS serialized datetime value from Excel to a PHP Date/Time object. * * @param float|int $excelTimestamp MS Excel serialized date/time value * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp, * if you don't want to treat it as a UTC value * Use the default (UTC) unless you absolutely need a conversion * * @return DateTime PHP date/time object */ public static function excelToDateTimeObject(float|int $excelTimestamp, null|DateTimeZone|string $timeZone = null): DateTime { $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone); if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) { // Unix timestamp base date $baseDate = new DateTime('1970-01-01', $timeZone); } else { // MS Excel calendar base dates if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) { // Allow adjustment for 1900 Leap Year in MS Excel $baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone); } else { $baseDate = new DateTime('1904-01-01', $timeZone); } } } else { $baseDate = new DateTime('1899-12-30', $timeZone); } if (is_int($excelTimestamp)) { if ($excelTimestamp >= 0) { return $baseDate->modify("+ $excelTimestamp days"); } return $baseDate->modify("$excelTimestamp days"); } $days = floor($excelTimestamp); $partDay = $excelTimestamp - $days; $hms = 86400 * $partDay; $microseconds = (int) round(fmod($hms, 1) * 1000000); $hms = (int) floor($hms); $hours = intdiv($hms, 3600); $hms -= $hours * 3600; $minutes = intdiv($hms, 60); $seconds = $hms % 60; if ($days >= 0) { $days = '+' . $days; } $interval = $days . ' days'; return $baseDate->modify($interval) ->setTime($hours, $minutes, $seconds, $microseconds); } /** * Convert a MS serialized datetime value from Excel to a unix timestamp. * The use of Unix timestamps, and therefore this function, is discouraged. * They are not Y2038-safe on a 32-bit system, and have no timezone info. * * @param float|int $excelTimestamp MS Excel serialized date/time value * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp, * if you don't want to treat it as a UTC value * Use the default (UTC) unless you absolutely need a conversion * * @return int Unix timetamp for this date/time */ public static function excelToTimestamp($excelTimestamp, $timeZone = null): int { $dto = self::excelToDateTimeObject($excelTimestamp, $timeZone); self::roundMicroseconds($dto); return (int) $dto->format('U'); } /** * Convert a date from PHP to an MS Excel serialized date/time value. * * @param mixed $dateValue PHP DateTime object or a string - Unix timestamp is also permitted, but discouraged; * not Y2038-safe on a 32-bit system, and no timezone info * * @return false|float Excel date/time value * or boolean FALSE on failure */ public static function PHPToExcel(mixed $dateValue) { if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) { return self::dateTimeToExcel($dateValue); } elseif (is_numeric($dateValue)) { return self::timestampToExcel($dateValue); } elseif (is_string($dateValue)) { return self::stringToExcel($dateValue); } return false; } /** * Convert a PHP DateTime object to an MS Excel serialized date/time value. * * @param DateTimeInterface $dateValue PHP DateTime object * * @return float MS Excel serialized date/time value */ public static function dateTimeToExcel(DateTimeInterface $dateValue): float { $seconds = (float) sprintf('%d.%06d', $dateValue->format('s'), $dateValue->format('u')); return self::formattedPHPToExcel( (int) $dateValue->format('Y'), (int) $dateValue->format('m'), (int) $dateValue->format('d'), (int) $dateValue->format('H'), (int) $dateValue->format('i'), $seconds ); } /** * Convert a Unix timestamp to an MS Excel serialized date/time value. * The use of Unix timestamps, and therefore this function, is discouraged. * They are not Y2038-safe on a 32-bit system, and have no timezone info. * * @param float|int|string $unixTimestamp Unix Timestamp * * @return false|float MS Excel serialized date/time value */ public static function timestampToExcel($unixTimestamp): bool|float { if (!is_numeric($unixTimestamp)) { return false; } return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp)); } /** * formattedPHPToExcel. * * @return float Excel date/time value */ public static function formattedPHPToExcel(int $year, int $month, int $day, int $hours = 0, int $minutes = 0, float|int $seconds = 0): float { if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) { // // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel // This affects every date following 28th February 1900 // $excel1900isLeapYear = true; if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = false; } $myexcelBaseDate = 2415020; } else { $myexcelBaseDate = 2416481; $excel1900isLeapYear = false; } // Julian base date Adjustment if ($month > 2) { $month -= 3; } else { $month += 9; --$year; } // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) $century = (int) substr((string) $year, 0, 2); $decade = (int) substr((string) $year, 2, 2); $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear; $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; return (float) $excelDate + $excelTime; } /** * Is a given cell a date/time? */ public static function isDateTime(Cell $cell, mixed $value = null, bool $dateWithoutTimeOkay = true): bool { $result = false; $worksheet = $cell->getWorksheetOrNull(); $spreadsheet = ($worksheet === null) ? null : $worksheet->getParent(); if ($worksheet !== null && $spreadsheet !== null) { $index = $spreadsheet->getActiveSheetIndex(); $selected = $worksheet->getSelectedCells(); try { if ($value === null) { $value = Functions::flattenSingleValue( $cell->getCalculatedValue() ); } if (is_numeric($value)) { $result = self::isDateTimeFormat( $worksheet->getStyle( $cell->getCoordinate() )->getNumberFormat(), $dateWithoutTimeOkay ); /** @var float|int $value */ self::excelToDateTimeObject($value); } } catch (Throwable) { $result = false; } $worksheet->setSelectedCells($selected); $spreadsheet->setActiveSheetIndex($index); } return $result; } /** * Is a given NumberFormat code a date/time format code? */ public static function isDateTimeFormat(NumberFormat $excelFormatCode, bool $dateWithoutTimeOkay = true): bool { return self::isDateTimeFormatCode((string) $excelFormatCode->getFormatCode(), $dateWithoutTimeOkay); } private const POSSIBLE_DATETIME_FORMAT_CHARACTERS = 'eymdHs'; private const POSSIBLE_TIME_FORMAT_CHARACTERS = 'Hs'; // note - no 'm' due to ambiguity /** * Is a given number format code a date/time? */ public static function isDateTimeFormatCode(string $excelFormatCode, bool $dateWithoutTimeOkay = true): bool { if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) { // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check) return false; } if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) { // Scientific format return false; } // Switch on formatcode $excelFormatCode = (string) NumberFormat::convertSystemFormats($excelFormatCode); if (in_array($excelFormatCode, NumberFormat::DATE_TIME_OR_DATETIME_ARRAY, true)) { return $dateWithoutTimeOkay || in_array($excelFormatCode, NumberFormat::TIME_OR_DATETIME_ARRAY); } // Typically number, currency or accounting (or occasionally fraction) formats if ((str_starts_with($excelFormatCode, '_')) || (str_starts_with($excelFormatCode, '0 '))) { return false; } // Some "special formats" provided in German Excel versions were detected as date time value, // so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany). if (str_contains($excelFormatCode, '-00000')) { return false; } $possibleFormatCharacters = $dateWithoutTimeOkay ? self::POSSIBLE_DATETIME_FORMAT_CHARACTERS : self::POSSIBLE_TIME_FORMAT_CHARACTERS; // Try checking for any of the date formatting characters that don't appear within square braces if (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $excelFormatCode)) { // We might also have a format mask containing quoted strings... // we don't want to test for any of our characters within the quoted blocks if (str_contains($excelFormatCode, '"')) { $segMatcher = false; foreach (explode('"', $excelFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) $segMatcher = $segMatcher === false; if ( $segMatcher && (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $subVal)) ) { return true; } } return false; } return true; } // No date... return false; } /** * Convert a date/time string to Excel time. * * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' * * @return false|float Excel date/time serial value */ public static function stringToExcel(string $dateValue): bool|float { if (strlen($dateValue) < 2) { return false; } if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2}([.]\d+)?)?)?$/iu', $dateValue)) { return false; } $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue); if (!is_float($dateValueNew)) { return false; } if (str_contains($dateValue, ':')) { $timeValue = DateTimeExcel\TimeValue::fromString($dateValue); if (!is_float($timeValue)) { return false; } $dateValueNew += $timeValue; } return $dateValueNew; } /** * Converts a month name (either a long or a short name) to a month number. * * @param string $monthName Month name or abbreviation * * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name */ public static function monthStringToNumber(string $monthName) { $monthIndex = 1; foreach (self::$monthNames as $shortMonthName => $longMonthName) { if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) { return $monthIndex; } ++$monthIndex; } return $monthName; } /** * Strips an ordinal from a numeric value. * * @param string $day Day number with an ordinal * * @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric */ public static function dayStringToNumber(string $day) { $strippedDayValue = (str_replace(self::$numberSuffixes, '', $day)); if (is_numeric($strippedDayValue)) { return (int) $strippedDayValue; } return $day; } public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime { $dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime(); $dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone()); return $dtobj; } public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string { $dtobj = self::dateTimeFromTimestamp($date, $timeZone); return $dtobj->format($format); } /** * Round the given DateTime object to seconds. */ public static function roundMicroseconds(DateTime $dti): void { $microseconds = (int) $dti->format('u'); $rounded = (int) round($microseconds, -6); $modify = $rounded - $microseconds; if ($modify !== 0) { $dti->modify(($modify > 0 ? '+' : '') . $modify . ' microseconds'); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/Drawing.php ================================================ getName(); $size = $defaultFont->getSize(); $sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size"; if (isset(Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex])) { // Exact width can be determined return $pixelValue * Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['width'] / Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['px']; } // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 return $pixelValue * 11 * Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width'] / Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] / $size; } /** * Convert column width from (intrinsic) Excel units to pixels. * * @param float $cellWidth Value in cell dimension * @param \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Default font of the workbook * * @return int Value in pixels */ public static function cellDimensionToPixels(float $cellWidth, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont): int { // Font name and size $name = $defaultFont->getName(); $size = $defaultFont->getSize(); $sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size"; if (isset(Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex])) { // Exact width can be determined $colWidth = $cellWidth * Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['px'] / Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 $colWidth = $cellWidth * $size * Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] / Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width'] / 11; } // Round pixels to closest integer $colWidth = (int) round($colWidth); return $colWidth; } /** * Convert pixels to points. * * @param int $pixelValue Value in pixels * * @return float Value in points */ public static function pixelsToPoints(int $pixelValue): float { return $pixelValue * 0.75; } /** * Convert points to pixels. * * @param float|int $pointValue Value in points * * @return int Value in pixels */ public static function pointsToPixels($pointValue): int { return (int) ceil($pointValue / 0.75); } /** * Convert degrees to angle. * * @param int $degrees Degrees * * @return int Angle */ public static function degreesToAngle(int $degrees): int { return (int) round($degrees * 60000); } /** * Convert angle to degrees. * * @param int|SimpleXMLElement $angle Angle * * @return int Degrees */ public static function angleToDegrees($angle): int { $angle = (int) $angle; if ($angle != 0) { return (int) round($angle / 60000); } return 0; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php ================================================ parent = $parent; } /** * Get the parent Shape Group Container. */ public function getParent(): SpgrContainer { return $this->parent; } /** * Set whether this is a group shape. */ public function setSpgr(bool $value): void { $this->spgr = $value; } /** * Get whether this is a group shape. */ public function getSpgr(): bool { return $this->spgr; } /** * Set the shape type. */ public function setSpType(int $value): void { $this->spType = $value; } /** * Get the shape type. */ public function getSpType(): int { return $this->spType; } /** * Set the shape flag. */ public function setSpFlag(int $value): void { $this->spFlag = $value; } /** * Get the shape flag. */ public function getSpFlag(): int { return $this->spFlag; } /** * Set the shape index. */ public function setSpId(int $value): void { $this->spId = $value; } /** * Get the shape index. */ public function getSpId(): int { return $this->spId; } /** * Set an option for the Shape Group Container. * * @param int $property The number specifies the option */ public function setOPT(int $property, mixed $value): void { $this->OPT[$property] = $value; } /** * Get an option for the Shape Group Container. * * @param int $property The number specifies the option */ public function getOPT(int $property): mixed { return $this->OPT[$property] ?? null; } /** * Get the collection of options. * * @return mixed[] */ public function getOPTCollection(): array { return $this->OPT; } /** * Set cell coordinates of upper-left corner of shape. * * @param string $value eg: 'A1' */ public function setStartCoordinates(string $value): void { $this->startCoordinates = $value; } /** * Get cell coordinates of upper-left corner of shape. */ public function getStartCoordinates(): string { return $this->startCoordinates; } /** * Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width. */ public function setStartOffsetX(int|float $startOffsetX): void { $this->startOffsetX = $startOffsetX; } /** * Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width. */ public function getStartOffsetX(): int|float { return $this->startOffsetX; } /** * Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height. */ public function setStartOffsetY(int|float $startOffsetY): void { $this->startOffsetY = $startOffsetY; } /** * Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height. */ public function getStartOffsetY(): int|float { return $this->startOffsetY; } /** * Set cell coordinates of bottom-right corner of shape. * * @param string $value eg: 'A1' */ public function setEndCoordinates(string $value): void { $this->endCoordinates = $value; } /** * Get cell coordinates of bottom-right corner of shape. */ public function getEndCoordinates(): string { return $this->endCoordinates; } /** * Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width. */ public function setEndOffsetX(int|float $endOffsetX): void { $this->endOffsetX = $endOffsetX; } /** * Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width. */ public function getEndOffsetX(): int|float { return $this->endOffsetX; } /** * Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height. */ public function setEndOffsetY(int|float $endOffsetY): void { $this->endOffsetY = $endOffsetY; } /** * Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height. */ public function getEndOffsetY(): int|float { return $this->endOffsetY; } /** * Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and * the dgContainer. A value of 1 = immediately within first spgrContainer * Higher nesting level occurs if and only if spContainer is part of a shape group. * * @return int Nesting level */ public function getNestingLevel(): int { $nestingLevel = 0; $parent = $this->getParent(); while ($parent instanceof SpgrContainer) { ++$nestingLevel; $parent = $parent->getParent(); } return $nestingLevel; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php ================================================ parent = $parent; } /** * Get the parent Shape Group Container if any. */ public function getParent(): ?self { return $this->parent; } /** * Add a child. This will be either spgrContainer or spContainer. * * @param SpgrContainer|SpgrContainer\SpContainer $child child to be added */ public function addChild(mixed $child): void { $this->children[] = $child; $child->setParent($this); } /** * Get collection of Shape Containers. * * @return mixed[] */ public function getChildren(): array { return $this->children; } /** * Recursively get all spContainers within this spgrContainer. * * @return SpgrContainer\SpContainer[] */ public function getAllSpContainers(): array { $allSpContainers = []; foreach ($this->children as $child) { if ($child instanceof self) { $allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers()); } else { $allSpContainers[] = $child; } } /** @var SpgrContainer\SpContainer[] $allSpContainers */ return $allSpContainers; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DgContainer.php ================================================ dgId; } public function setDgId(int $value): void { $this->dgId = $value; } public function getLastSpId(): ?int { return $this->lastSpId; } public function setLastSpId(int $value): void { $this->lastSpId = $value; } public function getSpgrContainer(): ?SpgrContainer { return $this->spgrContainer; } public function getSpgrContainerOrThrow(): SpgrContainer { if ($this->spgrContainer !== null) { return $this->spgrContainer; } throw new SpreadsheetException('spgrContainer is unexpectedly null'); } public function setSpgrContainer(SpgrContainer $spgrContainer): SpgrContainer { return $this->spgrContainer = $spgrContainer; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php ================================================ data; } /** * Set the raw image data. */ public function setData(string $data): void { $this->data = $data; } /** * Set parent BSE. */ public function setParent(BSE $parent): void { $this->parent = $parent; } /** * Get parent BSE. */ public function getParent(): BSE { return $this->parent; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php ================================================ parent = $parent; } public function getParent(): BstoreContainer { return $this->parent; } /** * Get the BLIP. */ public function getBlip(): ?BSE\Blip { return $this->blip; } /** * Set the BLIP. */ public function setBlip(BSE\Blip $blip): void { $this->blip = $blip; $blip->setParent($this); } /** * Get the BLIP type. */ public function getBlipType(): int { return $this->blipType; } /** * Set the BLIP type. */ public function setBlipType(int $blipType): void { $this->blipType = $blipType; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php ================================================ BSECollection[] = $BSE; $BSE->setParent($this); } /** * Get the collection of BLIP Store Entries. * * @return BstoreContainer\BSE[] */ public function getBSECollection(): array { return $this->BSECollection; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher/DggContainer.php ================================================ spIdMax; } /** * Set maximum shape index of all shapes in all drawings (plus one). */ public function setSpIdMax(int $value): void { $this->spIdMax = $value; } /** * Get total number of drawings saved. */ public function getCDgSaved(): int { return $this->cDgSaved; } /** * Set total number of drawings saved. */ public function setCDgSaved(int $value): void { $this->cDgSaved = $value; } /** * Get total number of shapes saved (including group shapes). */ public function getCSpSaved(): int { return $this->cSpSaved; } /** * Set total number of shapes saved (including group shapes). */ public function setCSpSaved(int $value): void { $this->cSpSaved = $value; } /** * Get BLIP Store Container. */ public function getBstoreContainer(): ?DggContainer\BstoreContainer { return $this->bstoreContainer; } /** * Get BLIP Store Container. */ public function getBstoreContainerOrThrow(): DggContainer\BstoreContainer { return $this->bstoreContainer ?? throw new SpreadsheetException('bstoreContainer is unexpectedly null'); } /** * Set BLIP Store Container. */ public function setBstoreContainer(DggContainer\BstoreContainer $bstoreContainer): void { $this->bstoreContainer = $bstoreContainer; } /** * Set an option for the drawing group. * * @param int $property The number specifies the option */ public function setOPT(int $property, mixed $value): void { $this->OPT[$property] = $value; } /** * Get an option for the drawing group. * * @param int $property The number specifies the option */ public function getOPT(int $property): mixed { if (isset($this->OPT[$property])) { return $this->OPT[$property]; } return null; } /** * Get identifier clusters. * * @return mixed[] */ public function getIDCLs(): array { return $this->IDCLs; } /** * Set identifier clusters. [ => , ...]. * * @param mixed[] $IDCLs */ public function setIDCLs(array $IDCLs): void { $this->IDCLs = $IDCLs; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Escher.php ================================================ dggContainer; } /** * Get Drawing Group Container. */ public function getDggContainerOrThrow(): Escher\DggContainer { return $this->dggContainer ?? throw new SpreadsheetException('dggContainer is unexpectedly null'); } /** * Set Drawing Group Container. */ public function setDggContainer(Escher\DggContainer $dggContainer): Escher\DggContainer { return $this->dggContainer = $dggContainer; } /** * Get Drawing Container. */ public function getDgContainer(): ?Escher\DgContainer { return $this->dgContainer; } /** * Get Drawing Container. */ public function getDgContainerOrThrow(): Escher\DgContainer { return $this->dgContainer ?? throw new SpreadsheetException('dgContainer is unexpectedly null'); } /** * Set Drawing Container. */ public function setDgContainer(Escher\DgContainer $dgContainer): Escher\DgContainer { return $this->dgContainer = $dgContainer; } } ================================================ FILE: src/PhpSpreadsheet/Shared/File.php ================================================ open($zipFile); if ($res === true) { $returnValue = ($zip->getFromName($archiveFile) !== false); $zip->close(); return $returnValue; } } return false; } return file_exists($filename); } /** * Returns canonicalized absolute pathname, also for ZIP archives. */ public static function realpath(string $filename): string { // Returnvalue $returnValue = ''; // Try using realpath() if (file_exists($filename)) { $returnValue = realpath($filename) ?: ''; } // Found something? if ($returnValue === '') { $pathArray = explode('/', $filename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { $iMax = count($pathArray); for ($i = 1; $i < $iMax; ++$i) { if ($pathArray[$i] == '..') { array_splice($pathArray, $i - 1, 2); break; } } } $returnValue = implode('/', $pathArray); } // Return return $returnValue; } /** * Get the systems temporary directory. */ public static function sysGetTempDir(): string { $path = sys_get_temp_dir(); if (self::$useUploadTempDirectory) { // use upload-directory when defined to allow running on environments having very restricted // open_basedir configs if (ini_get('upload_tmp_dir') !== false) { if ($temp = ini_get('upload_tmp_dir')) { if (file_exists($temp)) { $path = $temp; } } } } return realpath($path) ?: ''; } public static function temporaryFilename(): string { return tempnam(self::sysGetTempDir(), 'phpspreadsheet') ?: throw new Exception('Could not create temporary file'); } /** * Assert that given path is an existing file and is readable, otherwise throw exception. */ public static function assertFile(string $filename, string $zipMember = ''): void { if (!is_file($filename) || !is_readable($filename)) { throw new ReaderException('File "' . $filename . '" does not exist or is not readable.'); } if ($zipMember !== '') { $zipfile = "zip://$filename#$zipMember"; if (!self::fileExists($zipfile)) { // Has the file been saved with Windoze directory separators rather than unix? $zipfile = "zip://$filename#" . str_replace('/', '\\', $zipMember); if (!self::fileExists($zipfile)) { throw new ReaderException("Could not find zip member $zipfile"); } } } } /** * Same as assertFile, except return true/false and don't throw Exception. */ public static function testFileNoThrow(string $filename, ?string $zipMember = null): bool { if (!is_file($filename) || !is_readable($filename)) { return false; } if ($zipMember === null) { return true; } // validate zip, but don't check specific member if ($zipMember === '') { return self::validateZipFirst4($filename); } $zipfile = "zip://$filename#$zipMember"; if (self::fileExists($zipfile)) { return true; } // Has the file been saved with Windoze directory separators rather than unix? $zipfile = "zip://$filename#" . str_replace('/', '\\', $zipMember); return self::fileExists($zipfile); } } ================================================ FILE: src/PhpSpreadsheet/Shared/Font.php ================================================ [ 'x' => self::ARIAL, 'xb' => self::ARIAL_BOLD, 'xi' => self::ARIAL_ITALIC, 'xbi' => self::ARIAL_BOLD_ITALIC, ], 'Calibri' => [ 'x' => self::CALIBRI, 'xb' => self::CALIBRI_BOLD, 'xi' => self::CALIBRI_ITALIC, 'xbi' => self::CALIBRI_BOLD_ITALIC, ], 'Comic Sans MS' => [ 'x' => self::COMIC_SANS_MS, 'xb' => self::COMIC_SANS_MS_BOLD, 'xi' => self::COMIC_SANS_MS, 'xbi' => self::COMIC_SANS_MS_BOLD, ], 'Courier New' => [ 'x' => self::COURIER_NEW, 'xb' => self::COURIER_NEW_BOLD, 'xi' => self::COURIER_NEW_ITALIC, 'xbi' => self::COURIER_NEW_BOLD_ITALIC, ], 'Georgia' => [ 'x' => self::GEORGIA, 'xb' => self::GEORGIA_BOLD, 'xi' => self::GEORGIA_ITALIC, 'xbi' => self::GEORGIA_BOLD_ITALIC, ], 'Impact' => [ 'x' => self::IMPACT, 'xb' => self::IMPACT, 'xi' => self::IMPACT, 'xbi' => self::IMPACT, ], 'Liberation Sans' => [ 'x' => self::LIBERATION_SANS, 'xb' => self::LIBERATION_SANS_BOLD, 'xi' => self::LIBERATION_SANS_ITALIC, 'xbi' => self::LIBERATION_SANS_BOLD_ITALIC, ], 'Lucida Console' => [ 'x' => self::LUCIDA_CONSOLE, 'xb' => self::LUCIDA_CONSOLE, 'xi' => self::LUCIDA_CONSOLE, 'xbi' => self::LUCIDA_CONSOLE, ], 'Lucida Sans Unicode' => [ 'x' => self::LUCIDA_SANS_UNICODE, 'xb' => self::LUCIDA_SANS_UNICODE, 'xi' => self::LUCIDA_SANS_UNICODE, 'xbi' => self::LUCIDA_SANS_UNICODE, ], 'Microsoft Sans Serif' => [ 'x' => self::MICROSOFT_SANS_SERIF, 'xb' => self::MICROSOFT_SANS_SERIF, 'xi' => self::MICROSOFT_SANS_SERIF, 'xbi' => self::MICROSOFT_SANS_SERIF, ], 'Palatino Linotype' => [ 'x' => self::PALATINO_LINOTYPE, 'xb' => self::PALATINO_LINOTYPE_BOLD, 'xi' => self::PALATINO_LINOTYPE_ITALIC, 'xbi' => self::PALATINO_LINOTYPE_BOLD_ITALIC, ], 'Symbol' => [ 'x' => self::SYMBOL, 'xb' => self::SYMBOL, 'xi' => self::SYMBOL, 'xbi' => self::SYMBOL, ], 'Tahoma' => [ 'x' => self::TAHOMA, 'xb' => self::TAHOMA_BOLD, 'xi' => self::TAHOMA, 'xbi' => self::TAHOMA_BOLD, ], 'Times New Roman' => [ 'x' => self::TIMES_NEW_ROMAN, 'xb' => self::TIMES_NEW_ROMAN_BOLD, 'xi' => self::TIMES_NEW_ROMAN_ITALIC, 'xbi' => self::TIMES_NEW_ROMAN_BOLD_ITALIC, ], 'Trebuchet MS' => [ 'x' => self::TREBUCHET_MS, 'xb' => self::TREBUCHET_MS_BOLD, 'xi' => self::TREBUCHET_MS_ITALIC, 'xbi' => self::TREBUCHET_MS_BOLD_ITALIC, ], 'Verdana' => [ 'x' => self::VERDANA, 'xb' => self::VERDANA_BOLD, 'xi' => self::VERDANA_ITALIC, 'xbi' => self::VERDANA_BOLD_ITALIC, ], ]; /** * Array that can be used to supplement FONT_FILE_NAMES for calculating exact width. * * @var array> */ private static array $extraFontArray = []; /** @param array> $extraFontArray */ public static function setExtraFontArray(array $extraFontArray): void { self::$extraFontArray = $extraFontArray; } /** @return array> */ public static function getExtraFontArray(): array { return self::$extraFontArray; } /** * AutoSize method. */ private static string $autoSizeMethod = self::AUTOSIZE_METHOD_APPROX; /** * Path to folder containing TrueType font .ttf files. */ private static string $trueTypeFontPath = ''; /** * How wide is a default column for a given default font and size? * Empirical data found by inspecting real Excel files and reading off the pixel width * in Microsoft Office Excel 2007. * Added height in points. */ public const DEFAULT_COLUMN_WIDTHS = [ 'Arial' => [ 1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.0], 4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75], 5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25], 6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25], 7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0], 8 => ['px' => 56, 'width' => 9.33203125, 'height' => 11.25], 9 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.0], 10 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.75], ], 'Calibri' => [ 1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.00], 4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75], 5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25], 6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25], 7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0], 8 => ['px' => 56, 'width' => 9.33203125, 'height' => 11.25], 9 => ['px' => 56, 'width' => 9.33203125, 'height' => 12.0], 10 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.75], 11 => ['px' => 64, 'width' => 9.14062500, 'height' => 15.0], ], 'Verdana' => [ 1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.0], 4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75], 5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25], 6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25], 7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0], 8 => ['px' => 64, 'width' => 9.14062500, 'height' => 10.5], 9 => ['px' => 72, 'width' => 9.00000000, 'height' => 11.25], 10 => ['px' => 72, 'width' => 9.00000000, 'height' => 12.75], ], ]; /** * Set autoSize method. * * @param string $method see self::AUTOSIZE_METHOD_* * * @return bool Success or failure */ public static function setAutoSizeMethod(string $method): bool { if (!in_array($method, self::AUTOSIZE_METHODS)) { return false; } self::$autoSizeMethod = $method; return true; } /** * Get autoSize method. */ public static function getAutoSizeMethod(): string { return self::$autoSizeMethod; } /** * Set the path to the folder containing .ttf files. There should be a trailing slash. * Path will be recursively searched for font file. * Typical locations on various platforms: *
    *
  • C:/Windows/Fonts/
  • *
  • /usr/share/fonts/truetype/
  • *
  • ~/.fonts/
  • *
. */ public static function setTrueTypeFontPath(string $folderPath): void { self::$trueTypeFontPath = $folderPath; } /** * Get the path to the folder containing .ttf files. */ public static function getTrueTypeFontPath(): string { return self::$trueTypeFontPath; } /** * Pad amount for exact in pixels; use best guess if null. */ private static null|float|int $paddingAmountExact = null; /** * Set pad amount for exact in pixels; use best guess if null. */ public static function setPaddingAmountExact(null|float|int $paddingAmountExact): void { self::$paddingAmountExact = $paddingAmountExact; } /** * Get pad amount for exact in pixels; or null if using best guess. */ public static function getPaddingAmountExact(): null|float|int { return self::$paddingAmountExact; } /** * Calculate an (approximate) OpenXML column width, based on font size and text contained. * * @param FontStyle $font Font object * @param null|RichText|string $cellText Text to calculate width * @param int $rotation Rotation angle * @param null|FontStyle $defaultFont Font object * @param bool $filterAdjustment Add space for Autofilter or Table dropdown */ public static function calculateColumnWidth( FontStyle $font, $cellText = '', int $rotation = 0, ?FontStyle $defaultFont = null, bool $filterAdjustment = false, int $indentAdjustment = 0 ): float { // If it is rich text, use plain text if ($cellText instanceof RichText) { $cellText = $cellText->getPlainText(); } // Special case if there are one or more newline characters ("\n") $cellText = (string) $cellText; if (str_contains($cellText, "\n")) { $lineTexts = explode("\n", $cellText); $lineWidths = []; foreach ($lineTexts as $lineText) { $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont, $filterAdjustment); } return max($lineWidths); // width of longest line in cell } // Try to get the exact text width in pixels $approximate = self::$autoSizeMethod === self::AUTOSIZE_METHOD_APPROX; $columnWidth = 0; if (!$approximate) { try { $columnWidthAdjust = ceil( self::getTextWidthPixelsExact( str_repeat('n', 1 * (($filterAdjustment ? 3 : 1) + ($indentAdjustment * 2))), $font, 0 ) * 1.07 ); // Width of text in pixels excl. padding // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation) + (self::$paddingAmountExact ?? $columnWidthAdjust); } catch (PhpSpreadsheetException) { $approximate = true; } } if ($approximate) { $columnWidthAdjust = self::getTextWidthPixelsApprox( str_repeat('n', 1 * (($filterAdjustment ? 3 : 1) + ($indentAdjustment * 2))), $font, 0 ); // Width of text in pixels excl. padding, approximation // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation) + $columnWidthAdjust; } // Convert from pixel width to column width $columnWidth = Drawing::pixelsToCellDimension((int) $columnWidth, $defaultFont ?? new FontStyle()); // Return return round($columnWidth, 4); } /** * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle. */ public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): float { // font size should really be supplied in pixels in GD2, // but since GD2 seems to assume 72dpi, pixels and points are the same $fontFile = self::getTrueTypeFontFileFromFont($font); $textBox = imagettfbbox($font->getSize() ?? 10.0, $rotation, $fontFile, $text); if ($textBox === false) { // @codeCoverageIgnoreStart throw new PhpSpreadsheetException('imagettfbbox failed'); // @codeCoverageIgnoreEnd } // Get corners positions /** @var int[] $textBox */ $lowerLeftCornerX = $textBox[0]; $lowerRightCornerX = $textBox[2]; $upperRightCornerX = $textBox[4]; $upperLeftCornerX = $textBox[6]; // Consider the rotation when calculating the width return round(max($lowerRightCornerX - $upperLeftCornerX, $upperRightCornerX - $lowerLeftCornerX), 4); } /** * Get approximate width in pixels for a string of text in a certain font at a certain rotation angle. * * @return int Text width in pixels (no padding added) */ public static function getTextWidthPixelsApprox(string $columnText, FontStyle $font, int $rotation = 0): int { $fontName = $font->getName(); $fontSize = $font->getSize(); // Calculate column width in pixels. // We assume fixed glyph width, but count double for "fullwidth" characters. // Result varies with font name and size. switch ($fontName) { case 'Arial': // value 8 was set because of experience in different exports at Arial 10 font. $columnWidth = (int) (8 * StringHelper::countCharactersDbcs($columnText)); $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size break; case 'Verdana': // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font. $columnWidth = (int) (8 * StringHelper::countCharactersDbcs($columnText)); $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size break; default: // just assume Calibri // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font. $columnWidth = (int) (8.26 * StringHelper::countCharactersDbcs($columnText)); $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size break; } // Calculate approximate rotated column width if ($rotation !== 0) { if ($rotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { // stacked text $columnWidth = 4; // approximation } else { // rotated text $columnWidth = $columnWidth * cos(deg2rad($rotation)) + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation } } // pixel width is an integer return (int) $columnWidth; } /** * Calculate an (approximate) pixel size, based on a font points size. * * @param float|int $fontSizeInPoints Font size (in points) * * @return int Font size (in pixels) */ public static function fontSizeToPixels(float|int $fontSizeInPoints): int { return (int) ((4 / 3) * $fontSizeInPoints); } /** * Calculate an (approximate) pixel size, based on inch size. * * @param float|int $sizeInInch Font size (in inch) * * @return float|int Size (in pixels) */ public static function inchSizeToPixels(int|float $sizeInInch): int|float { return $sizeInInch * 96; } /** * Calculate an (approximate) pixel size, based on centimeter size. * * @param float|int $sizeInCm Font size (in centimeters) * * @return float Size (in pixels) */ public static function centimeterSizeToPixels(int|float $sizeInCm): float { return $sizeInCm * 37.795275591; } /** * Returns the font path given the font. * * @return string Path to TrueType font file */ public static function getTrueTypeFontFileFromFont(FontStyle $font, bool $checkPath = true): string { if ($checkPath && (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath))) { throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified'); } $name = $font->getName(); $fontArray = array_merge(self::FONT_FILE_NAMES, self::$extraFontArray); if (!isset($fontArray[$name])) { throw new PhpSpreadsheetException('Unknown font name "' . $name . '". Cannot map to TrueType font file'); } $bold = $font->getBold(); $italic = $font->getItalic(); $index = 'x'; if ($bold) { $index .= 'b'; } if ($italic) { $index .= 'i'; } $fontFile = $fontArray[$name][$index]; $separator = ''; if (mb_strlen(self::$trueTypeFontPath) > 1 && mb_substr(self::$trueTypeFontPath, -1) !== '/' && mb_substr(self::$trueTypeFontPath, -1) !== '\\') { $separator = DIRECTORY_SEPARATOR; } $fontFileAbsolute = preg_match('~^([A-Za-z]:)?[/\\\]~', $fontFile) === 1; if (!$fontFileAbsolute) { $fontFile = self::findFontFile(self::$trueTypeFontPath, $fontFile) ?? self::$trueTypeFontPath . $separator . $fontFile; } // Check if file actually exists if ($checkPath && !file_exists($fontFile) && !$fontFileAbsolute) { $alternateName = $name; if ($index !== 'x' && $fontArray[$name][$index] !== $fontArray[$name]['x']) { // Bold but no italic: // Comic Sans // Tahoma // Neither bold nor italic: // Impact // Lucida Console // Lucida Sans Unicode // Microsoft Sans Serif // Symbol if ($index === 'xb') { $alternateName .= ' Bold'; } elseif ($index === 'xi') { $alternateName .= ' Italic'; } elseif ($fontArray[$name]['xb'] === $fontArray[$name]['xbi']) { $alternateName .= ' Bold'; } else { $alternateName .= ' Bold Italic'; } } $fontFile = self::$trueTypeFontPath . $separator . $alternateName . '.ttf'; if (!file_exists($fontFile)) { throw new PhpSpreadsheetException('TrueType Font file not found'); } } return $fontFile; } public const CHARSET_FROM_FONT_NAME = [ 'EucrosiaUPC' => self::CHARSET_ANSI_THAI, 'Wingdings' => self::CHARSET_SYMBOL, 'Wingdings 2' => self::CHARSET_SYMBOL, 'Wingdings 3' => self::CHARSET_SYMBOL, ]; /** * Returns the associated charset for the font name. * * @param string $fontName Font name * * @return int Character set code */ public static function getCharsetFromFontName(string $fontName): int { return self::CHARSET_FROM_FONT_NAME[$fontName] ?? self::CHARSET_ANSI_LATIN; } /** * Get the effective column width for columns without a column dimension or column with width -1 * For example, for Calibri 11 this is 9.140625 (64 px). * * @param FontStyle $font The workbooks default font * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units * * @return ($returnAsPixels is true ? int : float) Column width */ public static function getDefaultColumnWidthByFont(FontStyle $font, bool $returnAsPixels = false): float|int { $size = $font->getSize(); $sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size"; if (isset(self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$sizex])) { // Exact width can be determined $columnWidth = $returnAsPixels ? self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$sizex]['px'] : self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$sizex]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 $columnWidth = $returnAsPixels ? self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] : self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width']; $columnWidth = $columnWidth * $font->getSize() / 11; // Round pixels to closest integer if ($returnAsPixels) { $columnWidth = (int) round($columnWidth); } } return $columnWidth; } /** * Get the effective row height for rows without a row dimension or rows with height -1 * For example, for Calibri 11 this is 15 points. * * @param FontStyle $font The workbooks default font * * @return float Row height in points */ public static function getDefaultRowHeightByFont(FontStyle $font): float { $name = $font->getName(); $size = $font->getSize(); $sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size"; if (isset(self::DEFAULT_COLUMN_WIDTHS[$name][$sizex])) { $rowHeight = self::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['height']; } elseif ($name === 'Arial' || $name === 'Verdana') { $rowHeight = self::DEFAULT_COLUMN_WIDTHS[$name][10]['height'] * $size / 10.0; } else { $rowHeight = self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['height'] * $size / 11.0; } return $rowHeight; } private static function findFontFile(string $startDirectory, string $desiredFont): ?string { $fontPath = null; if ($startDirectory === '') { return null; } if (file_exists("$startDirectory/$desiredFont")) { $fontPath = "$startDirectory/$desiredFont"; } else { $iterations = 0; $it = new RecursiveDirectoryIterator( $startDirectory, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS ); foreach ( new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ) as $filex ) { /** @var string */ $file = $filex; if (basename($file) === $desiredFont) { $fontPath = $file; break; } ++$iterations; if ($iterations > 5000) { // @codeCoverageIgnoreStart break; // @codeCoverageIgnoreEnd } } } return $fontPath; } } ================================================ FILE: src/PhpSpreadsheet/Shared/IntOrFloat.php ================================================ params); if (!isset($this->params['oleInstanceId'], $this->params['blockId'], $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) { //* @phpstan-ignore-line if ($options & STREAM_REPORT_ERRORS) { trigger_error('OLE stream not found', E_USER_WARNING); } return false; } $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']]; //* @phpstan-ignore-line if (!($this->ole instanceof OLE)) { //* @phpstan-ignore-line throw new Exception('class is not OLE'); } $blockId = $this->params['blockId']; $this->data = ''; if (isset($this->params['size']) && $this->params['size'] < $this->ole->bigBlockThreshold && $blockId != $this->ole->root->startBlock) { // Block id refers to small blocks $rootPos = $this->ole->getBlockOffset((int) $this->ole->root->startBlock); while ($blockId != -2) { /** @var int $blockId */ $pos = $rootPos + $blockId * $this->ole->bigBlockSize; $blockId = $this->ole->sbat[$blockId]; fseek($this->ole->_file_handle, $pos); $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); } } else { // Block id refers to big blocks while ($blockId != -2) { /** @var int $blockId */ $pos = $this->ole->getBlockOffset($blockId); fseek($this->ole->_file_handle, $pos); $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); $blockId = $this->ole->bbat[$blockId]; } } if (isset($this->params['size'])) { $this->data = substr($this->data, 0, $this->params['size']); //* @phpstan-ignore-line } if ($options & STREAM_USE_PATH) { $openedPath = $path; } return true; } /** * Implements support for fclose(). */ public function stream_close(): void // @codingStandardsIgnoreLine { $this->ole = null; unset($GLOBALS['_OLE_INSTANCES']); } /** * Implements support for fread(), fgets() etc. * * @param int $count maximum number of bytes to read * * @return false|string */ public function stream_read(int $count): bool|string // @codingStandardsIgnoreLine { if ($this->stream_eof()) { return false; } $s = substr($this->data, (int) $this->pos, $count); $this->pos += $count; return $s; } /** * Implements support for feof(). * * @return bool TRUE if the file pointer is at EOF; otherwise FALSE */ public function stream_eof(): bool // @codingStandardsIgnoreLine { return $this->pos >= strlen($this->data); } /** * Returns the position of the file pointer, i.e. its offset into the file * stream. Implements support for ftell(). */ public function stream_tell(): int // @codingStandardsIgnoreLine { return $this->pos; } /** * Implements support for fseek(). * * @param int $offset byte offset * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END */ public function stream_seek(int $offset, int $whence): bool // @codingStandardsIgnoreLine { if ($whence == SEEK_SET && $offset >= 0) { $this->pos = $offset; } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) { $this->pos += $offset; } elseif ($whence == SEEK_END && -$offset <= count($this->data)) { // @phpstan-ignore-line $this->pos = strlen($this->data) + $offset; } else { return false; } return true; } /** * Implements support for fstat(). Currently the only supported field is * "size". * * @return array{size: int} */ public function stream_stat(): array // @codingStandardsIgnoreLine { return [ 'size' => strlen($this->data), ]; } // Methods used by stream_wrapper_register() that are not implemented: // bool stream_flush ( void ) // int stream_write ( string data ) // bool rename ( string path_from, string path_to ) // bool mkdir ( string path, int mode, int options ) // bool rmdir ( string path, int options ) // bool dir_opendir ( string path, int options ) // array url_stat ( string path, int flags ) // string dir_readdir ( void ) // bool dir_rewinddir ( void ) // bool dir_closedir ( void ) } ================================================ FILE: src/PhpSpreadsheet/Shared/OLE/PPS/File.php ================================================ | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; /** * Class for creating File PPS's for OLE containers. * * @author Xavier Noguer */ class File extends PPS { /** * The constructor. * * @param string $name The name of the file (in Unicode) * * @see OLE::ascToUcs() */ public function __construct(string $name) { parent::__construct(null, $name, OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', []); } /** * Initialization method. Has to be called right after OLE_PPS_File(). */ public function init(): bool { return true; } /** * Append data to PPS. * * @param string $data The data to append */ public function append(string $data): void { $this->_data .= $data; } } ================================================ FILE: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php ================================================ | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; /** * Class for creating Root PPS's for OLE containers. * * @author Xavier Noguer */ class Root extends PPS { /** * @var resource */ private $fileHandle; private ?int $smallBlockSize = null; private ?int $bigBlockSize = null; /** * @param null|float|int $time_1st A timestamp * @param null|float|int $time_2nd A timestamp * @param File[] $raChild */ public function __construct($time_1st, $time_2nd, array $raChild) { parent::__construct(null, OLE::ascToUcs('Root Entry'), OLE::OLE_PPS_TYPE_ROOT, null, null, null, $time_1st, $time_2nd, null, $raChild); } /** * Method for saving the whole OLE container (including files). * In fact, if called with an empty argument (or '-'), it saves to a * temporary file and then outputs it's contents to stdout. * If a resource pointer to a stream created by fopen() is passed * it will be used, but you have to close such stream by yourself. * * @param resource $fileHandle the name of the file or stream where to save the OLE container * * @return bool true on success */ public function save($fileHandle): bool { $this->fileHandle = $fileHandle; // Initial Setting for saving $this->bigBlockSize = (int) (2 ** ( (isset($this->bigBlockSize)) ? self::adjust2($this->bigBlockSize) : 9 )); $this->smallBlockSize = (int) (2 ** ( (isset($this->smallBlockSize)) ? self::adjust2($this->smallBlockSize) : 6 )); // Make an array of PPS's (for Save) $aList = []; PPS::savePpsSetPnt($aList, [$this]); // calculate values for header [$iSBDcnt, $iBBcnt, $iPPScnt] = $this->calcSize($aList); //, $rhInfo); // Save Header $this->saveHeader((int) $iSBDcnt, (int) $iBBcnt, (int) $iPPScnt); // Make Small Data string (write SBD) $this->_data = $this->makeSmallData($aList); // Write BB $this->saveBigData((int) $iSBDcnt, $aList); // Write PPS $this->savePps($aList); // Write Big Block Depot and BDList and Adding Header informations $this->saveBbd((int) $iSBDcnt, (int) $iBBcnt, (int) $iPPScnt); return true; } /** * Calculate some numbers. * * @param PPS[] $raList Reference to an array of PPS's * * @return float[] The array of numbers */ private function calcSize(array &$raList): array { // Calculate Basic Setting [$iSBDcnt, $iBBcnt, $iPPScnt] = [0, 0, 0]; $iSBcnt = 0; $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { if ($raList[$i]->Type == OLE::OLE_PPS_TYPE_FILE) { $raList[$i]->Size = $raList[$i]->getDataLen(); if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) { $iSBcnt += floor($raList[$i]->Size / $this->smallBlockSize) + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); } else { $iBBcnt += (floor($raList[$i]->Size / $this->bigBlockSize) + (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); } } } $iSmallLen = $iSBcnt * $this->smallBlockSize; $iSlCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE); $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt) ? 1 : 0); $iBBcnt += (floor($iSmallLen / $this->bigBlockSize) + (($iSmallLen % $this->bigBlockSize) ? 1 : 0)); $iCnt = count($raList); $iBdCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE; $iPPScnt = (floor($iCnt / $iBdCnt) + (($iCnt % $iBdCnt) ? 1 : 0)); return [$iSBDcnt, $iBBcnt, $iPPScnt]; } /** * Helper function for calculating a magic value for block sizes. * * @param int $i2 The argument * * @see save() */ private static function adjust2(int $i2): float { $iWk = log($i2) / log(2); return ($iWk > floor($iWk)) ? floor($iWk) + 1 : $iWk; } /** * Save OLE header. */ private function saveHeader(int $iSBDcnt, int $iBBcnt, int $iPPScnt): void { $FILE = $this->fileHandle; // Calculate Basic Setting $iBlCnt = $this->bigBlockSize / OLE::OLE_LONG_INT_SIZE; $i1stBdL = ($this->bigBlockSize - 0x4C) / OLE::OLE_LONG_INT_SIZE; $iBdExL = 0; $iAll = $iBBcnt + $iPPScnt + $iSBDcnt; $iAllW = $iAll; $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt) ? 1 : 0); $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt) ? 1 : 0); // Calculate BD count if ($iBdCnt > $i1stBdL) { while (1) { ++$iBdExL; ++$iAllW; $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt) ? 1 : 0); $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt) ? 1 : 0); if ($iBdCnt <= ($iBdExL * $iBlCnt + $i1stBdL)) { break; } } } // Save Header fwrite( $FILE, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . pack('v', 0x3B) . pack('v', 0x03) . pack('v', -2) . pack('v', 9) . pack('v', 6) . pack('v', 0) . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . pack('V', $iBdCnt) . pack('V', $iBBcnt + $iSBDcnt) //ROOT START . pack('V', 0) . pack('V', 0x1000) . pack('V', $iSBDcnt ? 0 : -2) //Small Block Depot . pack('V', $iSBDcnt) ); // Extra BDList Start, Count if ($iBdCnt < $i1stBdL) { fwrite( $FILE, pack('V', -2) // Extra BDList Start . pack('V', 0)// Extra BDList Count ); } else { fwrite($FILE, pack('V', $iAll + $iBdCnt) . pack('V', $iBdExL)); } // BDList for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) { fwrite($FILE, pack('V', $iAll + $i)); } if ($i < $i1stBdL) { $jB = $i1stBdL - $i; for ($j = 0; $j < $jB; ++$j) { fwrite($FILE, (pack('V', -1))); } } } /** * Saving big data (PPS's with data bigger than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * * @param PPS[] $raList Reference to array of PPS's */ private function saveBigData(int $iStBlk, array &$raList): void { $FILE = $this->fileHandle; // cycle through PPS's $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { if ($raList[$i]->Type != OLE::OLE_PPS_TYPE_DIR) { $raList[$i]->Size = $raList[$i]->getDataLen(); if (($raList[$i]->Size >= OLE::OLE_DATA_SIZE_SMALL) || (($raList[$i]->Type == OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data))) { fwrite($FILE, $raList[$i]->_data); if ($raList[$i]->Size % $this->bigBlockSize) { fwrite($FILE, str_repeat("\x00", $this->bigBlockSize - ($raList[$i]->Size % $this->bigBlockSize))); } // Set For PPS $raList[$i]->startBlock = $iStBlk; $iStBlk += ((int) floor($raList[$i]->Size / $this->bigBlockSize) + (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); } } } } /** * get small data (PPS's with data smaller than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * * @param PPS[] $raList Reference to array of PPS's */ private function makeSmallData(array &$raList): string { $sRes = ''; $FILE = $this->fileHandle; $iSmBlk = 0; $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { // Make SBD, small data string if ($raList[$i]->Type == OLE::OLE_PPS_TYPE_FILE) { if ($raList[$i]->Size <= 0) { continue; } if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) { $iSmbCnt = (int) floor($raList[$i]->Size / $this->smallBlockSize) + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); // Add to SBD $jB = $iSmbCnt - 1; for ($j = 0; $j < $jB; ++$j) { fwrite($FILE, pack('V', $j + $iSmBlk + 1)); } fwrite($FILE, pack('V', -2)); // Add to Data String(this will be written for RootEntry) $sRes .= $raList[$i]->_data; if ($raList[$i]->Size % $this->smallBlockSize) { $sRes .= str_repeat("\x00", $this->smallBlockSize - ($raList[$i]->Size % $this->smallBlockSize)); } // Set for PPS $raList[$i]->startBlock = $iSmBlk; $iSmBlk += $iSmbCnt; } } } $iSbCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE); if ($iSmBlk % $iSbCnt) { $iB = $iSbCnt - ($iSmBlk % $iSbCnt); for ($i = 0; $i < $iB; ++$i) { fwrite($FILE, pack('V', -1)); } } return $sRes; } /** * Saves all the PPS's WKs. * * @param PPS[] $raList Reference to an array with all PPS's */ private function savePps(array &$raList): void { // Save each PPS WK $iC = count($raList); for ($i = 0; $i < $iC; ++$i) { fwrite($this->fileHandle, $raList[$i]->getPpsWk()); } // Adjust for Block $iCnt = count($raList); $iBCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE; if ($iCnt % $iBCnt) { fwrite($this->fileHandle, str_repeat("\x00", ($iBCnt - ($iCnt % $iBCnt)) * OLE::OLE_PPS_SIZE)); } } /** * Saving Big Block Depot. */ private function saveBbd(int $iSbdSize, int $iBsize, int $iPpsCnt): void { $FILE = $this->fileHandle; // Calculate Basic Setting $iBbCnt = $this->bigBlockSize / OLE::OLE_LONG_INT_SIZE; $i1stBdL = ($this->bigBlockSize - 0x4C) / OLE::OLE_LONG_INT_SIZE; $iBdExL = 0; $iAll = $iBsize + $iPpsCnt + $iSbdSize; $iAllW = $iAll; $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt) ? 1 : 0); $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt) ? 1 : 0); // Calculate BD count if ($iBdCnt > $i1stBdL) { while (1) { ++$iBdExL; ++$iAllW; $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt) ? 1 : 0); $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt) ? 1 : 0); if ($iBdCnt <= ($iBdExL * $iBbCnt + $i1stBdL)) { break; } } } // Making BD // Set for SBD if ($iSbdSize > 0) { for ($i = 0; $i < ($iSbdSize - 1); ++$i) { fwrite($FILE, pack('V', $i + 1)); } fwrite($FILE, pack('V', -2)); } // Set for B for ($i = 0; $i < ($iBsize - 1); ++$i) { fwrite($FILE, pack('V', $i + $iSbdSize + 1)); } fwrite($FILE, pack('V', -2)); // Set for PPS for ($i = 0; $i < ($iPpsCnt - 1); ++$i) { fwrite($FILE, pack('V', $i + $iSbdSize + $iBsize + 1)); } fwrite($FILE, pack('V', -2)); // Set for BBD itself ( 0xFFFFFFFD : BBD) for ($i = 0; $i < $iBdCnt; ++$i) { fwrite($FILE, pack('V', 0xFFFFFFFD)); } // Set for ExtraBDList for ($i = 0; $i < $iBdExL; ++$i) { fwrite($FILE, pack('V', 0xFFFFFFFC)); } // Adjust for Block if (($iAllW + $iBdCnt) % $iBbCnt) { $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt)); for ($i = 0; $i < $iBlock; ++$i) { fwrite($FILE, pack('V', -1)); } } // Extra BDList if ($iBdCnt > $i1stBdL) { $iN = 0; $iNb = 0; for ($i = $i1stBdL; $i < $iBdCnt; $i++, ++$iN) { if ($iN >= ($iBbCnt - 1)) { $iN = 0; ++$iNb; fwrite($FILE, pack('V', $iAll + $iBdCnt + $iNb)); } fwrite($FILE, pack('V', $iBsize + $iSbdSize + $iPpsCnt + $i)); } if (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)) { $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)); for ($i = 0; $i < $iB; ++$i) { fwrite($FILE, pack('V', -1)); } } fwrite($FILE, pack('V', -2)); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/OLE/PPS.php ================================================ | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Shared\OLE; /** * Class for creating PPS's for OLE containers. * * @author Xavier Noguer */ class PPS { private const ALL_ONE_BITS = (PHP_INT_SIZE > 4) ? 0xFFFFFFFF : -1; /** * The PPS index. */ public int $No; /** * The PPS name (in Unicode). */ public string $Name; /** * The PPS type. Dir, Root or File. */ public int $Type; /** * The index of the previous PPS. */ public int $PrevPps; /** * The index of the next PPS. */ public int $NextPps; /** * The index of it's first child if this is a Dir or Root PPS. */ public int $DirPps; /** * A timestamp. */ public float|int $Time1st; /** * A timestamp. */ public float|int $Time2nd; /** * Starting block (small or big) for this PPS's data inside the container. */ public ?int $startBlock = null; /** * The size of the PPS's data (in bytes). */ public int $Size; /** * The PPS's data (only used if it's not using a temporary file). */ public string $_data = ''; /** * Array of child PPS's (only used by Root and Dir PPS's). * * @var mixed[] */ public array $children = []; /** * Pointer to OLE container. */ public OLE $ole; /** * The constructor. * * @param ?int $No The PPS index * @param ?string $name The PPS name * @param ?int $type The PPS type. Dir, Root or File * @param ?int $prev The index of the previous PPS * @param ?int $next The index of the next PPS * @param ?int $dir The index of it's first child if this is a Dir or Root PPS * @param null|float|int $time_1st A timestamp * @param null|float|int $time_2nd A timestamp * @param ?string $data The (usually binary) source data of the PPS * @param mixed[] $children Array containing children PPS for this PPS */ public function __construct(?int $No, ?string $name, ?int $type, ?int $prev, ?int $next, ?int $dir, $time_1st, $time_2nd, ?string $data, array $children) { $this->No = (int) $No; $this->Name = (string) $name; $this->Type = (int) $type; $this->PrevPps = (int) $prev; $this->NextPps = (int) $next; $this->DirPps = (int) $dir; $this->Time1st = $time_1st ?? 0; $this->Time2nd = $time_2nd ?? 0; $this->_data = (string) $data; $this->children = $children; $this->Size = strlen((string) $data); } /** * Returns the amount of data saved for this PPS. * * @return int The amount of data (in bytes) */ public function getDataLen(): int { //if (!isset($this->_data)) { // return 0; //} return strlen($this->_data); } /** * Returns a string with the PPS's WK (What is a WK?). * * @return string The binary string */ public function getPpsWk(): string { $ret = str_pad($this->Name, 64, "\x00"); $ret .= pack('v', strlen($this->Name) + 2) // 66 . pack('c', $this->Type) // 67 . pack('c', 0x00) //UK // 68 . pack('V', $this->PrevPps) //Prev // 72 . pack('V', $this->NextPps) //Next // 76 . pack('V', $this->DirPps) //Dir // 80 . "\x00\x09\x02\x00" // 84 . "\x00\x00\x00\x00" // 88 . "\xc0\x00\x00\x00" // 92 . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root . "\x00\x00\x00\x00" // 100 . OLE::localDateToOLE($this->Time1st) // 108 . OLE::localDateToOLE($this->Time2nd) // 116 . pack('V', $this->startBlock ?? 0) // 120 . pack('V', $this->Size) // 124 . pack('V', 0); // 128 return $ret; } /** * Updates index and pointers to previous, next and children PPS's for this * PPS. I don't think it'll work with Dir PPS's. * * @param self[] $raList Reference to the array of PPS's for the whole OLE * container * * @return int The index for this PPS */ public static function savePpsSetPnt(array &$raList, mixed $to_save, int $depth = 0): int { if (!is_array($to_save) || (empty($to_save))) { return self::ALL_ONE_BITS; } /** @var self[] $to_save */ if (count($to_save) == 1) { $cnt = count($raList); // If the first entry, it's the root... Don't clone it! $raList[$cnt] = ($depth == 0) ? $to_save[0] : clone $to_save[0]; $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = self::ALL_ONE_BITS; $raList[$cnt]->NextPps = self::ALL_ONE_BITS; $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } else { $iPos = (int) floor(count($to_save) / 2); $aPrev = array_slice($to_save, 0, $iPos); $aNext = array_slice($to_save, $iPos + 1); $cnt = count($raList); // If the first entry, it's the root... Don't clone it! $raList[$cnt] = ($depth == 0) ? $to_save[$iPos] : clone $to_save[$iPos]; $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = self::savePpsSetPnt($raList, $aPrev, $depth++); $raList[$cnt]->NextPps = self::savePpsSetPnt($raList, $aNext, $depth++); $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } return $cnt; } } ================================================ FILE: src/PhpSpreadsheet/Shared/OLE.php ================================================ | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root; /* * Array for storing OLE instances that are accessed from * OLE_ChainedBlockStream::stream_open(). * * @var array */ $GLOBALS['_OLE_INSTANCES'] = []; /** * OLE package base class. * * @author Xavier Noguer * @author Christian Schmidt */ class OLE { const OLE_PPS_TYPE_ROOT = 5; const OLE_PPS_TYPE_DIR = 1; const OLE_PPS_TYPE_FILE = 2; const OLE_DATA_SIZE_SMALL = 0x1000; const OLE_LONG_INT_SIZE = 4; const OLE_PPS_SIZE = 0x80; /** * The file handle for reading an OLE container. * * @var resource */ public $_file_handle; /** * Array of PPS's found on the OLE container. * * @var array */ public array $_list = []; /** * Root directory of OLE container. */ public Root $root; /** * Big Block Allocation Table. * * @var mixed[] (blockId => nextBlockId) */ public array $bbat; /** * Short Block Allocation Table. * * @var mixed[] (blockId => nextBlockId) */ public array $sbat; /** * Size of big blocks. This is usually 512. * * @var int<1, max> number of octets per block */ public int $bigBlockSize; /** * Size of small blocks. This is usually 64. * * @var int number of octets per block */ public int $smallBlockSize; /** * Threshold for big blocks. */ public int $bigBlockThreshold; /** * Reads an OLE container from the contents of the file given. * * @acces public * * @return bool true on success, PEAR_Error on failure */ public function read(string $filename): bool { $fh = @fopen($filename, 'rb'); if ($fh === false) { throw new ReaderException("Can't open file $filename"); } $this->_file_handle = $fh; $signature = fread($fh, 8); if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) { throw new ReaderException("File doesn't seem to be an OLE container."); } fseek($fh, 28); if (fread($fh, 2) != "\xFE\xFF") { // This shouldn't be a problem in practice throw new ReaderException('Only Little-Endian encoding is supported.'); } // Size of blocks and short blocks in bytes /** @var int<1, max> */ $temp = 2 ** self::readInt2($fh); $this->bigBlockSize = $temp; $this->smallBlockSize = 2 ** self::readInt2($fh); // Skip UID, revision number and version number fseek($fh, 44); // Number of blocks in Big Block Allocation Table $bbatBlockCount = self::readInt4($fh); // Root chain 1st block $directoryFirstBlockId = self::readInt4($fh); // Skip unused bytes fseek($fh, 56); // Streams shorter than this are stored using small blocks $this->bigBlockThreshold = self::readInt4($fh); // Block id of first sector in Short Block Allocation Table $sbatFirstBlockId = self::readInt4($fh); // Number of blocks in Short Block Allocation Table $sbbatBlockCount = self::readInt4($fh); // Block id of first sector in Master Block Allocation Table $mbatFirstBlockId = self::readInt4($fh); // Number of blocks in Master Block Allocation Table $mbbatBlockCount = self::readInt4($fh); $this->bbat = []; // Remaining 4 * 109 bytes of current block is beginning of Master // Block Allocation Table $mbatBlocks = []; for ($i = 0; $i < 109; ++$i) { $mbatBlocks[] = self::readInt4($fh); } // Read rest of Master Block Allocation Table (if any is left) $pos = $this->getBlockOffset($mbatFirstBlockId); for ($i = 0; $i < $mbbatBlockCount; ++$i) { fseek($fh, $pos); for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) { $mbatBlocks[] = self::readInt4($fh); } // Last block id in each block points to next block $pos = $this->getBlockOffset(self::readInt4($fh)); } // Read Big Block Allocation Table according to chain specified by $mbatBlocks for ($i = 0; $i < $bbatBlockCount; ++$i) { $pos = $this->getBlockOffset($mbatBlocks[$i]); fseek($fh, $pos); for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) { $this->bbat[] = self::readInt4($fh); } } // Read short block allocation table (SBAT) $this->sbat = []; $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; $sbatFh = $this->getStream($sbatFirstBlockId); for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) { $this->sbat[$blockId] = self::readInt4($sbatFh); } fclose($sbatFh); $this->readPpsWks($directoryFirstBlockId); return true; } /** * @param int $blockId byte offset from beginning of file */ public function getBlockOffset(int $blockId): int { return 512 + $blockId * $this->bigBlockSize; } /** * Returns a stream for use with fread() etc. External callers should * use \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File::getStream(). * * @param int|OLE\PPS $blockIdOrPps block id or PPS * * @return resource read-only stream */ public function getStream($blockIdOrPps) { static $isRegistered = false; if (!$isRegistered) { stream_wrapper_register('ole-chainedblockstream', ChainedBlockStream::class); $isRegistered = true; } // Store current instance in global array, so that it can be accessed // in OLE_ChainedBlockStream::stream_open(). // Object is removed from self::$instances in OLE_Stream::close(). $GLOBALS['_OLE_INSTANCES'][] = $this; //* @phpstan-ignore-line $keys = array_keys($GLOBALS['_OLE_INSTANCES']); //* @phpstan-ignore-line $instanceId = end($keys); $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId; if ($blockIdOrPps instanceof OLE\PPS) { $path .= '&blockId=' . $blockIdOrPps->startBlock; $path .= '&size=' . $blockIdOrPps->Size; } else { $path .= '&blockId=' . $blockIdOrPps; } $resource = fopen($path, 'rb') ?: throw new Exception("Unable to open stream $path"); return $resource; } /** * Reads a signed char. * * @param resource $fileHandle file handle */ private static function readInt1($fileHandle): int { [, $tmp] = unpack('c', fread($fileHandle, 1) ?: '') ?: [0, 0]; /** @var int $tmp */ return $tmp; } /** * Reads an unsigned short (2 octets). * * @param resource $fileHandle file handle */ private static function readInt2($fileHandle): int { [, $tmp] = unpack('v', fread($fileHandle, 2) ?: '') ?: [0, 0]; /** @var int $tmp */ return $tmp; } private const SIGNED_4OCTET_LIMIT = 2147483648; private const SIGNED_4OCTET_SUBTRACT = 2 * self::SIGNED_4OCTET_LIMIT; /** * Reads long (4 octets), interpreted as if signed on 32-bit system. * * @param resource $fileHandle file handle */ private static function readInt4($fileHandle): int { [, $tmp] = unpack('V', fread($fileHandle, 4) ?: '') ?: [0, 0]; /** @var int $tmp */ if ($tmp >= self::SIGNED_4OCTET_LIMIT) { $tmp -= self::SIGNED_4OCTET_SUBTRACT; } return $tmp; } /** * Gets information about all PPS's on the OLE container from the PPS WK's * creates an OLE_PPS object for each one. * * @param int $blockId the block id of the first block * * @return bool true on success, PEAR_Error on failure */ public function readPpsWks(int $blockId): bool { $fh = $this->getStream($blockId); for ($pos = 0; true; $pos += 128) { fseek($fh, $pos, SEEK_SET); $nameUtf16 = (string) fread($fh, 64); $nameLength = self::readInt2($fh); $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2); // Simple conversion from UTF-16LE to ISO-8859-1 $name = str_replace("\x00", '', $nameUtf16); $type = self::readInt1($fh); switch ($type) { case self::OLE_PPS_TYPE_ROOT: $pps = new Root(null, null, []); $this->root = $pps; break; case self::OLE_PPS_TYPE_DIR: $pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, []); break; case self::OLE_PPS_TYPE_FILE: $pps = new OLE\PPS\File($name); break; default: throw new Exception('Unsupported PPS type'); } fseek($fh, 1, SEEK_CUR); $pps->Type = $type; $pps->Name = $name; $pps->PrevPps = self::readInt4($fh); $pps->NextPps = self::readInt4($fh); $pps->DirPps = self::readInt4($fh); fseek($fh, 20, SEEK_CUR); $pps->Time1st = self::OLE2LocalDate((string) fread($fh, 8)); $pps->Time2nd = self::OLE2LocalDate((string) fread($fh, 8)); $pps->startBlock = self::readInt4($fh); $pps->Size = self::readInt4($fh); $pps->No = count($this->_list); $this->_list[] = $pps; // check if the PPS tree (starting from root) is complete if (isset($this->root) && $this->ppsTreeComplete($this->root->No)) { break; } } fclose($fh); // Initialize $pps->children on directories foreach ($this->_list as $pps) { if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) { $nos = [$pps->DirPps]; $pps->children = []; while (!empty($nos)) { $no = array_pop($nos); if ($no != -1) { $childPps = $this->_list[$no]; $nos[] = $childPps->PrevPps; $nos[] = $childPps->NextPps; $pps->children[] = $childPps; } } } } return true; } /** * It checks whether the PPS tree is complete (all PPS's read) * starting with the given PPS (not necessarily root). * * @param int $index The index of the PPS from which we are checking * * @return bool Whether the PPS tree for the given PPS is complete */ private function ppsTreeComplete(int $index): bool { if (!isset($this->_list[$index])) { return false; } $pps = $this->_list[$index]; return ($pps->PrevPps == -1 || $this->ppsTreeComplete($pps->PrevPps)) && ($pps->NextPps == -1 || $this->ppsTreeComplete($pps->NextPps)) && ($pps->DirPps == -1 || $this->ppsTreeComplete($pps->DirPps)); } /** * Checks whether a PPS is a File PPS or not. * If there is no PPS for the index given, it will return false. * * @param int $index The index for the PPS * * @return bool true if it's a File PPS, false otherwise */ public function isFile(int $index): bool { if (isset($this->_list[$index])) { return $this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE; } return false; } /** * Checks whether a PPS is a Root PPS or not. * If there is no PPS for the index given, it will return false. * * @param int $index the index for the PPS * * @return bool true if it's a Root PPS, false otherwise */ public function isRoot(int $index): bool { if (isset($this->_list[$index])) { return $this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT; } return false; } /** * Gives the total number of PPS's found in the OLE container. * * @return int The total number of PPS's found in the OLE container */ public function ppsTotal(): int { return count($this->_list); } /** * Gets data from a PPS * If there is no PPS for the index given, it will return an empty string. * * @param int $index The index for the PPS * @param int $position The position from which to start reading * (relative to the PPS) * @param int $length The amount of bytes to read (at most) * * @return string The binary string containing the data requested * * @see OLE_PPS_File::getStream() */ public function getData(int $index, int $position, int $length): string { // if position is not valid return empty string if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) { return ''; } $fh = $this->getStream($this->_list[$index]); $data = (string) stream_get_contents($fh, $length, $position); fclose($fh); return $data; } /** * Gets the data length from a PPS * If there is no PPS for the index given, it will return 0. * * @param int $index The index for the PPS * * @return int The amount of bytes in data the PPS has */ public function getDataLength(int $index): int { if (isset($this->_list[$index])) { return $this->_list[$index]->Size; } return 0; } /** * Utility function to transform ASCII text to Unicode. * * @param string $ascii The ASCII string to transform * * @return string The string in Unicode */ public static function ascToUcs(string $ascii): string { $rawname = ''; $iMax = strlen($ascii); for ($i = 0; $i < $iMax; ++$i) { $rawname .= $ascii[$i] . "\x00"; } return $rawname; } /** * Utility function * Returns a string for the OLE container with the date given. * * @param float|int $date A timestamp * * @return string The string for the OLE container */ public static function localDateToOLE($date): string { if (!$date) { return "\x00\x00\x00\x00\x00\x00\x00\x00"; } $dateTime = Date::dateTimeFromTimestamp("$date"); // days from 1-1-1601 until the beginning of UNIX era $days = 134774; // calculate seconds $big_date = $days * 24 * 3600 + (float) $dateTime->format('U'); // multiply just to make MS happy $big_date *= 10000000; // Make HEX string $res = ''; $factor = 2 ** 56; while ($factor >= 1) { $hex = (int) floor($big_date / $factor); $res = pack('c', $hex) . $res; $big_date = fmod($big_date, $factor); $factor /= 256; } return $res; } /** * Returns a timestamp from an OLE container's date. * * @param string $oleTimestamp A binary string with the encoded date * * @return float|int The Unix timestamp corresponding to the string */ public static function OLE2LocalDate(string $oleTimestamp) { if (strlen($oleTimestamp) != 8) { throw new ReaderException('Expecting 8 byte string'); } // convert to units of 100 ns since 1601: /** @var int[] */ $unpackedTimestamp = unpack('v4', $oleTimestamp) ?: []; $timestampHigh = (float) $unpackedTimestamp[4] * 65536 + (float) $unpackedTimestamp[3]; $timestampLow = (float) $unpackedTimestamp[2] * 65536 + (float) $unpackedTimestamp[1]; // translate to seconds since 1601: $timestampHigh /= 10000000; $timestampLow /= 10000000; // days from 1601 to 1970: $days = 134774; // translate to seconds since 1970: $unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5); return IntOrFloat::evaluate($unixTimestamp); } } ================================================ FILE: src/PhpSpreadsheet/Shared/OLERead.php ================================================ data = (string) file_get_contents($filename, false, null, 0, 8); // Check OLE identifier $identifierOle = pack('CCCCCCCC', 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1); if ($this->data != $identifierOle) { throw new ReaderException('The filename ' . $filename . ' is not recognised as an OLE file'); } // Get the file data $this->data = (string) file_get_contents($filename); // Total number of sectors used for the SAT $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); // SecID of the first sector of the directory stream $this->rootStartBlock = self::getInt4d($this->data, self::ROOT_START_BLOCK_POS); // SecID of the first sector of the SSAT (or -2 if not extant) $this->sbdStartBlock = self::getInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS); // SecID of the first sector of the MSAT (or -2 if no additional sectors are used) $this->extensionBlock = self::getInt4d($this->data, self::EXTENSION_BLOCK_POS); // Total number of sectors used by MSAT $this->numExtensionBlocks = self::getInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS); $bigBlockDepotBlocks = []; $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS; $bbdBlocks = $this->numBigBlockDepotBlocks; if ($this->numExtensionBlocks !== 0) { $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS) / 4; } for ($i = 0; $i < $bbdBlocks; ++$i) { $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); $pos += 4; } for ($j = 0; $j < $this->numExtensionBlocks; ++$j) { $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE; $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1); for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) { $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); $pos += 4; } $bbdBlocks += $blocksToRead; if ($bbdBlocks < $this->numBigBlockDepotBlocks) { $this->extensionBlock = self::getInt4d($this->data, $pos); } } $pos = 0; $this->bigBlockChain = ''; $bbs = self::BIG_BLOCK_SIZE / 4; for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) { $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE; $this->bigBlockChain .= substr($this->data, $pos, 4 * $bbs); $pos += 4 * $bbs; } $sbdBlock = $this->sbdStartBlock; $this->smallBlockChain = ''; while ($sbdBlock != -2) { $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE; $this->smallBlockChain .= substr($this->data, $pos, 4 * $bbs); $pos += 4 * $bbs; $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock * 4); } // read the directory stream $block = $this->rootStartBlock; $this->entry = $this->readData($block); $this->readPropertySets(); } /** * Extract binary stream data. */ public function getStream(?int $stream): ?string { if ($stream === null) { return null; } $streamData = ''; if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) { /** @var int */ $temp = $this->props[$this->rootentry]['startBlock']; $rootdata = $this->readData($temp); /** @var int */ $block = $this->props[$stream]['startBlock']; while ($block != -2) { $pos = $block * self::SMALL_BLOCK_SIZE; $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE); $block = self::getInt4d($this->smallBlockChain, $block * 4); } return $streamData; } /** @var int */ $temp = $this->props[$stream]['size']; $numBlocks = $temp / self::BIG_BLOCK_SIZE; if ($temp % self::BIG_BLOCK_SIZE != 0) { ++$numBlocks; } if ($numBlocks == 0) { return ''; } /** @var int */ $block = $this->props[$stream]['startBlock']; while ($block != -2) { $pos = ($block + 1) * self::BIG_BLOCK_SIZE; $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); $block = self::getInt4d($this->bigBlockChain, $block * 4); } return $streamData; } /** * Read a standard stream (by joining sectors using information from SAT). * * @param int $block Sector ID where the stream starts * * @return string Data for standard stream */ private function readData(int $block): string { $data = ''; while ($block != -2) { $pos = ($block + 1) * self::BIG_BLOCK_SIZE; $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); $block = self::getInt4d($this->bigBlockChain, $block * 4); } return $data; } /** * Read entries in the directory stream. */ private function readPropertySets(): void { $offset = 0; // loop through entries, each entry is 128 bytes $entryLen = strlen($this->entry); while ($offset < $entryLen) { // entry data (128 bytes) $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE); // size in bytes of name $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS + 1]) << 8); // type of entry $type = ord($d[self::TYPE_POS]); // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook) // sectorID of first sector of the short-stream container stream, if this entry is root entry $startBlock = self::getInt4d($d, self::START_BLOCK_POS); $size = self::getInt4d($d, self::SIZE_POS); $name = str_replace("\x00", '', substr($d, 0, $nameSize)); $this->props[] = [ 'name' => $name, 'type' => $type, 'startBlock' => $startBlock, 'size' => $size, ]; // tmp helper to simplify checks $upName = strtoupper($name); // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook) if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) { $this->wrkbook = count($this->props) - 1; } elseif ($upName === 'ROOT ENTRY' || $upName === 'R') { // Root entry $this->rootentry = count($this->props) - 1; } // Summary information if ($name == chr(5) . 'SummaryInformation') { $this->summaryInformation = count($this->props) - 1; } // Additional Document Summary information if ($name == chr(5) . 'DocumentSummaryInformation') { $this->documentSummaryInformation = count($this->props) - 1; } $offset += self::PROPERTY_STORAGE_BLOCK_SIZE; } } /** * Read 4 bytes of data at specified position. */ private static function getInt4d(string $data, int $pos): int { if ($pos < 0) { // Invalid position throw new ReaderException('Parameter pos=' . $pos . ' is invalid.'); } $len = strlen($data); if ($len < $pos + 4) { $data .= str_repeat("\0", $pos + 4 - $len); } // FIX: represent numbers correctly on 64-bit system // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 // Changed by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems $_or_24 = ord($data[$pos + 3]); if ($_or_24 >= 128) { // negative number $_ord_24 = -abs((256 - $_or_24) << 24); } else { $_ord_24 = ($_or_24 & 127) << 24; } return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; } } ================================================ FILE: src/PhpSpreadsheet/Shared/PasswordHasher.php ================================================ 'md2', Protection::ALGORITHM_MD4 => 'md4', Protection::ALGORITHM_MD5 => 'md5', Protection::ALGORITHM_SHA_1 => 'sha1', Protection::ALGORITHM_SHA_256 => 'sha256', Protection::ALGORITHM_SHA_384 => 'sha384', Protection::ALGORITHM_SHA_512 => 'sha512', Protection::ALGORITHM_RIPEMD_128 => 'ripemd128', Protection::ALGORITHM_RIPEMD_160 => 'ripemd160', Protection::ALGORITHM_WHIRLPOOL => 'whirlpool', ]; if (array_key_exists($algorithmName, $mapping)) { return $mapping[$algorithmName]; } throw new SpException('Unsupported password algorithm: ' . $algorithmName); } /** * Create a password hash from a given string. * * This method is based on the spec at: * https://interoperability.blob.core.windows.net/files/MS-OFFCRYPTO/[MS-OFFCRYPTO].pdf * 2.3.7.1 Binary Document Password Verifier Derivation Method 1 * * It replaces a method based on the algorithm provided by * Daniel Rentz of OpenOffice and the PEAR package * Spreadsheet_Excel_Writer by Xavier Noguer . * * @param string $password Password to hash */ private static function defaultHashPassword(string $password): string { $verifier = 0; $pwlen = strlen($password); $passwordArray = pack('c', $pwlen) . $password; for ($i = $pwlen; $i >= 0; --$i) { $intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1; $intermediate2 = 2 * $verifier; $intermediate2 = $intermediate2 & 0x7FFF; $intermediate3 = $intermediate1 | $intermediate2; $verifier = $intermediate3 ^ ord($passwordArray[$i]); } $verifier ^= 0xCE4B; return strtoupper(dechex($verifier)); } /** * Create a password hash from a given string by a specific algorithm. * * 2.4.2.4 ISO Write Protection Method * * @see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/1357ea58-646e-4483-92ef-95d718079d6f * * @param string $password Password to hash * @param string $algorithm Hash algorithm used to compute the password hash value * @param string $salt Pseudorandom base64-encoded string * @param int $spinCount Number of times to iterate on a hash of a password * * @return string Hashed password */ public static function hashPassword(string $password, string $algorithm = '', string $salt = '', int $spinCount = 10000): string { if (strlen($password) > self::MAX_PASSWORD_LENGTH) { throw new SpException('Password exceeds ' . self::MAX_PASSWORD_LENGTH . ' characters'); } $phpAlgorithm = self::getAlgorithm($algorithm); if (!$phpAlgorithm) { return self::defaultHashPassword($password); } $saltValue = base64_decode($salt); $encodedPassword = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8'); $hashValue = hash($phpAlgorithm, $saltValue . $encodedPassword, true); for ($i = 0; $i < $spinCount; ++$i) { $hashValue = hash($phpAlgorithm, $hashValue . pack('L', $i), true); } return base64_encode($hashValue); } } ================================================ FILE: src/PhpSpreadsheet/Shared/StringHelper.php ================================================ "\x00", "\x1B 1" => "\x01", "\x1B 2" => "\x02", "\x1B 3" => "\x03", "\x1B 4" => "\x04", "\x1B 5" => "\x05", "\x1B 6" => "\x06", "\x1B 7" => "\x07", "\x1B 8" => "\x08", "\x1B 9" => "\x09", "\x1B :" => "\x0a", "\x1B ;" => "\x0b", "\x1B <" => "\x0c", "\x1B =" => "\x0d", "\x1B >" => "\x0e", "\x1B ?" => "\x0f", "\x1B!0" => "\x10", "\x1B!1" => "\x11", "\x1B!2" => "\x12", "\x1B!3" => "\x13", "\x1B!4" => "\x14", "\x1B!5" => "\x15", "\x1B!6" => "\x16", "\x1B!7" => "\x17", "\x1B!8" => "\x18", "\x1B!9" => "\x19", "\x1B!:" => "\x1a", "\x1B!;" => "\x1b", "\x1B!<" => "\x1c", "\x1B!=" => "\x1d", "\x1B!>" => "\x1e", "\x1B!?" => "\x1f", "\x1B'?" => "\x7f", "\x1B(0" => '€', // 128 in CP1252 "\x1B(2" => '‚', // 130 in CP1252 "\x1B(3" => 'ƒ', // 131 in CP1252 "\x1B(4" => '„', // 132 in CP1252 "\x1B(5" => '…', // 133 in CP1252 "\x1B(6" => '†', // 134 in CP1252 "\x1B(7" => '‡', // 135 in CP1252 "\x1B(8" => 'ˆ', // 136 in CP1252 "\x1B(9" => '‰', // 137 in CP1252 "\x1B(:" => 'Š', // 138 in CP1252 "\x1B(;" => '‹', // 139 in CP1252 "\x1BNj" => 'Œ', // 140 in CP1252 "\x1B(>" => 'Ž', // 142 in CP1252 "\x1B)1" => '‘', // 145 in CP1252 "\x1B)2" => '’', // 146 in CP1252 "\x1B)3" => '“', // 147 in CP1252 "\x1B)4" => '”', // 148 in CP1252 "\x1B)5" => '•', // 149 in CP1252 "\x1B)6" => '–', // 150 in CP1252 "\x1B)7" => '—', // 151 in CP1252 "\x1B)8" => '˜', // 152 in CP1252 "\x1B)9" => '™', // 153 in CP1252 "\x1B):" => 'š', // 154 in CP1252 "\x1B);" => '›', // 155 in CP1252 "\x1BNz" => 'œ', // 156 in CP1252 "\x1B)>" => 'ž', // 158 in CP1252 "\x1B)?" => 'Ÿ', // 159 in CP1252 "\x1B*0" => ' ', // 160 in CP1252 "\x1BN!" => '¡', // 161 in CP1252 "\x1BN\"" => '¢', // 162 in CP1252 "\x1BN#" => '£', // 163 in CP1252 "\x1BN(" => '¤', // 164 in CP1252 "\x1BN%" => '¥', // 165 in CP1252 "\x1B*6" => '¦', // 166 in CP1252 "\x1BN'" => '§', // 167 in CP1252 "\x1BNH " => '¨', // 168 in CP1252 "\x1BNS" => '©', // 169 in CP1252 "\x1BNc" => 'ª', // 170 in CP1252 "\x1BN+" => '«', // 171 in CP1252 "\x1B*<" => '¬', // 172 in CP1252 "\x1B*=" => '­', // 173 in CP1252 "\x1BNR" => '®', // 174 in CP1252 "\x1B*?" => '¯', // 175 in CP1252 "\x1BN0" => '°', // 176 in CP1252 "\x1BN1" => '±', // 177 in CP1252 "\x1BN2" => '²', // 178 in CP1252 "\x1BN3" => '³', // 179 in CP1252 "\x1BNB " => '´', // 180 in CP1252 "\x1BN5" => 'µ', // 181 in CP1252 "\x1BN6" => '¶', // 182 in CP1252 "\x1BN7" => '·', // 183 in CP1252 "\x1B+8" => '¸', // 184 in CP1252 "\x1BNQ" => '¹', // 185 in CP1252 "\x1BNk" => 'º', // 186 in CP1252 "\x1BN;" => '»', // 187 in CP1252 "\x1BN<" => '¼', // 188 in CP1252 "\x1BN=" => '½', // 189 in CP1252 "\x1BN>" => '¾', // 190 in CP1252 "\x1BN?" => '¿', // 191 in CP1252 "\x1BNAA" => 'À', // 192 in CP1252 "\x1BNBA" => 'Á', // 193 in CP1252 "\x1BNCA" => 'Â', // 194 in CP1252 "\x1BNDA" => 'Ã', // 195 in CP1252 "\x1BNHA" => 'Ä', // 196 in CP1252 "\x1BNJA" => 'Å', // 197 in CP1252 "\x1BNa" => 'Æ', // 198 in CP1252 "\x1BNKC" => 'Ç', // 199 in CP1252 "\x1BNAE" => 'È', // 200 in CP1252 "\x1BNBE" => 'É', // 201 in CP1252 "\x1BNCE" => 'Ê', // 202 in CP1252 "\x1BNHE" => 'Ë', // 203 in CP1252 "\x1BNAI" => 'Ì', // 204 in CP1252 "\x1BNBI" => 'Í', // 205 in CP1252 "\x1BNCI" => 'Î', // 206 in CP1252 "\x1BNHI" => 'Ï', // 207 in CP1252 "\x1BNb" => 'Ð', // 208 in CP1252 "\x1BNDN" => 'Ñ', // 209 in CP1252 "\x1BNAO" => 'Ò', // 210 in CP1252 "\x1BNBO" => 'Ó', // 211 in CP1252 "\x1BNCO" => 'Ô', // 212 in CP1252 "\x1BNDO" => 'Õ', // 213 in CP1252 "\x1BNHO" => 'Ö', // 214 in CP1252 "\x1B-7" => '×', // 215 in CP1252 "\x1BNi" => 'Ø', // 216 in CP1252 "\x1BNAU" => 'Ù', // 217 in CP1252 "\x1BNBU" => 'Ú', // 218 in CP1252 "\x1BNCU" => 'Û', // 219 in CP1252 "\x1BNHU" => 'Ü', // 220 in CP1252 "\x1B-=" => 'Ý', // 221 in CP1252 "\x1BNl" => 'Þ', // 222 in CP1252 "\x1BN{" => 'ß', // 223 in CP1252 "\x1BNAa" => 'à', // 224 in CP1252 "\x1BNBa" => 'á', // 225 in CP1252 "\x1BNCa" => 'â', // 226 in CP1252 "\x1BNDa" => 'ã', // 227 in CP1252 "\x1BNHa" => 'ä', // 228 in CP1252 "\x1BNJa" => 'å', // 229 in CP1252 "\x1BNq" => 'æ', // 230 in CP1252 "\x1BNKc" => 'ç', // 231 in CP1252 "\x1BNAe" => 'è', // 232 in CP1252 "\x1BNBe" => 'é', // 233 in CP1252 "\x1BNCe" => 'ê', // 234 in CP1252 "\x1BNHe" => 'ë', // 235 in CP1252 "\x1BNAi" => 'ì', // 236 in CP1252 "\x1BNBi" => 'í', // 237 in CP1252 "\x1BNCi" => 'î', // 238 in CP1252 "\x1BNHi" => 'ï', // 239 in CP1252 "\x1BNs" => 'ð', // 240 in CP1252 "\x1BNDn" => 'ñ', // 241 in CP1252 "\x1BNAo" => 'ò', // 242 in CP1252 "\x1BNBo" => 'ó', // 243 in CP1252 "\x1BNCo" => 'ô', // 244 in CP1252 "\x1BNDo" => 'õ', // 245 in CP1252 "\x1BNHo" => 'ö', // 246 in CP1252 "\x1B/7" => '÷', // 247 in CP1252 "\x1BNy" => 'ø', // 248 in CP1252 "\x1BNAu" => 'ù', // 249 in CP1252 "\x1BNBu" => 'ú', // 250 in CP1252 "\x1BNCu" => 'û', // 251 in CP1252 "\x1BNHu" => 'ü', // 252 in CP1252 "\x1B/=" => 'ý', // 253 in CP1252 "\x1BN|" => 'þ', // 254 in CP1252 "\x1BNHy" => 'ÿ', // 255 in CP1252 ]; /** * Decimal separator. */ protected static ?string $decimalSeparator = null; /** * Thousands separator. */ protected static ?string $thousandsSeparator = null; /** * Currency code. */ protected static ?string $currencyCode = null; /** * Is iconv extension available? */ protected static ?bool $isIconvEnabled = null; /** * iconv options. */ protected static string $iconvOptions = '//IGNORE//TRANSLIT'; /** @var string[] */ protected static array $iconvOptionsArray = ['//IGNORE//TRANSLIT', '//IGNORE']; /** @internal */ protected static string $iconvName = 'iconv'; /** @internal */ protected static bool $iconvTest2 = false; /** @internal */ protected static bool $iconvTest3 = false; /** * Get whether iconv extension is available. */ public static function getIsIconvEnabled(): bool { if (isset(static::$isIconvEnabled)) { return static::$isIconvEnabled; } // Assume no problems with iconv static::$isIconvEnabled = true; // Fail if iconv doesn't exist if (!function_exists(static::$iconvName)) { static::$isIconvEnabled = false; } elseif (static::$iconvTest2 || !@iconv('UTF-8', 'UTF-16LE', 'x')) { // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false, static::$isIconvEnabled = false; } elseif (static::$iconvTest3 || (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0))) { // CUSTOM: IBM AIX iconv() does not work static::$isIconvEnabled = false; } // Deactivate iconv default options if they fail (as seen on IBM i-series) if (static::$isIconvEnabled) { static::$iconvOptions = ''; foreach (static::$iconvOptionsArray as $option) { if (@iconv('UTF-8', 'UTF-16LE' . $option, 'x') !== false) { static::$iconvOptions = $option; break; } } } return static::$isIconvEnabled; } /** * Convert from OpenXML escaped control character to PHP control character. * * Excel 2007 team: * ---------------- * That's correct, control characters are stored directly in the shared-strings table. * We do encode characters that cannot be represented in XML using the following escape sequence: * _xHHHH_ where H represents a hexadecimal character in the character's value... * So you could end up with something like _x0008_ in a string (either in a cell value () * element or in the shared string element. * * @param string $textValue Value to unescape */ public static function controlCharacterOOXML2PHP(string $textValue): string { return Preg::replaceCallback('/_x[0-9A-F]{4}_(_xD[CDEF][0-9A-F]{2}_)?/', self::toOutChar(...), $textValue); } private static function toHexVal(string $char): int { if ($char >= '0' && $char <= '9') { return ord($char) - ord('0'); } return ord($char) - ord('A') + 10; } /** @param array $match */ private static function toOutChar(array $match): string { /** @var string */ $chars = $match[0]; $h = ((self::toHexVal($chars[2]) << 12) | (self::toHexVal($chars[3]) << 8) | (self::toHexVal($chars[4]) << 4) | (self::toHexVal($chars[5]))); if (strlen($chars) === 7) { // no low surrogate if ($chars[2] === 'D' && in_array($chars[3], ['8', '9', 'A', 'B', 'C', 'D', 'E', 'F'], true)) { return '�'; } return mb_chr($h, 'UTF-8'); } if ($chars[2] === 'D' && in_array($chars[3], ['C', 'D', 'D', 'F'], true)) { return '�'; // Excel interprets as one substitute, not 2 } if ($chars[2] !== 'D' || !in_array($chars[3], ['8', '9', 'A', 'B'], true)) { return mb_chr($h, 'UTF-8') . '�'; } $l = ((self::toHexVal($chars[9]) << 12) | (self::toHexVal($chars[10]) << 8) | (self::toHexVal($chars[11]) << 4) | (self::toHexVal($chars[12]))); $result = 0x10000 + ($h - 0xD800) * 0x400 + ($l - 0xDC00); return mb_chr($result, 'UTF-8'); } /** * Convert from PHP control character to OpenXML escaped control character. * * Excel 2007 team: * ---------------- * That's correct, control characters are stored directly in the shared-strings table. * We do encode characters that cannot be represented in XML using the following escape sequence: * _xHHHH_ where H represents a hexadecimal character in the character's value... * So you could end up with something like _x0008_ in a string (either in a cell value () * element or in the shared string element. * * @param string $textValue Value to escape */ public static function controlCharacterPHP2OOXML(string $textValue): string { $textValue = Preg::replace('/_(x[0-9A-F]{4}_)/', '_x005F_$1', $textValue); return str_replace(self::CONTROL_CHARACTERS_KEYS, self::CONTROL_CHARACTERS_VALUES, $textValue); } /** * Try to sanitize UTF8, replacing invalid sequences with Unicode substitution characters. */ public static function sanitizeUTF8(string $textValue): string { $textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue); $subst = mb_substitute_character(); // default is question mark mb_substitute_character(65533); // Unicode substitution character $returnValue = (string) mb_convert_encoding($textValue, 'UTF-8', 'UTF-8'); mb_substitute_character($subst); return $returnValue; } /** * Check if a string contains UTF8 data. */ public static function isUTF8(string $textValue): bool { return $textValue === self::sanitizeUTF8($textValue); } /** * Formats a numeric value as a string for output in various output writers forcing * point as decimal separator in case locale is other than English. */ public static function formatNumber(float|int|string|null $numericValue): string { if (is_float($numericValue)) { return str_replace(',', '.', (string) $numericValue); } return (string) $numericValue; } /** * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length) * Writes the string using uncompressed notation, no rich text, no Asian phonetics * If mbstring extension is not available, ASCII is assumed, and compressed notation is used * although this will give wrong results for non-ASCII strings * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * * @param string $textValue UTF-8 encoded string * @param array $arrcRuns Details of rich text runs in $value */ public static function UTF8toBIFF8UnicodeShort(string $textValue, array $arrcRuns = []): string { // character count $ln = self::countCharacters($textValue, 'UTF-8'); // option flags if (empty($arrcRuns)) { $data = pack('CC', $ln, 0x0001); // characters $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); } else { $data = pack('vC', $ln, 0x09); $data .= pack('v', count($arrcRuns)); // characters $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); foreach ($arrcRuns as $cRun) { $data .= pack('v', $cRun['strlen']); $data .= pack('v', $cRun['fontidx']); } } return $data; } /** * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length) * Writes the string using uncompressed notation, no rich text, no Asian phonetics * If mbstring extension is not available, ASCII is assumed, and compressed notation is used * although this will give wrong results for non-ASCII strings * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * * @param string $textValue UTF-8 encoded string */ public static function UTF8toBIFF8UnicodeLong(string $textValue): string { // characters $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); $ln = (int) (strlen($chars) / 2); // N.B. - strlen, not mb_strlen issue #642 return pack('vC', $ln, 0x0001) . $chars; } /** * Convert string from one encoding to another. * * @param string $to Encoding to convert to, e.g. 'UTF-8' * @param string $from Encoding to convert from, e.g. 'UTF-16LE' */ public static function convertEncoding(string $textValue, string $to, string $from, ?string $options = null): string { if (static::getIsIconvEnabled()) { $result = iconv($from, $to . ($options ?? static::$iconvOptions), $textValue); if (false !== $result) { return $result; } } return (string) mb_convert_encoding($textValue, $to, $from); } /** * Get character count. * * @param string $encoding Encoding * * @return int Character count */ public static function countCharacters(string $textValue, string $encoding = 'UTF-8'): int { return mb_strlen($textValue, $encoding); } /** * Get character count using mb_strwidth rather than mb_strlen. * * @param string $encoding Encoding * * @return int Character count */ public static function countCharactersDbcs(string $textValue, string $encoding = 'UTF-8'): int { return mb_strwidth($textValue, $encoding); } /** * Get a substring of a UTF-8 encoded string. * * @param string $textValue UTF-8 encoded string * @param int $offset Start offset * @param ?int $length Maximum number of characters in substring */ public static function substring(string $textValue, int $offset, ?int $length = 0): string { return mb_substr($textValue, $offset, $length, 'UTF-8'); } /** * Convert a UTF-8 encoded string to upper case. * * @param string $textValue UTF-8 encoded string */ public static function strToUpper(string $textValue): string { return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8'); } /** * Convert a UTF-8 encoded string to lower case. * * @param string $textValue UTF-8 encoded string */ public static function strToLower(string $textValue): string { return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8'); } /** * Convert a UTF-8 encoded string to title/proper case * (uppercase every first character in each word, lower case all other characters). * * @param string $textValue UTF-8 encoded string */ public static function strToTitle(string $textValue): string { return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8'); } public static function mbIsUpper(string $character): bool { return mb_strtolower($character, 'UTF-8') !== $character; } /** * Splits a UTF-8 string into an array of individual characters. * * @return string[] */ public static function mbStrSplit(string $string): array { // Split at all position not after the start: ^ // and not before the end: $ $split = Preg::split('/(? $v) { $textValue = str_replace($k, $v, $textValue); } return $textValue; } /** * Retrieve any leading numeric part of a string, or return the full string if no leading numeric * (handles basic integer or float, but not exponent or non decimal). * * @return float|string string or only the leading numeric part of the string */ public static function testStringAsNumeric(string $textValue): float|string { if (is_numeric($textValue)) { return $textValue; } $v = (float) $textValue; return (is_numeric(substr($textValue, 0, strlen((string) $v)))) ? $v : $textValue; } public static function strlenAllowNull(?string $string): int { return strlen("$string"); } /** * @param bool $convertBool If true, convert bool to locale-aware TRUE/FALSE rather than 1/null-string * @param bool $lessFloatPrecision If true, floats will be converted to a more human-friendly but less computationally accurate value */ public static function convertToString(mixed $value, bool $throw = true, string $default = '', bool $convertBool = false, bool $lessFloatPrecision = false): string { if ($convertBool && is_bool($value)) { return $value ? Calculation::getTRUE() : Calculation::getFALSE(); } if (is_float($value) && !$lessFloatPrecision) { $string = (string) $value; // look out for scientific notation if (!Preg::isMatch('/[^-+0-9.]/', $string)) { $minus = $value < 0 ? '-' : ''; $positive = abs($value); $floor = floor($positive); $oldFrac = (string) ($positive - $floor); $frac = Preg::replace('/^0[.](\d+)$/', '$1', $oldFrac); if ($frac !== $oldFrac) { return "$minus$floor.$frac"; } } return $string; } if ($value === null || is_scalar($value) || $value instanceof Stringable) { return (string) $value; } if ($throw) { throw new SpreadsheetException('Unable to convert to string'); } return $default; } /** * Assist with POST items when samples are run in browser. * Never run as part of unit tests, which are command line. * * @codeCoverageIgnore */ public static function convertPostToString(string $index, string $default = ''): string { if (isset($_POST[$index])) { return htmlentities(self::convertToString($_POST[$index], false, $default)); } return $default; } /** * Php introduced str_increment with Php8.3, * but didn't issue deprecation notices till 8.5. * * @codeCoverageIgnore */ public static function stringIncrement(string &$str): string { if (function_exists('str_increment')) { $str = str_increment($str); // @phpstan-ignore-line } else { ++$str; // @phpstan-ignore-line } return $str; // @phpstan-ignore-line } /** @internal */ protected static string $testClass = IntlCalendar::class; /** * Set all of currencyCode, thousandsSeparator, decimalSeparator, * and Calculation locale with a single call. * The main point here is avoid the use of Php setlocale, * which is not threadsafe. It uses the Intl extension instead, * which is not a requirement for PhpSpreadsheet. * Because of that, the function returns a bool which will * be false if Intl is not available, or the supplied locale * is not valid according to Intl. */ public static function setLocale(?string $locale): bool { if ($locale === null) { self::$currencyCode = null; self::$thousandsSeparator = null; self::$decimalSeparator = null; Calculation::getInstance()->setLocale('en_us'); return true; } $localeCalc = $locale; if (Preg::isMatch('/^([a-z][a-z])_([a-z][a-z])(?:[.]utf-8)?$/i', $locale, $matches)) { $locale = strtolower($matches[1]) . '_' . strtoupper($matches[2]); $localeCalc = strtolower($matches[1]) . '_' . strtolower($matches[2]); } if (!class_exists(static::$testClass)) { return false; } // NumberFormatter constructor succeeds even with // bad locale before Php8.4, so try to validate // the locale beforehand. $locales = IntlCalendar::getAvailableLocales(); if (!in_array($locale, $locales, true)) { return false; } $formatter = new NumberFormatter( $locale, NumberFormatter::CURRENCY ); $currency = $formatter->getSymbol( NumberFormatter::CURRENCY_SYMBOL ); $formatter = new NumberFormatter( $locale, NumberFormatter::DECIMAL ); $thousands = $formatter->getSymbol( NumberFormatter::GROUPING_SEPARATOR_SYMBOL ); $decimal = $formatter->getSymbol( NumberFormatter::DECIMAL_SEPARATOR_SYMBOL ); self::$currencyCode = $currency; self::$thousandsSeparator = $thousands; self::$decimalSeparator = $decimal; Calculation::getInstance()->setLocale($localeCalc); return true; } } ================================================ FILE: src/PhpSpreadsheet/Shared/TimeZone.php ================================================ setTimeZone(new DateTimeZone($timezoneName)); return $dtobj->getOffset(); } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/BestFit.php ================================================ error; } public function getBestFitType(): string { return $this->bestFitType; } /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ abstract public function getValueOfYForX(float $xValue): float; /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ abstract public function getValueOfXForY(float $yValue): float; /** * Return the original set of X-Values. * * @return float[] X-Values */ public function getXValues(): array { return $this->xValues; } /** * Return the original set of Y-Values. * * @return float[] Y-Values */ public function getYValues(): array { return $this->yValues; } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ abstract public function getEquation(int $dp = 0): string; /** * Return the Slope of the line. * * @param int $dp Number of places of decimal precision to display */ public function getSlope(int $dp = 0): float { if ($dp != 0) { return round($this->slope, $dp); } return $this->slope; } /** * Return the standard error of the Slope. * * @param int $dp Number of places of decimal precision to display */ public function getSlopeSE(int $dp = 0): float { if ($dp != 0) { return round($this->slopeSE, $dp); } return $this->slopeSE; } /** * Return the Value of X where it intersects Y = 0. * * @param int $dp Number of places of decimal precision to display */ public function getIntersect(int $dp = 0): float { if ($dp != 0) { return round($this->intersect, $dp); } return $this->intersect; } /** * Return the standard error of the Intersect. * * @param int $dp Number of places of decimal precision to display */ public function getIntersectSE(int $dp = 0): float { if ($dp != 0) { return round($this->intersectSE, $dp); } return $this->intersectSE; } /** * Return the goodness of fit for this regression. * * @param int $dp Number of places of decimal precision to return */ public function getGoodnessOfFit(int $dp = 0): float { if ($dp != 0) { return round($this->goodnessOfFit, $dp); } return $this->goodnessOfFit; } /** * Return the goodness of fit for this regression. * * @param int $dp Number of places of decimal precision to return */ public function getGoodnessOfFitPercent(int $dp = 0): float { if ($dp != 0) { return round($this->goodnessOfFit * 100, $dp); } return $this->goodnessOfFit * 100; } /** * Return the standard deviation of the residuals for this regression. * * @param int $dp Number of places of decimal precision to return */ public function getStdevOfResiduals(int $dp = 0): float { if ($dp != 0) { return round($this->stdevOfResiduals, $dp); } return $this->stdevOfResiduals; } /** * @param int $dp Number of places of decimal precision to return */ public function getSSRegression(int $dp = 0): float { if ($dp != 0) { return round($this->SSRegression, $dp); } return $this->SSRegression; } /** * @param int $dp Number of places of decimal precision to return */ public function getSSResiduals(int $dp = 0): float { if ($dp != 0) { return round($this->SSResiduals, $dp); } return $this->SSResiduals; } /** * @param int $dp Number of places of decimal precision to return */ public function getDFResiduals(int $dp = 0): float { if ($dp != 0) { return round($this->DFResiduals, $dp); } return $this->DFResiduals; } /** * @param int $dp Number of places of decimal precision to return */ public function getF(int $dp = 0): float { if ($dp != 0) { return round($this->f, $dp); } return $this->f; } /** * @param int $dp Number of places of decimal precision to return */ public function getCovariance(int $dp = 0): float { if ($dp != 0) { return round($this->covariance, $dp); } return $this->covariance; } /** * @param int $dp Number of places of decimal precision to return */ public function getCorrelation(int $dp = 0): float { if ($dp != 0) { return round($this->correlation, $dp); } return $this->correlation; } /** * @return float[] */ public function getYBestFitValues(): array { return $this->yBestFitValues; } protected function calculateGoodnessOfFit(float $sumX, float $sumY, float $sumX2, float $sumY2, float $sumXY, float $meanX, float $meanY, bool|int $const): void { $SSres = $SScov = $SStot = $SSsex = 0.0; foreach ($this->xValues as $xKey => $xValue) { $bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); $SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY); if ($const === true) { $SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY); } else { $SStot += $this->yValues[$xKey] * $this->yValues[$xKey]; } $SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY); if ($const === true) { $SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX); } else { $SSsex += $this->xValues[$xKey] * $this->xValues[$xKey]; } } $this->SSResiduals = $SSres; $this->DFResiduals = $this->valueCount - 1 - ($const === true ? 1 : 0); if ($this->DFResiduals == 0.0) { $this->stdevOfResiduals = 0.0; } else { $this->stdevOfResiduals = sqrt($SSres / $this->DFResiduals); } if ($SStot == 0.0 || $SSres == $SStot) { $this->goodnessOfFit = 1; } else { $this->goodnessOfFit = 1 - ($SSres / $SStot); } $this->SSRegression = $this->goodnessOfFit * $SStot; $this->covariance = $SScov / $this->valueCount; $this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - $sumX ** 2) * ($this->valueCount * $sumY2 - $sumY ** 2)); $this->slopeSE = $this->stdevOfResiduals / sqrt($SSsex); $this->intersectSE = $this->stdevOfResiduals * sqrt(1 / ($this->valueCount - ($sumX * $sumX) / $sumX2)); if ($this->SSResiduals != 0.0) { if ($this->DFResiduals == 0.0) { $this->f = 0.0; } else { $this->f = $this->SSRegression / ($this->SSResiduals / $this->DFResiduals); } } else { if ($this->DFResiduals == 0.0) { $this->f = 0.0; } else { $this->f = $this->SSRegression / $this->DFResiduals; } } } /** * @param array $values * * @return float|int */ private function sumSquares(array $values) { return array_sum( array_map( fn ($value): float|int => $value ** 2, $values ) ); } /** * @param float[] $yValues * @param float[] $xValues */ protected function leastSquareFit(array $yValues, array $xValues, bool $const): void { // calculate sums $sumValuesX = array_sum($xValues); $sumValuesY = array_sum($yValues); $meanValueX = $sumValuesX / $this->valueCount; $meanValueY = $sumValuesY / $this->valueCount; $sumSquaresX = $this->sumSquares($xValues); $sumSquaresY = $this->sumSquares($yValues); $mBase = $mDivisor = 0.0; $xy_sum = 0.0; for ($i = 0; $i < $this->valueCount; ++$i) { $xy_sum += $xValues[$i] * $yValues[$i]; if ($const === true) { $mBase += ($xValues[$i] - $meanValueX) * ($yValues[$i] - $meanValueY); $mDivisor += ($xValues[$i] - $meanValueX) * ($xValues[$i] - $meanValueX); } else { $mBase += $xValues[$i] * $yValues[$i]; $mDivisor += $xValues[$i] * $xValues[$i]; } } // calculate slope $this->slope = $mBase / $mDivisor; // calculate intersect $this->intersect = ($const === true) ? $meanValueY - ($this->slope * $meanValueX) : 0.0; $this->calculateGoodnessOfFit($sumValuesX, $sumValuesY, $sumSquaresX, $sumSquaresY, $xy_sum, $meanValueX, $meanValueY, $const); } /** * Define the regression. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = []) { // Calculate number of points $yValueCount = count($yValues); $xValueCount = count($xValues); // Define X Values if necessary if ($xValueCount === 0) { $xValues = range(1.0, $yValueCount); } elseif ($yValueCount !== $xValueCount) { // Ensure both arrays of points are the same size $this->error = true; } $this->valueCount = $yValueCount; $this->xValues = $xValues; $this->yValues = $yValues; } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php ================================================ getIntersect() * $this->getSlope() ** ($xValue - $this->xOffset); } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return log(($yValue + $this->yOffset) / $this->getIntersect()) / log($this->getSlope()); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $intersect . ' * ' . $slope . '^X'; } /** * Return the Slope of the line. * * @param int $dp Number of places of decimal precision to display */ public function getSlope(int $dp = 0): float { if ($dp != 0) { return round(exp($this->slope), $dp); } return exp($this->slope); } /** * Return the Value of X where it intersects Y = 0. * * @param int $dp Number of places of decimal precision to display */ public function getIntersect(int $dp = 0): float { if ($dp != 0) { return round(exp($this->intersect), $dp); } return exp($this->intersect); } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function exponentialRegression(array $yValues, array $xValues, bool $const): void { $adjustedYValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $yValues ); $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->exponentialRegression($yValues, $xValues, (bool) $const); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php ================================================ getIntersect() + $this->getSlope() * $xValue; } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return ($yValue - $this->getIntersect()) / $this->getSlope(); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $intersect . ' + ' . $slope . ' * X'; } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function linearRegression(array $yValues, array $xValues, bool $const): void { $this->leastSquareFit($yValues, $xValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->linearRegression($this->yValues, $this->xValues, (bool) $const); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php ================================================ getIntersect() + $this->getSlope() * log($xValue - $this->xOffset); } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return exp(($yValue - $this->getIntersect()) / $this->getSlope()); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $slope . ' * log(' . $intersect . ' * X)'; } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function logarithmicRegression(array $yValues, array $xValues, bool $const): void { $adjustedYValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $yValues ); $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->logarithmicRegression($yValues, $xValues, (bool) $const); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php ================================================ slope is specified where an array is expected in several places. // But it seems that it should always be float. // This code is probably not exercised at all in unit tests. // Private bool property $implemented is set to indicate // whether this implementation is correct. class PolynomialBestFit extends BestFit { /** * Algorithm type to use for best-fit * (Name of this Trend class). */ protected string $bestFitType = 'polynomial'; /** * Polynomial order. */ protected int $order = 0; private bool $implemented = false; /** * Return the order of this polynomial. */ public function getOrder(): int { return $this->order; } /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ public function getValueOfYForX(float $xValue): float { $retVal = $this->getIntersect(); $slope = $this->getSlope(); // Phpstan and Scrutinizer are both correct - getSlope returns float, not array. // @phpstan-ignore-next-line foreach ($slope as $key => $value) { /** @var float $value */ if ($value != 0.0) { /** @var int $key */ $retVal += $value * $xValue ** ($key + 1); } } return $retVal; } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return ($yValue - $this->getIntersect()) / $this->getSlope(); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); $equation = 'Y = ' . $intersect; // Phpstan and Scrutinizer are both correct - getSlope returns float, not array. // @phpstan-ignore-next-line foreach ($slope as $key => $value) { /** @var float|int $value */ if ($value != 0.0) { $equation .= ' + ' . $value . ' * X'; /** @var int $key */ if ($key > 0) { $equation .= '^' . ($key + 1); } } } return $equation; } /** * Return the Slope of the line. * * @param int $dp Number of places of decimal precision to display */ public function getSlope(int $dp = 0): float { if ($dp != 0) { $coefficients = []; //* @phpstan-ignore-next-line foreach ($this->slope as $coefficient) { /** @var float|int $coefficient */ $coefficients[] = round($coefficient, $dp); } // @phpstan-ignore-next-line return $coefficients; } return $this->slope; } /** @return array */ public function getCoefficients(int $dp = 0): array { // Phpstan and Scrutinizer are both correct - getSlope returns float, not array. // @phpstan-ignore-next-line return array_merge([$this->getIntersect($dp)], $this->getSlope($dp)); } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param int $order Order of Polynomial for this regression * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function polynomialRegression(int $order, array $yValues, array $xValues): void { // calculate sums $x_sum = array_sum($xValues); $y_sum = array_sum($yValues); $xx_sum = $xy_sum = $yy_sum = 0; for ($i = 0; $i < $this->valueCount; ++$i) { $xy_sum += $xValues[$i] * $yValues[$i]; $xx_sum += $xValues[$i] * $xValues[$i]; $yy_sum += $yValues[$i] * $yValues[$i]; } /* * This routine uses logic from the PHP port of polyfit version 0.1 * written by Michael Bommarito and Paul Meagher * * The function fits a polynomial function of order $order through * a series of x-y data points using least squares. * */ $A = []; $B = []; for ($i = 0; $i < $this->valueCount; ++$i) { for ($j = 0; $j <= $order; ++$j) { $A[$i][$j] = $xValues[$i] ** $j; } } for ($i = 0; $i < $this->valueCount; ++$i) { $B[$i] = [$yValues[$i]]; } $matrixA = new Matrix($A); $matrixB = new Matrix($B); $C = $matrixA->solve($matrixB); $coefficients = []; for ($i = 0; $i < $C->rows; ++$i) { $r = $C->getValue($i + 1, 1); // row and column are origin-1 if (!is_numeric($r) || abs($r + 0) <= 10 ** (-9)) { $r = 0; } else { $r += 0; } $coefficients[] = $r; } $this->intersect = (float) array_shift($coefficients); // Phpstan is correct //* @phpstan-ignore-next-line $this->slope = $coefficients; $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, 0, 0, 0); foreach ($this->xValues as $xKey => $xValue) { $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); } } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param int $order Order of Polynomial for this regression * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(int $order, array $yValues, array $xValues = []) { if (!$this->implemented) { throw new SpreadsheetException('Polynomial Best Fit not yet implemented'); } parent::__construct($yValues, $xValues); if (!$this->error) { if ($order < $this->valueCount) { $this->bestFitType .= '_' . $order; $this->order = $order; $this->polynomialRegression($order, $yValues, $xValues); if (($this->getGoodnessOfFit() < 0.0) || ($this->getGoodnessOfFit() > 1.0)) { $this->error = true; } } else { $this->error = true; } } } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php ================================================ getIntersect() * ($xValue - $this->xOffset) ** $this->getSlope(); } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return (($yValue + $this->yOffset) / $this->getIntersect()) ** (1 / $this->getSlope()); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $intersect . ' * X^' . $slope; } /** * Return the Value of X where it intersects Y = 0. * * @param int $dp Number of places of decimal precision to display */ public function getIntersect(int $dp = 0): float { if ($dp != 0) { return round(exp($this->intersect), $dp); } return exp($this->intersect); } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function powerRegression(array $yValues, array $xValues, bool $const): void { $adjustedYValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $yValues ); $adjustedXValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $xValues ); $this->leastSquareFit($adjustedYValues, $adjustedXValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->powerRegression($yValues, $xValues, (bool) $const); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/Trend/Trend.php ================================================ getGoodnessOfFit(); } if ($trendType !== self::TREND_BEST_FIT_NO_POLY) { foreach (self::$trendTypePolynomialOrders as $trendMethod) { $order = (int) substr($trendMethod, -1); $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues); if ($bestFit[$trendMethod]->getError()) { unset($bestFit[$trendMethod]); } else { $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); } } } // Determine which of our Trend lines is the best fit, and then we return the instance of that Trend class arsort($bestFitValue); $bestFitType = key($bestFitValue); return $bestFit[$bestFitType]; default: throw new SpreadsheetException("Unknown trend type $trendType"); } } } ================================================ FILE: src/PhpSpreadsheet/Shared/XMLWriter.php ================================================ openMemory(); } else { // Create temporary filename if ($temporaryStorageFolder === null) { $temporaryStorageFolder = File::sysGetTempDir(); } $this->tempFileName = (string) @tempnam($temporaryStorageFolder, 'xml'); // Open storage if (empty($this->tempFileName) || $this->openUri($this->tempFileName) === false) { // Fallback to memory... $this->openMemory(); if ($this->tempFileName != '') { @unlink($this->tempFileName); } $this->tempFileName = ''; } } // Set default values if (self::$debugEnabled) { $this->setIndent(true); } } /** * Destructor. */ public function __destruct() { // Unlink temporary files // There is nothing reasonable to do if unlink fails. if ($this->tempFileName != '') { @unlink($this->tempFileName); } } /** @param mixed[] $data */ public function __unserialize(array $data): void { $this->tempFileName = ''; throw new SpreadsheetException('Unserialize not permitted'); } /** * Get written data. */ public function getData(): string { if ($this->tempFileName == '') { return $this->outputMemory(true); } $this->flush(); return file_get_contents($this->tempFileName) ?: ''; } /** * Wrapper method for writeRaw. * * @param null|string|string[] $rawTextData */ public function writeRawData($rawTextData): bool { if (is_array($rawTextData)) { $rawTextData = implode("\n", $rawTextData); } return $this->text($rawTextData ?? ''); } } ================================================ FILE: src/PhpSpreadsheet/Shared/Xls.php ================================================ getParentOrThrow()->getDefaultStyle()->getFont(); $columnDimensions = $worksheet->getColumnDimensions(); // first find the true column width in pixels (uncollapsed and unhidden) if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) { // then we have column dimension with explicit width $columnDimension = $columnDimensions[$col]; $width = $columnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); } elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) { // then we have default column dimension with explicit width $defaultColumnDimension = $worksheet->getDefaultColumnDimension(); $width = $defaultColumnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); } else { // we don't even have any default column dimension. Width depends on default font $pixelWidth = Font::getDefaultColumnWidthByFont($font, true); } // now find the effective column width in pixels if (isset($columnDimensions[$col]) && !$columnDimensions[$col]->getVisible()) { $effectivePixelWidth = 0; } else { $effectivePixelWidth = $pixelWidth; } return $effectivePixelWidth; } /** * Convert the height of a cell from user's units to pixels. By interpolation * the relationship is: y = 4/3x. If the height hasn't been set by the user we * use the default value. If the row is hidden we use a value of zero. * * @param Worksheet $worksheet The sheet * @param int $row The row index (1-based) * * @return int The width in pixels */ public static function sizeRow(Worksheet $worksheet, int $row = 1): int { // default font of the workbook $font = $worksheet->getParentOrThrow()->getDefaultStyle()->getFont(); $rowDimensions = $worksheet->getRowDimensions(); // first find the true row height in pixels (uncollapsed and unhidden) if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) { // then we have a row dimension $rowDimension = $rowDimensions[$row]; $rowHeight = $rowDimension->getRowHeight(); $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 } elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) { // then we have a default row dimension with explicit height $defaultRowDimension = $worksheet->getDefaultRowDimension(); $pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS); } else { // we don't even have any default row dimension. Height depends on default font $pointRowHeight = Font::getDefaultRowHeightByFont($font); $pixelRowHeight = Font::fontSizeToPixels((int) $pointRowHeight); } // now find the effective row height in pixels if (isset($rowDimensions[$row]) && !$rowDimensions[$row]->getVisible()) { $effectivePixelRowHeight = 0; } else { $effectivePixelRowHeight = $pixelRowHeight; } return (int) $effectivePixelRowHeight; } /** * Get the horizontal distance in pixels between two anchors * The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets. * * @param float|int $startOffsetX Offset within start cell measured in 1/1024 of the cell width * @param float|int $endOffsetX Offset within end cell measured in 1/1024 of the cell width * * @return int Horizontal measured in pixels */ public static function getDistanceX(Worksheet $worksheet, string $startColumn = 'A', float|int $startOffsetX = 0, string $endColumn = 'A', float|int $endOffsetX = 0): int { $distanceX = 0; // add the widths of the spanning columns $startColumnIndex = Coordinate::columnIndexFromString($startColumn); $endColumnIndex = Coordinate::columnIndexFromString($endColumn); for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { $distanceX += self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($i)); } // correct for offsetX in startcell $distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024); // correct for offsetX in endcell $distanceX -= (int) floor(self::sizeCol($worksheet, $endColumn) * (1 - $endOffsetX / 1024)); return $distanceX; } /** * Get the vertical distance in pixels between two anchors * The distanceY is found as sum of all the spanning rows minus two offsets. * * @param int $startRow (1-based) * @param float|int $startOffsetY Offset within start cell measured in 1/256 of the cell height * @param int $endRow (1-based) * @param float|int $endOffsetY Offset within end cell measured in 1/256 of the cell height * * @return int Vertical distance measured in pixels */ public static function getDistanceY(Worksheet $worksheet, int $startRow = 1, float|int $startOffsetY = 0, int $endRow = 1, float|int $endOffsetY = 0): int { $distanceY = 0; // add the widths of the spanning rows for ($row = $startRow; $row <= $endRow; ++$row) { $distanceY += self::sizeRow($worksheet, $row); } // correct for offsetX in startcell $distanceY -= (int) floor(self::sizeRow($worksheet, $startRow) * $startOffsetY / 256); // correct for offsetX in endcell $distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256)); return $distanceY; } /** * Convert 1-cell anchor coordinates to 2-cell anchor coordinates * This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications. * * Calculate the vertices that define the position of the image as required by * the OBJ record. * * +------------+------------+ * | A | B | * +-----+------------+------------+ * | |(x1,y1) | | * | 1 |(A1)._______|______ | * | | | | | * | | | | | * +-----+----| BITMAP |-----+ * | | | | | * | 2 | |______________. | * | | | (B2)| * | | | (x2,y2)| * +---- +------------+------------+ * * Example of a bitmap that covers some of the area from cell A1 to cell B2. * * Based on the width and height of the bitmap we need to calculate 8 vars: * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. * The width and height of the cells are also variable and have to be taken into * account. * The values of $col_start and $row_start are passed in from the calling * function. The values of $col_end and $row_end are calculated by subtracting * the width and height of the bitmap from the width and height of the * underlying cells. * The vertices are expressed as a percentage of the underlying cell width as * follows (rhs values are in pixels): * * x1 = X / W *1024 * y1 = Y / H *256 * x2 = (X-1) / W *1024 * y2 = (Y-1) / H *256 * * Where: X is distance from the left side of the underlying cell * Y is distance from the top of the underlying cell * W is the width of the cell * H is the height of the cell * * @param string $coordinates E.g. 'A1' * @param int $offsetX Horizontal offset in pixels * @param int $offsetY Vertical offset in pixels * @param int $width Width in pixels * @param int $height Height in pixels * * @return ?array{startCoordinates: string, startOffsetX: float|int, startOffsetY: float|int, endCoordinates: string, endOffsetX: float|int, endOffsetY: float|int} */ public static function oneAnchor2twoAnchor(Worksheet $worksheet, string $coordinates, int $offsetX, int $offsetY, int $width, int $height): ?array { [$col_start, $row] = Coordinate::indexesFromString($coordinates); $row_start = $row - 1; $x1 = $offsetX; $y1 = $offsetY; // Initialise end cell to the same as the start cell $col_end = $col_start; // Col containing lower right corner of object $row_end = $row_start; // Row containing bottom right corner of object // Zero the specified offset if greater than the cell dimensions if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) { $x1 = 0; } if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) { $y1 = 0; } $width = $width + $x1 - 1; $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) { $width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)); ++$col_end; } // Subtract the underlying cell heights to find the end cell of the image while ($height >= self::sizeRow($worksheet, $row_end + 1)) { $height -= self::sizeRow($worksheet, $row_end + 1); ++$row_end; } // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // with zero height or width. if ( self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0 || self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0 || self::sizeRow($worksheet, $row_start + 1) == 0 || self::sizeRow($worksheet, $row_end + 1) == 0 ) { return null; } // Convert the pixel values to the percentage value expected by Excel $x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; $y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256; $x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object $y2 = ($height + 1) / self::sizeRow($worksheet, $row_end + 1) * 256; // Distance to bottom of object $startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1); $endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1); return [ 'startCoordinates' => $startCoordinates, 'startOffsetX' => $x1, 'startOffsetY' => $y1, 'endCoordinates' => $endCoordinates, 'endOffsetX' => $x2, 'endOffsetY' => $y2, ]; } } ================================================ FILE: src/PhpSpreadsheet/Spreadsheet.php ================================================ |string>>> */ private array $unparsedLoadedData = []; /** * Controls visibility of the horizonal scroll bar in the application. */ private bool $showHorizontalScroll = true; /** * Controls visibility of the horizonal scroll bar in the application. */ private bool $showVerticalScroll = true; /** * Controls visibility of the sheet tabs in the application. */ private bool $showSheetTabs = true; /** * Specifies a boolean value that indicates whether the workbook window * is minimized. */ private bool $minimized = false; /** * Specifies a boolean value that indicates whether to group dates * when presenting the user with filtering options in the user * interface. */ private bool $autoFilterDateGrouping = true; /** * Specifies the index to the first sheet in the book view. */ private int $firstSheetIndex = 0; /** * Specifies the visible status of the workbook. */ private string $visibility = self::VISIBILITY_VISIBLE; /** * Specifies the ratio between the workbook tabs bar and the horizontal * scroll bar. TabRatio is assumed to be out of 1000 of the horizontal * window width. */ private int $tabRatio = 600; private Theme $theme; private ?IValueBinder $valueBinder = null; /** @var array */ private array $fontCharsets = [ 'B Nazanin' => SharedFont::CHARSET_ANSI_ARABIC, ]; /** * @param int $charset uses any value from Shared\Font, * but defaults to ARABIC because that is the only known * charset for which this declaration might be needed */ public function addFontCharset(string $fontName, int $charset = SharedFont::CHARSET_ANSI_ARABIC): void { $this->fontCharsets[$fontName] = $charset; } public function getFontCharset(string $fontName): int { return $this->fontCharsets[$fontName] ?? -1; } /** * Return all fontCharsets. * * @return array */ public function getFontCharsets(): array { return $this->fontCharsets; } public function getTheme(): Theme { return $this->theme; } /** * The workbook has macros ? */ public function hasMacros(): bool { return $this->hasMacros; } /** * Define if a workbook has macros. * * @param bool $hasMacros true|false */ public function setHasMacros(bool $hasMacros): void { $this->hasMacros = (bool) $hasMacros; } /** * Set the macros code. */ public function setMacrosCode(?string $macroCode): void { $this->macrosCode = $macroCode; $this->setHasMacros($macroCode !== null); } /** * Return the macros code. */ public function getMacrosCode(): ?string { return $this->macrosCode; } /** * Set the macros certificate. */ public function setMacrosCertificate(?string $certificate): void { $this->macrosCertificate = $certificate; } /** * Is the project signed ? * * @return bool true|false */ public function hasMacrosCertificate(): bool { return $this->macrosCertificate !== null; } /** * Return the macros certificate. */ public function getMacrosCertificate(): ?string { return $this->macrosCertificate; } /** * Remove all macros, certificate from spreadsheet. */ public function discardMacros(): void { $this->hasMacros = false; $this->macrosCode = null; $this->macrosCertificate = null; } /** * set ribbon XML data. */ public function setRibbonXMLData(mixed $target, mixed $xmlData): void { if (is_string($target) && is_string($xmlData)) { $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData]; } else { $this->ribbonXMLData = null; } } /** * retrieve ribbon XML Data. * * @return mixed[] */ public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here... { $returnData = null; $what = strtolower($what); switch ($what) { case 'all': $returnData = $this->ribbonXMLData; break; case 'target': case 'data': if (is_array($this->ribbonXMLData)) { $returnData = $this->ribbonXMLData[$what]; } break; } return $returnData; } /** * store binaries ribbon objects (pictures). */ public function setRibbonBinObjects(mixed $binObjectsNames, mixed $binObjectsData): void { if ($binObjectsNames !== null && $binObjectsData !== null) { $this->ribbonBinObjects = ['names' => $binObjectsNames, 'data' => $binObjectsData]; } else { $this->ribbonBinObjects = null; } } /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @internal * * @return mixed[] */ public function getUnparsedLoadedData(): array { return $this->unparsedLoadedData; } /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @internal * * @param array|string>>> $unparsedLoadedData */ public function setUnparsedLoadedData(array $unparsedLoadedData): void { $this->unparsedLoadedData = $unparsedLoadedData; } /** * retrieve Binaries Ribbon Objects. * * @return mixed[] */ public function getRibbonBinObjects(string $what = 'all'): ?array { $ReturnData = null; $what = strtolower($what); switch ($what) { case 'all': return $this->ribbonBinObjects; case 'names': case 'data': if (is_array($this->ribbonBinObjects) && is_array($this->ribbonBinObjects[$what] ?? null)) { $ReturnData = $this->ribbonBinObjects[$what]; } break; case 'types': if ( is_array($this->ribbonBinObjects) && isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data']) ) { $tmpTypes = array_keys($this->ribbonBinObjects['data']); $ReturnData = array_unique(array_map(fn (string $path): string => pathinfo($path, PATHINFO_EXTENSION), $tmpTypes)); } else { $ReturnData = []; // the caller want an array... not null if empty } break; } return $ReturnData; } /** * This workbook have a custom UI ? */ public function hasRibbon(): bool { return $this->ribbonXMLData !== null; } /** * This workbook have additional object for the ribbon ? */ public function hasRibbonBinObjects(): bool { return $this->ribbonBinObjects !== null; } /** * This workbook has in cell images. */ public function hasInCellDrawings(): bool { $sheetCount = $this->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { if ($this->getSheet($i)->getInCellDrawingCollection()->count() > 0) { return true; } } return false; } /** * Check if a sheet with a specified code name already exists. * * @param string $codeName Name of the worksheet to check */ public function sheetCodeNameExists(string $codeName): bool { return $this->getSheetByCodeName($codeName) !== null; } /** * Get sheet by code name. Warning : sheet don't have always a code name ! * * @param string $codeName Sheet name */ public function getSheetByCodeName(string $codeName): ?Worksheet { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { if ($this->workSheetCollection[$i]->getCodeName() == $codeName) { return $this->workSheetCollection[$i]; } } return null; } /** * Create a new PhpSpreadsheet with one Worksheet. */ public function __construct() { $this->uniqueID = uniqid('', true); $this->calculationEngine = new Calculation($this); $this->theme = new Theme(); // Initialise worksheet collection and add one worksheet $this->workSheetCollection = []; $this->workSheetCollection[] = new Worksheet($this); $this->activeSheetIndex = 0; // Create document properties $this->properties = new Properties(); // Create document security $this->security = new Security(); // Set defined names $this->definedNames = []; // Create the cellXf supervisor $this->cellXfSupervisor = new Style(true); $this->cellXfSupervisor->bindParent($this); // Create the default style $this->addCellXf(new Style()); $this->addCellStyleXf(new Style()); } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { $this->disconnectWorksheets(); unset($this->calculationEngine); $this->cellXfCollection = []; $this->cellStyleXfCollection = []; $this->definedNames = []; } /** * Disconnect all worksheets from this PhpSpreadsheet workbook object, * typically so that the PhpSpreadsheet object can be unset. */ public function disconnectWorksheets(): void { foreach ($this->workSheetCollection as $worksheet) { $worksheet->disconnectCells(); unset($worksheet); } $this->workSheetCollection = []; } /** * Return the calculation engine for this worksheet. */ public function getCalculationEngine(): Calculation { return $this->calculationEngine; } /** * Intended for use only via a destructor. * * @internal */ public function getCalculationEngineOrNull(): ?Calculation { if (!isset($this->calculationEngine)) { //* @phpstan-ignore-line return null; } return $this->calculationEngine; } /** * Get properties. */ public function getProperties(): Properties { return $this->properties; } /** * Set properties. */ public function setProperties(Properties $documentProperties): void { $this->properties = $documentProperties; } /** * Get security. */ public function getSecurity(): Security { return $this->security; } /** * Set security. */ public function setSecurity(Security $documentSecurity): void { $this->security = $documentSecurity; } /** * Get active sheet. */ public function getActiveSheet(): Worksheet { return $this->getSheet($this->activeSheetIndex); } /** * Create sheet and add it to this workbook. * * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) */ public function createSheet(?int $sheetIndex = null): Worksheet { $newSheet = new Worksheet($this); $this->addSheet($newSheet, $sheetIndex, true); return $newSheet; } /** * Check if a sheet with a specified name already exists. * * @param string $worksheetName Name of the worksheet to check */ public function sheetNameExists(string $worksheetName): bool { return $this->getSheetByName($worksheetName) !== null; } public function duplicateWorksheetByTitle(string $title): Worksheet { $original = $this->getSheetByNameOrThrow($title); $index = $this->getIndex($original) + 1; $clone = clone $original; return $this->addSheet($clone, $index, true); } /** * Add sheet. * * @param Worksheet $worksheet The worksheet to add * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) */ public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet { if ($retitleIfNeeded) { $title = $worksheet->getTitle(); if ($this->sheetNameExists($title)) { $i = 1; $newTitle = "$title $i"; while ($this->sheetNameExists($newTitle)) { ++$i; $newTitle = "$title $i"; } $worksheet->setTitle($newTitle); } } if ($this->sheetNameExists($worksheet->getTitle())) { throw new Exception( "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first." ); } if ($sheetIndex === null) { if ($this->activeSheetIndex < 0) { $this->activeSheetIndex = 0; } $this->workSheetCollection[] = $worksheet; } else { // Insert the sheet at the requested index array_splice( $this->workSheetCollection, $sheetIndex, 0, [$worksheet] ); // Adjust active sheet index if necessary if ($this->activeSheetIndex >= $sheetIndex) { ++$this->activeSheetIndex; } if ($this->activeSheetIndex < 0) { $this->activeSheetIndex = 0; } } if ($worksheet->getParent() === null) { $worksheet->rebindParent($this); } return $worksheet; } /** * Remove sheet by index. * * @param int $sheetIndex Index position of the worksheet to remove */ public function removeSheetByIndex(int $sheetIndex): void { $numSheets = count($this->workSheetCollection); if ($sheetIndex > $numSheets - 1) { throw new Exception( "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}." ); } array_splice($this->workSheetCollection, $sheetIndex, 1); // Adjust active sheet index if necessary if ( ($this->activeSheetIndex >= $sheetIndex) && ($this->activeSheetIndex > 0 || $numSheets <= 1) ) { --$this->activeSheetIndex; } } /** * Get sheet by index. * * @param int $sheetIndex Sheet index */ public function getSheet(int $sheetIndex): Worksheet { if (!isset($this->workSheetCollection[$sheetIndex])) { $numSheets = $this->getSheetCount(); throw new Exception( "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}." ); } return $this->workSheetCollection[$sheetIndex]; } /** * Get all sheets. * * @return Worksheet[] */ public function getAllSheets(): array { return $this->workSheetCollection; } /** * Get sheet by name. * * @param string $worksheetName Sheet name */ public function getSheetByName(string $worksheetName): ?Worksheet { $trimWorksheetName = StringHelper::strToUpper(trim($worksheetName, "'")); foreach ($this->workSheetCollection as $worksheet) { if (StringHelper::strToUpper($worksheet->getTitle()) === $trimWorksheetName) { return $worksheet; } } return null; } /** * Get sheet by name, throwing exception if not found. */ public function getSheetByNameOrThrow(string $worksheetName): Worksheet { $worksheet = $this->getSheetByName($worksheetName); if ($worksheet === null) { throw new Exception("Sheet $worksheetName does not exist."); } return $worksheet; } /** * Get index for sheet. * * @return int index */ public function getIndex(Worksheet $worksheet, bool $noThrow = false): int { foreach ($this->workSheetCollection as $key => $value) { if ($value === $worksheet) { return $key; } } if ($noThrow) { return -1; } throw new Exception('Sheet does not exist.'); } /** * Set index for sheet by sheet name. * * @param string $worksheetName Sheet name to modify index for * @param int $newIndexPosition New index for the sheet * * @return int New sheet index */ public function setIndexByName(string $worksheetName, int $newIndexPosition): int { $oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName)); $worksheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, $newIndexPosition, 0, $worksheet ); return $newIndexPosition; } /** * Get sheet count. */ public function getSheetCount(): int { return count($this->workSheetCollection); } /** * Get active sheet index. * * @return int Active sheet index */ public function getActiveSheetIndex(): int { return $this->activeSheetIndex; } /** * Set active sheet index. * * @param int $worksheetIndex Active sheet index */ public function setActiveSheetIndex(int $worksheetIndex): Worksheet { $numSheets = count($this->workSheetCollection); if ($worksheetIndex > $numSheets - 1) { throw new Exception( "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}." ); } $this->activeSheetIndex = $worksheetIndex; return $this->getActiveSheet(); } /** * Set active sheet index by name. * * @param string $worksheetName Sheet title */ public function setActiveSheetIndexByName(string $worksheetName): Worksheet { if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); return $worksheet; } throw new Exception('Workbook does not contain sheet:' . $worksheetName); } /** * Get sheet names. * * @return string[] */ public function getSheetNames(): array { $returnValue = []; $worksheetCount = $this->getSheetCount(); for ($i = 0; $i < $worksheetCount; ++$i) { $returnValue[] = $this->getSheet($i)->getTitle(); } return $returnValue; } /** * Add external sheet. * * @param Worksheet $worksheet External sheet to add * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) */ public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet { if ($this->sheetNameExists($worksheet->getTitle())) { throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first."); } // count how many cellXfs there are in this workbook currently, we will need this below $countCellXfs = count($this->cellXfCollection); // copy all the shared cellXfs from the external workbook and append them to the current foreach ($worksheet->getParentOrThrow()->getCellXfCollection() as $cellXf) { $this->addCellXf(clone $cellXf); } // move sheet to this workbook $worksheet->rebindParent($this); // update the cellXfs foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } // update the column dimensions Xfs foreach ($worksheet->getColumnDimensions() as $columnDimension) { $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs); } // update the row dimensions Xfs foreach ($worksheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex(); if ($xfIndex !== null) { $rowDimension->setXfIndex($xfIndex + $countCellXfs); } } return $this->addSheet($worksheet, $sheetIndex); } /** * Get an array of all Named Ranges. * * @return DefinedName[] */ public function getNamedRanges(): array { return array_filter( $this->definedNames, fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE ); } /** * Get an array of all Named Formulae. * * @return DefinedName[] */ public function getNamedFormulae(): array { return array_filter( $this->definedNames, fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA ); } /** * Get an array of all Defined Names (both named ranges and named formulae). * * @return DefinedName[] */ public function getDefinedNames(): array { return $this->definedNames; } /** * Add a named range. * If a named range with this name already exists, then this will replace the existing value. */ public function addNamedRange(NamedRange $namedRange): void { $this->addDefinedName($namedRange); } /** * Add a named formula. * If a named formula with this name already exists, then this will replace the existing value. */ public function addNamedFormula(NamedFormula $namedFormula): void { $this->addDefinedName($namedFormula); } /** * Add a defined name (either a named range or a named formula). * If a defined named with this name already exists, then this will replace the existing value. */ public function addDefinedName(DefinedName $definedName): void { $upperCaseName = StringHelper::strToUpper($definedName->getName()); if ($definedName->getScope() == null) { // global scope $this->definedNames[$upperCaseName] = $definedName; } else { // local scope $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName; } } /** * Get named range. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange { $returnValue = null; if ($namedRange !== '') { $namedRange = StringHelper::strToUpper($namedRange); // first look for global named range $returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE); // then look for local named range (has priority over global named range if both names exist) $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue; } return $returnValue instanceof NamedRange ? $returnValue : null; } /** * Get named formula. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula { $returnValue = null; if ($namedFormula !== '') { $namedFormula = StringHelper::strToUpper($namedFormula); // first look for global named formula $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA); // then look for local named formula (has priority over global named formula if both names exist) $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue; } return $returnValue instanceof NamedFormula ? $returnValue : null; } private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName { if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) { return $this->definedNames[$name]; } return null; } private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName { if ( ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name]) && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type ) { return $this->definedNames[$worksheet->getTitle() . '!' . $name]; } return null; } /** * Get named range. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName { $returnValue = null; if ($definedName !== '') { $definedName = StringHelper::strToUpper($definedName); // first look for global defined name foreach ($this->definedNames as $dn) { $upper = StringHelper::strToUpper($dn->getName()); if ( !$dn->getLocalOnly() && $definedName === $upper ) { $returnValue = $dn; break; } } // then look for local defined name (has priority over global defined name if both names exist) if ($worksheet !== null) { $wsTitle = StringHelper::strToUpper($worksheet->getTitle()); $definedName = Preg::replace('/^.*!/', '', $definedName); foreach ($this->definedNames as $dn) { $sheet = $dn->getScope() ?? $dn->getWorksheet(); $upper = StringHelper::strToUpper($dn->getName()); $upperTitle = StringHelper::strToUpper((string) $sheet?->getTitle()); if ( $dn->getLocalOnly() && $upper === $definedName && $upperTitle === $wsTitle ) { return $dn; } } } } return $returnValue; } /** * Remove named range. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self { if ($this->getNamedRange($namedRange, $worksheet) === null) { return $this; } return $this->removeDefinedName($namedRange, $worksheet); } /** * Remove named formula. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self { if ($this->getNamedFormula($namedFormula, $worksheet) === null) { return $this; } return $this->removeDefinedName($namedFormula, $worksheet); } /** * Remove defined name. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self { $definedName = StringHelper::strToUpper($definedName); if ($worksheet === null) { if (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } } else { if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]); } elseif (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } } return $this; } /** * Get worksheet iterator. */ public function getWorksheetIterator(): Iterator { return new Iterator($this); } /** * Copy workbook (!= clone!). */ public function copy(): self { return unserialize(serialize($this)); //* @phpstan-ignore-line } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->uniqueID = uniqid('', true); $usedKeys = []; // I don't know why new Style rather than clone. $this->cellXfSupervisor = new Style(true); //$this->cellXfSupervisor = clone $this->cellXfSupervisor; $this->cellXfSupervisor->bindParent($this); $usedKeys['cellXfSupervisor'] = true; $oldCalc = $this->calculationEngine; $this->calculationEngine = new Calculation($this); $this->calculationEngine ->setSuppressFormulaErrors( $oldCalc->getSuppressFormulaErrors() ) ->setCalculationCacheEnabled( $oldCalc->getCalculationCacheEnabled() ) ->setBranchPruningEnabled( $oldCalc->getBranchPruningEnabled() ) ->setInstanceArrayReturnType( $oldCalc->getInstanceArrayReturnType() ); $usedKeys['calculationEngine'] = true; $currentCollection = $this->cellStyleXfCollection; $this->cellStyleXfCollection = []; foreach ($currentCollection as $item) { $clone = $item->exportArray(); $style = (new Style())->applyFromArray($clone); $this->addCellStyleXf($style); } $usedKeys['cellStyleXfCollection'] = true; $currentCollection = $this->cellXfCollection; $this->cellXfCollection = []; foreach ($currentCollection as $item) { $clone = $item->exportArray(); $style = (new Style())->applyFromArray($clone); $this->addCellXf($style); } $usedKeys['cellXfCollection'] = true; $currentCollection = $this->workSheetCollection; $this->workSheetCollection = []; foreach ($currentCollection as $item) { $clone = clone $item; $clone->setParent($this); $this->workSheetCollection[] = $clone; } $usedKeys['workSheetCollection'] = true; foreach (get_object_vars($this) as $key => $val) { if (isset($usedKeys[$key])) { continue; } switch ($key) { // arrays of objects not covered above case 'definedNames': /** @var DefinedName[] */ $currentCollection = $val; $this->$key = []; foreach ($currentCollection as $item) { $clone = clone $item; $title = $clone->getWorksheet()?->getTitle(); if ($title !== null) { $ws = $this->getSheetByName($title); $clone->setWorksheet($ws); } $title = $clone->getScope()?->getTitle(); if ($title !== null) { $ws = $this->getSheetByName($title); $clone->setScope($ws); } $this->{$key}[] = $clone; } break; default: if (is_object($val)) { $this->$key = clone $val; } } } } /** * Get the workbook collection of cellXfs. * * @return Style[] */ public function getCellXfCollection(): array { return $this->cellXfCollection; } /** * Get cellXf by index. */ public function getCellXfByIndex(int $cellStyleIndex): Style { return $this->cellXfCollection[$cellStyleIndex]; } public function getCellXfByIndexOrNull(?int $cellStyleIndex): ?Style { return ($cellStyleIndex === null) ? null : ($this->cellXfCollection[$cellStyleIndex] ?? null); } /** * Get cellXf by hash code. * * @return false|Style */ public function getCellXfByHashCode(string $hashcode): bool|Style { foreach ($this->cellXfCollection as $cellXf) { if ($cellXf->getHashCode() === $hashcode) { return $cellXf; } } return false; } /** * Check if style exists in style collection. */ public function cellXfExists(Style $cellStyleIndex): bool { return in_array($cellStyleIndex, $this->cellXfCollection, true); } /** * Get default style. */ public function getDefaultStyle(): Style { if (isset($this->cellXfCollection[0])) { return $this->cellXfCollection[0]; } throw new Exception('No default style found for this workbook'); } /** * Add a cellXf to the workbook. */ public function addCellXf(Style $style): void { $this->cellXfCollection[] = $style; $style->setIndex(count($this->cellXfCollection) - 1); } /** * Remove cellXf by index. It is ensured that all cells get their xf index updated. * * @param int $cellStyleIndex Index to cellXf */ public function removeCellXfByIndex(int $cellStyleIndex): void { if ($cellStyleIndex > count($this->cellXfCollection) - 1) { throw new Exception('CellXf index is out of bounds.'); } // first remove the cellXf array_splice($this->cellXfCollection, $cellStyleIndex, 1); // then update cellXf indexes for cells foreach ($this->workSheetCollection as $worksheet) { foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); $xfIndex = $cell->getXfIndex(); if ($xfIndex > $cellStyleIndex) { // decrease xf index by 1 $cell->setXfIndex($xfIndex - 1); } elseif ($xfIndex == $cellStyleIndex) { // set to default xf index 0 $cell->setXfIndex(0); } } } } /** * Get the cellXf supervisor. */ public function getCellXfSupervisor(): Style { return $this->cellXfSupervisor; } /** * Get the workbook collection of cellStyleXfs. * * @return Style[] */ public function getCellStyleXfCollection(): array { return $this->cellStyleXfCollection; } /** * Get cellStyleXf by index. * * @param int $cellStyleIndex Index to cellXf */ public function getCellStyleXfByIndex(int $cellStyleIndex): Style { return $this->cellStyleXfCollection[$cellStyleIndex]; } /** * Get cellStyleXf by hash code. * * @return false|Style */ public function getCellStyleXfByHashCode(string $hashcode): bool|Style { foreach ($this->cellStyleXfCollection as $cellStyleXf) { if ($cellStyleXf->getHashCode() === $hashcode) { return $cellStyleXf; } } return false; } /** * Add a cellStyleXf to the workbook. */ public function addCellStyleXf(Style $style): void { $this->cellStyleXfCollection[] = $style; $style->setIndex(count($this->cellStyleXfCollection) - 1); } /** * Remove cellStyleXf by index. * * @param int $cellStyleIndex Index to cellXf */ public function removeCellStyleXfByIndex(int $cellStyleIndex): void { if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) { throw new Exception('CellStyleXf index is out of bounds.'); } array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1); } /** * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells * and columns in the workbook. */ public function garbageCollect(): void { // how many references are there to each cellXf ? $countReferencesCellXf = []; foreach ($this->cellXfCollection as $index => $cellXf) { $countReferencesCellXf[$index] = 0; } foreach ($this->getWorksheetIterator() as $sheet) { // from cells foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); ++$countReferencesCellXf[$cell->getXfIndex()]; } // from row dimensions foreach ($sheet->getRowDimensions() as $rowDimension) { if ($rowDimension->getXfIndex() !== null) { ++$countReferencesCellXf[$rowDimension->getXfIndex()]; } } // from column dimensions foreach ($sheet->getColumnDimensions() as $columnDimension) { ++$countReferencesCellXf[$columnDimension->getXfIndex()]; } } // remove cellXfs without references and create mapping so we can update xfIndex // for all cells and columns $countNeededCellXfs = 0; $map = []; foreach ($this->cellXfCollection as $index => $cellXf) { if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf ++$countNeededCellXfs; } else { unset($this->cellXfCollection[$index]); } $map[$index] = $countNeededCellXfs - 1; } $this->cellXfCollection = array_values($this->cellXfCollection); // update the index for all cellXfs foreach ($this->cellXfCollection as $i => $cellXf) { $cellXf->setIndex($i); } // make sure there is always at least one cellXf (there should be) if (empty($this->cellXfCollection)) { $this->cellXfCollection[] = new Style(); } // update the xfIndex for all cells, row dimensions, column dimensions foreach ($this->getWorksheetIterator() as $sheet) { // for all cells foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); $cell->setXfIndex($map[$cell->getXfIndex()]); } // for all row dimensions foreach ($sheet->getRowDimensions() as $rowDimension) { if ($rowDimension->getXfIndex() !== null) { $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]); } } // for all column dimensions foreach ($sheet->getColumnDimensions() as $columnDimension) { $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]); } // also do garbage collection for all the sheets $sheet->garbageCollect(); } } /** * Return the unique ID value assigned to this spreadsheet workbook. * * @deprecated 5.2.0 Serves no useful purpose. No replacement. * * @codeCoverageIgnore */ public function getID(): string { return $this->uniqueID; } /** * Get the visibility of the horizonal scroll bar in the application. * * @return bool True if horizonal scroll bar is visible */ public function getShowHorizontalScroll(): bool { return $this->showHorizontalScroll; } /** * Set the visibility of the horizonal scroll bar in the application. * * @param bool $showHorizontalScroll True if horizonal scroll bar is visible */ public function setShowHorizontalScroll(bool $showHorizontalScroll): void { $this->showHorizontalScroll = (bool) $showHorizontalScroll; } /** * Get the visibility of the vertical scroll bar in the application. * * @return bool True if vertical scroll bar is visible */ public function getShowVerticalScroll(): bool { return $this->showVerticalScroll; } /** * Set the visibility of the vertical scroll bar in the application. * * @param bool $showVerticalScroll True if vertical scroll bar is visible */ public function setShowVerticalScroll(bool $showVerticalScroll): void { $this->showVerticalScroll = (bool) $showVerticalScroll; } /** * Get the visibility of the sheet tabs in the application. * * @return bool True if the sheet tabs are visible */ public function getShowSheetTabs(): bool { return $this->showSheetTabs; } /** * Set the visibility of the sheet tabs in the application. * * @param bool $showSheetTabs True if sheet tabs are visible */ public function setShowSheetTabs(bool $showSheetTabs): void { $this->showSheetTabs = (bool) $showSheetTabs; } /** * Return whether the workbook window is minimized. * * @return bool true if workbook window is minimized */ public function getMinimized(): bool { return $this->minimized; } /** * Set whether the workbook window is minimized. * * @param bool $minimized true if workbook window is minimized */ public function setMinimized(bool $minimized): void { $this->minimized = (bool) $minimized; } /** * Return whether to group dates when presenting the user with * filtering options in the user interface. * * @return bool true if workbook window is minimized */ public function getAutoFilterDateGrouping(): bool { return $this->autoFilterDateGrouping; } /** * Set whether to group dates when presenting the user with * filtering options in the user interface. * * @param bool $autoFilterDateGrouping true if workbook window is minimized */ public function setAutoFilterDateGrouping(bool $autoFilterDateGrouping): void { $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping; } /** * Return the first sheet in the book view. * * @return int First sheet in book view */ public function getFirstSheetIndex(): int { return $this->firstSheetIndex; } /** * Set the first sheet in the book view. * * @param int $firstSheetIndex First sheet in book view */ public function setFirstSheetIndex(int $firstSheetIndex): void { if ($firstSheetIndex >= 0) { $this->firstSheetIndex = (int) $firstSheetIndex; } else { throw new Exception('First sheet index must be a positive integer.'); } } /** * Return the visibility status of the workbook. * * This may be one of the following three values: * - visibile * * @return string Visible status */ public function getVisibility(): string { return $this->visibility; } /** * Set the visibility status of the workbook. * * Valid values are: * - 'visible' (self::VISIBILITY_VISIBLE): * Workbook window is visible * - 'hidden' (self::VISIBILITY_HIDDEN): * Workbook window is hidden, but can be shown by the user * via the user interface * - 'veryHidden' (self::VISIBILITY_VERY_HIDDEN): * Workbook window is hidden and cannot be shown in the * user interface. * * @param null|string $visibility visibility status of the workbook */ public function setVisibility(?string $visibility): void { if ($visibility === null) { $visibility = self::VISIBILITY_VISIBLE; } if (in_array($visibility, self::WORKBOOK_VIEW_VISIBILITY_VALUES)) { $this->visibility = $visibility; } else { throw new Exception('Invalid visibility value.'); } } /** * Get the ratio between the workbook tabs bar and the horizontal scroll bar. * TabRatio is assumed to be out of 1000 of the horizontal window width. * * @return int Ratio between the workbook tabs bar and the horizontal scroll bar */ public function getTabRatio(): int { return $this->tabRatio; } /** * Set the ratio between the workbook tabs bar and the horizontal scroll bar * TabRatio is assumed to be out of 1000 of the horizontal window width. * * @param int $tabRatio Ratio between the tabs bar and the horizontal scroll bar */ public function setTabRatio(int $tabRatio): void { if ($tabRatio >= 0 && $tabRatio <= 1000) { $this->tabRatio = (int) $tabRatio; } else { throw new Exception('Tab ratio must be between 0 and 1000.'); } } public function reevaluateAutoFilters(bool $resetToMax): void { foreach ($this->workSheetCollection as $sheet) { $filter = $sheet->getAutoFilter(); if (!empty($filter->getRange())) { if ($resetToMax) { $filter->setRangeToMaxRow(); } $filter->showHideRows(); } } } /** * @throws Exception */ public function jsonSerialize(): mixed { throw new Exception('Spreadsheet objects cannot be json encoded'); } public function resetThemeFonts(): void { $majorFontLatin = $this->theme->getMajorFontLatin(); $minorFontLatin = $this->theme->getMinorFontLatin(); foreach ($this->cellXfCollection as $cellStyleXf) { $scheme = $cellStyleXf->getFont()->getScheme(); if ($scheme === 'major') { $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme); } elseif ($scheme === 'minor') { $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme); } } foreach ($this->cellStyleXfCollection as $cellStyleXf) { $scheme = $cellStyleXf->getFont()->getScheme(); if ($scheme === 'major') { $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme); } elseif ($scheme === 'minor') { $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme); } } } public function getTableByName(string $tableName): ?Table { $table = null; foreach ($this->workSheetCollection as $sheet) { $table = $sheet->getTableByName($tableName); if ($table !== null) { break; } } return $table; } /** * @return bool Success or failure */ public function setExcelCalendar(int $baseYear): bool { if (($baseYear === Date::CALENDAR_WINDOWS_1900) || ($baseYear === Date::CALENDAR_MAC_1904)) { $this->excelCalendar = $baseYear; return true; } return false; } /** * @return int Excel base date (1900 or 1904) */ public function getExcelCalendar(): int { return $this->excelCalendar; } public function deleteLegacyDrawing(Worksheet $worksheet): void { unset($this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing']); } public function getLegacyDrawing(Worksheet $worksheet): ?string { /** @var ?string */ $temp = $this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'] ?? null; return $temp; } public function getValueBinder(): ?IValueBinder { return $this->valueBinder; } public function setValueBinder(?IValueBinder $valueBinder): self { $this->valueBinder = $valueBinder; return $this; } /** * All the PDF writers treat charts as if they occupy a single cell. * This will be better most of the time. * It is not needed for any other output type. * It changes the contents of the spreadsheet, so you might * be better off cloning the spreadsheet and then using * this method on, and then writing, the clone. */ public function mergeChartCellsForPdf(): void { foreach ($this->workSheetCollection as $worksheet) { foreach ($worksheet->getChartCollection() as $chart) { $br = $chart->getBottomRightCell(); $tl = $chart->getTopLeftCell(); if ($br !== '' && $br !== $tl) { if (!$worksheet->cellExists($br)) { $worksheet->getCell($br)->setValue(' '); } $worksheet->mergeCells("$tl:$br"); } } } } /** * All the PDF writers do better with drawings than charts. * This will be better some of the time. * It is not needed for any other output type. * It changes the contents of the spreadsheet, so you might * be better off cloning the spreadsheet and then using * this method on, and then writing, the clone. */ public function mergeDrawingCellsForPdf(): void { foreach ($this->workSheetCollection as $worksheet) { foreach ($worksheet->getDrawingCollection() as $drawing) { $br = $drawing->getCoordinates2(); $tl = $drawing->getCoordinates(); if ($br !== '' && $br !== $tl) { if (!$worksheet->cellExists($br)) { $worksheet->getCell($br)->setValue(' '); } $worksheet->mergeCells("$tl:$br"); } } } } /** * Excel will sometimes replace user's formatting choice * with a built-in choice that it thinks is equivalent. * Its choice is often not equivalent after all. * Such treatment is astonishingly user-hostile. * This function will undo such changes. */ public function replaceBuiltinNumberFormat(int $builtinFormatIndex, string $formatCode): void { foreach ($this->cellXfCollection as $style) { $numberFormat = $style->getNumberFormat(); if ($numberFormat->getBuiltInFormatCode() === $builtinFormatIndex) { $numberFormat->setFormatCode($formatCode); } } } /** * Change all 2-digit-year date styles to use 4-digit year; * change all dd-mm-yyyy and mm-dd-yyyy styles to yyyy-mm-dd; * dd-mmm-yyyy is unambiguous and left unchanged. */ public function disambiguateDateStyles(): void { foreach ($this->cellXfCollection as $style) { $numberFormat = $style->getNumberFormat(); $oldFormat = (string) $numberFormat->getFormatCode(); $newFormat = Preg::replace('/\byy\b/i', 'yyyy', $oldFormat); $newFormat = Preg::replace( '~\bdd?(-|/|"-"|"/")' . 'mm?(-|/|"-"|"/")' . 'yyyy~', 'yyyy-mm-dd', $newFormat ); $newFormat = Preg::replace( '~\bmm?(-|/|"-"|"/")' . 'dd?(-|/|"-"|"/")' . 'yyyy~', 'yyyy-mm-dd', $newFormat ); if ($newFormat !== $oldFormat) { $numberFormat->setFormatCode($newFormat); } } } public function returnArrayAsArray(): void { $this->calculationEngine->setInstanceArrayReturnType( Calculation::RETURN_ARRAY_AS_ARRAY ); } public function returnArrayAsValue(): void { $this->calculationEngine->setInstanceArrayReturnType( Calculation::RETURN_ARRAY_AS_VALUE ); } /** @var string[] */ private $domainWhiteList = []; /** * Currently used only by WEBSERVICE function. * * @param string[] $domainWhiteList */ public function setDomainWhiteList(array $domainWhiteList): self { $this->domainWhiteList = $domainWhiteList; return $this; } /** @return string[] */ public function getDomainWhiteList(): array { return $this->domainWhiteList; } private bool $usesCheckBoxStyle = false; public function getUsesCheckBoxStyle(): bool { return $this->usesCheckBoxStyle; } public function setUsesCheckBoxStyle(): bool { $this->usesCheckBoxStyle = false; foreach ($this->getCellXfCollection() as $cellXf) { if ($cellXf->getCheckBox()) { $this->usesCheckBoxStyle = true; break; } } return $this->usesCheckBoxStyle; } } ================================================ FILE: src/PhpSpreadsheet/Style/Alignment.php ================================================ self::HORIZONTAL_LEFT, self::HORIZONTAL_RIGHT => self::HORIZONTAL_RIGHT, self::HORIZONTAL_CENTER => self::HORIZONTAL_CENTER, self::HORIZONTAL_CENTER_CONTINUOUS => self::HORIZONTAL_CENTER_CONTINUOUS, self::HORIZONTAL_JUSTIFY => self::HORIZONTAL_JUSTIFY, self::HORIZONTAL_FILL => self::HORIZONTAL_FILL, self::HORIZONTAL_DISTRIBUTED => self::HORIZONTAL_DISTRIBUTED, ]; // Mapping for horizontal alignment CSS const HORIZONTAL_ALIGNMENT_FOR_HTML = [ self::HORIZONTAL_LEFT => self::HORIZONTAL_LEFT, self::HORIZONTAL_RIGHT => self::HORIZONTAL_RIGHT, self::HORIZONTAL_CENTER => self::HORIZONTAL_CENTER, self::HORIZONTAL_CENTER_CONTINUOUS => self::HORIZONTAL_CENTER, self::HORIZONTAL_JUSTIFY => self::HORIZONTAL_JUSTIFY, //self::HORIZONTAL_FILL => self::HORIZONTAL_FILL, // no reasonable equivalent for fill self::HORIZONTAL_DISTRIBUTED => self::HORIZONTAL_JUSTIFY, ]; // Vertical alignment styles const VERTICAL_BOTTOM = 'bottom'; const VERTICAL_TOP = 'top'; const VERTICAL_CENTER = 'center'; const VERTICAL_JUSTIFY = 'justify'; const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only // Vertical alignment CSS private const VERTICAL_BASELINE = 'baseline'; private const VERTICAL_MIDDLE = 'middle'; private const VERTICAL_SUB = 'sub'; private const VERTICAL_SUPER = 'super'; private const VERTICAL_TEXT_BOTTOM = 'text-bottom'; private const VERTICAL_TEXT_TOP = 'text-top'; // Mapping for vertical alignment const VERTICAL_ALIGNMENT_FOR_XLSX = [ self::VERTICAL_BOTTOM => self::VERTICAL_BOTTOM, self::VERTICAL_TOP => self::VERTICAL_TOP, self::VERTICAL_CENTER => self::VERTICAL_CENTER, self::VERTICAL_JUSTIFY => self::VERTICAL_JUSTIFY, self::VERTICAL_DISTRIBUTED => self::VERTICAL_DISTRIBUTED, // css settings that aren't in sync with Excel self::VERTICAL_BASELINE => self::VERTICAL_BOTTOM, self::VERTICAL_MIDDLE => self::VERTICAL_CENTER, self::VERTICAL_SUB => self::VERTICAL_BOTTOM, self::VERTICAL_SUPER => self::VERTICAL_TOP, self::VERTICAL_TEXT_BOTTOM => self::VERTICAL_BOTTOM, self::VERTICAL_TEXT_TOP => self::VERTICAL_TOP, ]; // Mapping for vertical alignment for Html const VERTICAL_ALIGNMENT_FOR_HTML = [ self::VERTICAL_BOTTOM => self::VERTICAL_BOTTOM, self::VERTICAL_TOP => self::VERTICAL_TOP, self::VERTICAL_CENTER => self::VERTICAL_MIDDLE, self::VERTICAL_JUSTIFY => self::VERTICAL_MIDDLE, self::VERTICAL_DISTRIBUTED => self::VERTICAL_MIDDLE, // css settings that aren't in sync with Excel self::VERTICAL_BASELINE => self::VERTICAL_BASELINE, self::VERTICAL_MIDDLE => self::VERTICAL_MIDDLE, self::VERTICAL_SUB => self::VERTICAL_SUB, self::VERTICAL_SUPER => self::VERTICAL_SUPER, self::VERTICAL_TEXT_BOTTOM => self::VERTICAL_TEXT_BOTTOM, self::VERTICAL_TEXT_TOP => self::VERTICAL_TEXT_TOP, ]; // Read order const READORDER_CONTEXT = 0; const READORDER_LTR = 1; const READORDER_RTL = 2; // Special value for Text Rotation const TEXTROTATION_STACK_EXCEL = 255; const TEXTROTATION_STACK_PHPSPREADSHEET = -165; // 90 - 255 public const INDENT_UNITS_TO_PIXELS = 9; /** * Horizontal alignment. */ protected ?string $horizontal = self::HORIZONTAL_GENERAL; /** * Justify Last Line alignment. */ protected ?bool $justifyLastLine = null; /** * Vertical alignment. */ protected ?string $vertical = self::VERTICAL_BOTTOM; /** * Text rotation. */ protected ?int $textRotation = 0; /** * Wrap text. */ protected bool $wrapText = false; /** * Shrink to fit. */ protected bool $shrinkToFit = false; /** * Indent - only possible with horizontal alignment left and right. */ protected int $indent = 0; /** * Read order. */ protected int $readOrder = 0; /** * Create a new Alignment. * * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ public function __construct(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); if ($isConditional) { $this->horizontal = null; $this->vertical = null; $this->textRotation = null; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getAlignment(); } /** * Build style array from subcomponents. * * @param mixed[] $array * * @return array{alignment: mixed[]} */ public function getStyleArray(array $array): array { return ['alignment' => $array]; } /** * Apply styles from array. * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray( * [ * 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, * 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, * 'textRotation' => 0, * 'wrapText' => TRUE * ] * ); * * * @param mixed[] $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells()) ->applyFromArray($this->getStyleArray($styleArray)); } else { /** @var array{horizontal?: string, vertical?: string, justifyLastLine?: bool, textRotation?: int, wrapText?: bool, shrinkToFit?: bool, readOrder?: int, indent?: int} $styleArray */ if (isset($styleArray['horizontal'])) { $this->setHorizontal($styleArray['horizontal']); } if (isset($styleArray['justifyLastLine'])) { $this->setJustifyLastLine($styleArray['justifyLastLine']); } if (isset($styleArray['vertical'])) { $this->setVertical($styleArray['vertical']); } if (isset($styleArray['textRotation'])) { $this->setTextRotation($styleArray['textRotation']); } if (isset($styleArray['wrapText'])) { $this->setWrapText($styleArray['wrapText']); } if (isset($styleArray['shrinkToFit'])) { $this->setShrinkToFit($styleArray['shrinkToFit']); } if (isset($styleArray['indent'])) { $this->setIndent($styleArray['indent']); } if (isset($styleArray['readOrder'])) { $this->setReadOrder($styleArray['readOrder']); } } return $this; } /** * Get Horizontal. */ public function getHorizontal(): null|string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHorizontal(); } return $this->horizontal; } /** * Set Horizontal. * * @param string $horizontalAlignment see self::HORIZONTAL_* * * @return $this */ public function setHorizontal(string $horizontalAlignment): static { $horizontalAlignment = strtolower($horizontalAlignment); if ($horizontalAlignment === self::HORIZONTAL_CENTER_CONTINUOUS_LC) { $horizontalAlignment = self::HORIZONTAL_CENTER_CONTINUOUS; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->horizontal = $horizontalAlignment; } return $this; } /** * Get Justify Last Line. */ public function getJustifyLastLine(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getJustifyLastLine(); } return $this->justifyLastLine; } /** * Set Justify Last Line. * * @return $this */ public function setJustifyLastLine(bool $justifyLastLine): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['justifyLastLine' => $justifyLastLine]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->justifyLastLine = $justifyLastLine; } return $this; } /** * Get Vertical. */ public function getVertical(): null|string { if ($this->isSupervisor) { return $this->getSharedComponent()->getVertical(); } return $this->vertical; } /** * Set Vertical. * * @param string $verticalAlignment see self::VERTICAL_* * * @return $this */ public function setVertical(string $verticalAlignment): static { $verticalAlignment = strtolower($verticalAlignment); if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->vertical = $verticalAlignment; } return $this; } /** * Get TextRotation. */ public function getTextRotation(): null|int { if ($this->isSupervisor) { return $this->getSharedComponent()->getTextRotation(); } return $this->textRotation; } /** * Set TextRotation. * * @return $this */ public function setTextRotation(int $angleInDegrees): static { // Excel2007 value 255 => PhpSpreadsheet value -165 if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) { $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET; } // Set rotation if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->textRotation = $angleInDegrees; } } else { throw new PhpSpreadsheetException("Text rotation $angleInDegrees should be a value between -90 and 90."); } return $this; } /** * Get Wrap Text. */ public function getWrapText(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getWrapText(); } return $this->wrapText; } /** * Set Wrap Text. * * @return $this */ public function setWrapText(bool $wrapped): static { if ($wrapped == '') { $wrapped = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['wrapText' => $wrapped]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->wrapText = $wrapped; } return $this; } /** * Get Shrink to fit. */ public function getShrinkToFit(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getShrinkToFit(); } return $this->shrinkToFit; } /** * Set Shrink to fit. * * @return $this */ public function setShrinkToFit(bool $shrink): static { if ($shrink == '') { $shrink = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->shrinkToFit = $shrink; } return $this; } /** * Get indent. */ public function getIndent(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getIndent(); } return $this->indent; } /** * Set indent. * * @return $this */ public function setIndent(int $indent): static { if ($indent > 0) { if ( $this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_LEFT && $this->getHorizontal() != self::HORIZONTAL_RIGHT && $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED ) { $indent = 0; // indent not supported } } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['indent' => $indent]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->indent = $indent; } return $this; } /** * Get read order. */ public function getReadOrder(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getReadOrder(); } return $this->readOrder; } /** * Set read order. * * @return $this */ public function setReadOrder(int $readOrder): static { if ($readOrder < 0 || $readOrder > 2) { $readOrder = 0; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['readOrder' => $readOrder]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->readOrder = $readOrder; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->horizontal . (($this->justifyLastLine === null) ? 'null' : ($this->justifyLastLine ? 't' : 'f')) . $this->vertical . $this->textRotation . ($this->wrapText ? 't' : 'f') . ($this->shrinkToFit ? 't' : 'f') . $this->indent . $this->readOrder . __CLASS__ ); } /** @return mixed[] */ protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'horizontal', $this->getHorizontal()); $this->exportArray2($exportedArray, 'justifyLastLine', $this->getJustifyLastLine()); $this->exportArray2($exportedArray, 'indent', $this->getIndent()); $this->exportArray2($exportedArray, 'readOrder', $this->getReadOrder()); $this->exportArray2($exportedArray, 'shrinkToFit', $this->getShrinkToFit()); $this->exportArray2($exportedArray, 'textRotation', $this->getTextRotation()); $this->exportArray2($exportedArray, 'vertical', $this->getVertical()); $this->exportArray2($exportedArray, 'wrapText', $this->getWrapText()); return $exportedArray; } } ================================================ FILE: src/PhpSpreadsheet/Style/Border.php ================================================ color = new Color(Color::COLOR_BLACK, $isSupervisor); // bind parent if we are a supervisor if ($isSupervisor) { $this->color->bindParent($this, 'color'); } if ($isConditional) { $this->borderStyle = self::BORDER_OMIT; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; /** @var Borders $sharedComponent */ $sharedComponent = $parent->getSharedComponent(); return match ($this->parentPropertyName) { 'bottom' => $sharedComponent->getBottom(), 'diagonal' => $sharedComponent->getDiagonal(), 'left' => $sharedComponent->getLeft(), 'right' => $sharedComponent->getRight(), 'top' => $sharedComponent->getTop(), default => throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'), }; } /** * Build style array from subcomponents. * * @param mixed[] $array * * @return mixed[] */ public function getStyleArray(array $array): array { /** @var Style $parent */ $parent = $this->parent; return $parent->getStyleArray([$this->parentPropertyName => $array]); } /** * Apply styles from array. * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray( * [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ); * * * @param mixed[] $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { /** @var array{borderStyle?: string, color?: array{rgb?: string, argb?: string}} $styleArray */ if (isset($styleArray['borderStyle'])) { $this->setBorderStyle($styleArray['borderStyle']); } if (isset($styleArray['color'])) { $this->getColor() ->applyFromArray($styleArray['color']); } } return $this; } /** * Get Border style. */ public function getBorderStyle(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getBorderStyle(); } return $this->borderStyle; } /** * Set Border style. * * @param bool|string $style When passing a boolean, FALSE equates Border::BORDER_NONE * and TRUE to Border::BORDER_MEDIUM * * @return $this */ public function setBorderStyle(bool|string $style): static { if (empty($style)) { $style = self::BORDER_NONE; } elseif (is_bool($style)) { $style = self::BORDER_MEDIUM; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['borderStyle' => $style]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->borderStyle = $style; } return $this; } /** * Get Border Color. */ public function getColor(): Color { return $this->color; } /** * Set Border Color. * * @return $this */ public function setColor(Color $color): static { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->borderStyle . $this->color->getHashCode() . __CLASS__ ); } /** @return mixed[] */ protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'borderStyle', $this->getBorderStyle()); $this->exportArray2($exportedArray, 'color', $this->getColor()); return $exportedArray; } } ================================================ FILE: src/PhpSpreadsheet/Style/Borders.php ================================================ left = new Border($isSupervisor, $isConditional); $this->right = new Border($isSupervisor, $isConditional); $this->top = new Border($isSupervisor, $isConditional); $this->bottom = new Border($isSupervisor, $isConditional); $this->diagonal = new Border($isSupervisor, $isConditional); $this->diagonalDirection = self::DIAGONAL_NONE; // Specially for supervisor if ($isSupervisor) { // Initialize pseudo-borders $this->allBorders = new Border(true, $isConditional); $this->outline = new Border(true, $isConditional); $this->inside = new Border(true, $isConditional); $this->vertical = new Border(true, $isConditional); $this->horizontal = new Border(true, $isConditional); // bind parent if we are a supervisor $this->left->bindParent($this, 'left'); $this->right->bindParent($this, 'right'); $this->top->bindParent($this, 'top'); $this->bottom->bindParent($this, 'bottom'); $this->diagonal->bindParent($this, 'diagonal'); $this->allBorders->bindParent($this, 'allBorders'); $this->outline->bindParent($this, 'outline'); $this->inside->bindParent($this, 'inside'); $this->vertical->bindParent($this, 'vertical'); $this->horizontal->bindParent($this, 'horizontal'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getBorders(); } /** * Build style array from subcomponents. * * @param mixed[] $array * * @return array{borders: mixed[]} */ public function getStyleArray(array $array): array { return ['borders' => $array]; } /** * Apply styles from array. * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * [ * 'bottom' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'top' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ] * ); * * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * [ * 'allBorders' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ] * ); * * * @param mixed[] $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { /** @var array{left?: float[], right?: float[], top?: float[], bottom?: float[], diagonal?: mixed[], diagonalDirection?: int, allBorders?: mixed[][]} $styleArray */ if (isset($styleArray['left'])) { $this->getLeft()->applyFromArray($styleArray['left']); } if (isset($styleArray['right'])) { $this->getRight()->applyFromArray($styleArray['right']); } if (isset($styleArray['top'])) { $this->getTop()->applyFromArray($styleArray['top']); } if (isset($styleArray['bottom'])) { $this->getBottom()->applyFromArray($styleArray['bottom']); } if (isset($styleArray['diagonal'])) { $this->getDiagonal()->applyFromArray($styleArray['diagonal']); } if (isset($styleArray['diagonalDirection'])) { $this->setDiagonalDirection($styleArray['diagonalDirection']); } if (isset($styleArray['allBorders'])) { $this->getLeft()->applyFromArray($styleArray['allBorders']); $this->getRight()->applyFromArray($styleArray['allBorders']); $this->getTop()->applyFromArray($styleArray['allBorders']); $this->getBottom()->applyFromArray($styleArray['allBorders']); } } return $this; } /** * Get Left. */ public function getLeft(): Border { return $this->left; } /** * Get Right. */ public function getRight(): Border { return $this->right; } /** * Get Top. */ public function getTop(): Border { return $this->top; } /** * Get Bottom. */ public function getBottom(): Border { return $this->bottom; } /** * Get Diagonal. */ public function getDiagonal(): Border { return $this->diagonal; } /** * Get AllBorders (pseudo-border). Only applies to supervisor. */ public function getAllBorders(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->allBorders; } /** * Get Outline (pseudo-border). Only applies to supervisor. */ public function getOutline(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->outline; } /** * Get Inside (pseudo-border). Only applies to supervisor. */ public function getInside(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->inside; } /** * Get Vertical (pseudo-border). Only applies to supervisor. */ public function getVertical(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->vertical; } /** * Get Horizontal (pseudo-border). Only applies to supervisor. */ public function getHorizontal(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->horizontal; } /** * Get DiagonalDirection. */ public function getDiagonalDirection(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getDiagonalDirection(); } return $this->diagonalDirection; } /** * Set DiagonalDirection. * * @param int $direction see self::DIAGONAL_* * * @return $this */ public function setDiagonalDirection(int $direction): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->diagonalDirection = $direction; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashcode(); } return md5( $this->getLeft()->getHashCode() . $this->getRight()->getHashCode() . $this->getTop()->getHashCode() . $this->getBottom()->getHashCode() . $this->getDiagonal()->getHashCode() . $this->getDiagonalDirection() . __CLASS__ ); } /** @return mixed[][] */ protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'bottom', $this->getBottom()); $this->exportArray2($exportedArray, 'diagonal', $this->getDiagonal()); $this->exportArray2($exportedArray, 'diagonalDirection', $this->getDiagonalDirection()); $this->exportArray2($exportedArray, 'left', $this->getLeft()); $this->exportArray2($exportedArray, 'right', $this->getRight()); $this->exportArray2($exportedArray, 'top', $this->getTop()); /** @var mixed[][] $exportedArray */ return $exportedArray; } } ================================================ FILE: src/PhpSpreadsheet/Style/Color.php ================================================ self::COLOR_BLACK, 'White' => self::COLOR_WHITE, 'Red' => self::COLOR_RED, 'Green' => self::COLOR_GREEN, 'Blue' => self::COLOR_BLUE, 'Yellow' => self::COLOR_YELLOW, 'Magenta' => self::COLOR_MAGENTA, 'Cyan' => self::COLOR_CYAN, ]; const VALIDATE_ARGB_SIZE = 8; const VALIDATE_RGB_SIZE = 6; const VALIDATE_COLOR_6 = '/^[A-F0-9]{6}$/i'; const VALIDATE_COLOR_8 = '/^[A-F0-9]{8}$/i'; private const INDEXED_COLORS = [ 1 => 'FF000000', // System Colour #1 - Black 2 => 'FFFFFFFF', // System Colour #2 - White 3 => 'FFFF0000', // System Colour #3 - Red 4 => 'FF00FF00', // System Colour #4 - Green 5 => 'FF0000FF', // System Colour #5 - Blue 6 => 'FFFFFF00', // System Colour #6 - Yellow 7 => 'FFFF00FF', // System Colour #7- Magenta 8 => 'FF00FFFF', // System Colour #8- Cyan 9 => 'FF800000', // Standard Colour #9 10 => 'FF008000', // Standard Colour #10 11 => 'FF000080', // Standard Colour #11 12 => 'FF808000', // Standard Colour #12 13 => 'FF800080', // Standard Colour #13 14 => 'FF008080', // Standard Colour #14 15 => 'FFC0C0C0', // Standard Colour #15 16 => 'FF808080', // Standard Colour #16 17 => 'FF9999FF', // Chart Fill Colour #17 18 => 'FF993366', // Chart Fill Colour #18 19 => 'FFFFFFCC', // Chart Fill Colour #19 20 => 'FFCCFFFF', // Chart Fill Colour #20 21 => 'FF660066', // Chart Fill Colour #21 22 => 'FFFF8080', // Chart Fill Colour #22 23 => 'FF0066CC', // Chart Fill Colour #23 24 => 'FFCCCCFF', // Chart Fill Colour #24 25 => 'FF000080', // Chart Line Colour #25 26 => 'FFFF00FF', // Chart Line Colour #26 27 => 'FFFFFF00', // Chart Line Colour #27 28 => 'FF00FFFF', // Chart Line Colour #28 29 => 'FF800080', // Chart Line Colour #29 30 => 'FF800000', // Chart Line Colour #30 31 => 'FF008080', // Chart Line Colour #31 32 => 'FF0000FF', // Chart Line Colour #32 33 => 'FF00CCFF', // Standard Colour #33 34 => 'FFCCFFFF', // Standard Colour #34 35 => 'FFCCFFCC', // Standard Colour #35 36 => 'FFFFFF99', // Standard Colour #36 37 => 'FF99CCFF', // Standard Colour #37 38 => 'FFFF99CC', // Standard Colour #38 39 => 'FFCC99FF', // Standard Colour #39 40 => 'FFFFCC99', // Standard Colour #40 41 => 'FF3366FF', // Standard Colour #41 42 => 'FF33CCCC', // Standard Colour #42 43 => 'FF99CC00', // Standard Colour #43 44 => 'FFFFCC00', // Standard Colour #44 45 => 'FFFF9900', // Standard Colour #45 46 => 'FFFF6600', // Standard Colour #46 47 => 'FF666699', // Standard Colour #47 48 => 'FF969696', // Standard Colour #48 49 => 'FF003366', // Standard Colour #49 50 => 'FF339966', // Standard Colour #50 51 => 'FF003300', // Standard Colour #51 52 => 'FF333300', // Standard Colour #52 53 => 'FF993300', // Standard Colour #53 54 => 'FF993366', // Standard Colour #54 55 => 'FF333399', // Standard Colour #55 56 => 'FF333333', // Standard Colour #56 ]; /** * ARGB - Alpha RGB. */ protected ?string $argb = null; private bool $hasChanged = false; private int $theme = -1; /** * Create a new Color. * * @param string $colorValue ARGB value for the colour, or named colour * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ public function __construct(string $colorValue = self::COLOR_BLACK, bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { $this->argb = $this->validateColor($colorValue) ?: self::COLOR_BLACK; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; /** @var Border|Fill $sharedComponent */ $sharedComponent = $parent->getSharedComponent(); if ($sharedComponent instanceof Fill) { if ($this->parentPropertyName === 'endColor') { return $sharedComponent->getEndColor(); } return $sharedComponent->getStartColor(); } return $sharedComponent->getColor(); } /** * Build style array from subcomponents. * * @param mixed[] $array * * @return mixed[] */ public function getStyleArray(array $array): array { /** @var Style $parent */ $parent = $this->parent; return $parent->getStyleArray([$this->parentPropertyName => $array]); } /** * Apply styles from array. * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']); * * * @param array{rgb?: string, argb?: string, theme?: int} $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet() ->getStyle($this->getSelectedCells()) ->applyFromArray( $this->getStyleArray($styleArray) ); } else { if (isset($styleArray['rgb'])) { $this->setRGB($styleArray['rgb']); } if (isset($styleArray['argb'])) { $this->setARGB($styleArray['argb']); } if (isset($styleArray['theme'])) { $this->setTheme($styleArray['theme']); } } return $this; } private function validateColor(?string $colorValue): string { if ($colorValue === null || $colorValue === '') { return self::COLOR_BLACK; } $named = ucfirst(strtolower($colorValue)); if (array_key_exists($named, self::NAMED_COLOR_TRANSLATIONS)) { return self::NAMED_COLOR_TRANSLATIONS[$named]; } if (preg_match(self::VALIDATE_COLOR_8, $colorValue) === 1) { return $colorValue; } if (preg_match(self::VALIDATE_COLOR_6, $colorValue) === 1) { return 'FF' . $colorValue; } return ''; } /** * Get ARGB. */ public function getARGB(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); } return $this->argb; } /** * Set ARGB. * * @param ?string $colorValue ARGB value, or a named color * * @return $this */ public function setARGB(?string $colorValue = self::COLOR_BLACK, bool $nullStringOkay = false): static { $this->hasChanged = true; $this->setTheme(-1); if (!$nullStringOkay || $colorValue !== '') { $colorValue = $this->validateColor($colorValue); if ($colorValue === '') { return $this; } } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['argb' => $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->argb = $colorValue; } return $this; } /** * Get RGB. */ public function getRGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); } return substr($this->argb ?? '', 2); } /** * Set RGB. * * @param ?string $colorValue RGB value, or a named color * * @return $this */ public function setRGB(?string $colorValue = self::COLOR_BLACK): static { return $this->setARGB($colorValue); } /** * Get a specified colour component of an RGB value. * * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param int $offset Position within the RGB value to extract * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * * @return int|string The extracted colour component */ private static function getColourComponent(string $rgbValue, int $offset, bool $hex = true): string|int { $colour = substr($rgbValue, $offset, 2) ?: ''; if (preg_match('/^[0-9a-f]{2}$/i', $colour) !== 1) { $colour = '00'; } return ($hex) ? $colour : (int) hexdec($colour); } /** * Get the red colour component of an RGB value. * * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * * @return int|string The red colour component */ public static function getRed(string $rgbValue, bool $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex); } /** * Get the green colour component of an RGB value. * * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * * @return int|string The green colour component */ public static function getGreen(string $rgbValue, bool $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex); } /** * Get the blue colour component of an RGB value. * * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * * @return int|string The blue colour component */ public static function getBlue(string $rgbValue, bool $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex); } /** * Adjust the brightness of a color. * * @param string $hexColourValue The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1 * * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) */ public static function changeBrightness(string $hexColourValue, float $adjustPercentage): string { $rgba = (strlen($hexColourValue) === 8); $adjustPercentage = max(-1.0, min(1.0, $adjustPercentage)); /** @var int $red */ $red = self::getRed($hexColourValue, false); /** @var int $green */ $green = self::getGreen($hexColourValue, false); /** @var int $blue */ $blue = self::getBlue($hexColourValue, false); return (($rgba) ? 'FF' : '') . RgbTint::rgbAndTintToRgb($red, $green, $blue, $adjustPercentage); } /** * Get indexed color. * * @param int $colorIndex Index entry point into the colour array * @param bool $background Flag to indicate whether default background or foreground colour * should be returned if the indexed colour doesn't exist * @param null|string[] $palette */ public static function indexedColor(int $colorIndex, bool $background = false, ?array $palette = null): self { // Clean parameter $colorIndex = (int) $colorIndex; if (empty($palette)) { if (isset(self::INDEXED_COLORS[$colorIndex])) { return new self(self::INDEXED_COLORS[$colorIndex]); } } else { if (isset($palette[$colorIndex])) { return new self($palette[$colorIndex]); } } return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK); } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->argb . (string) $this->theme . __CLASS__ ); } /** @return mixed[] */ protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'argb', $this->getARGB()); $this->exportArray2($exportedArray, 'theme', $this->getTheme()); return $exportedArray; } public function getHasChanged(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->hasChanged; } return $this->hasChanged; } public function getTheme(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getTheme(); } return $this->theme; } public function setTheme(int $theme): self { $this->hasChanged = true; if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['theme' => $theme]); $this->getActiveSheet() ->getStyle($this->getSelectedCells()) ->applyFromArray($styleArray); } else { $this->theme = $theme; } return $this; } public function setHyperlinkTheme(): self { $rgb = $this->getActiveSheet() ->getParent() ?->getTheme() ->getThemeColors(); if (is_array($rgb) && array_key_exists('hlink', $rgb)) { $this->setRGB($rgb['hlink']); } return $this->setTheme(Theme::HYPERLINK_THEME); } } ================================================ FILE: src/PhpSpreadsheet/Style/Conditional.php ================================================ style = new Style(false, true); } public function getPriority(): int { return $this->priority; } public function setPriority(int $priority): self { $this->priority = $priority; return $this; } public function getNoFormatSet(): bool { return $this->noFormatSet; } public function setNoFormatSet(bool $noFormatSet): self { $this->noFormatSet = $noFormatSet; return $this; } /** * Get Condition type. */ public function getConditionType(): string { return $this->conditionType; } /** * Set Condition type. * * @param string $type Condition type, see self::CONDITION_* * * @return $this */ public function setConditionType(string $type): static { $this->conditionType = $type; return $this; } /** * Get Operator type. */ public function getOperatorType(): string { return $this->operatorType; } /** * Set Operator type. * * @param string $type Conditional operator type, see self::OPERATOR_* * * @return $this */ public function setOperatorType(string $type): static { $this->operatorType = $type; return $this; } /** * Get text. */ public function getText(): string { return $this->text; } /** * Set text. * * @return $this */ public function setText(string $text): static { $this->text = $text; return $this; } /** * Get StopIfTrue. */ public function getStopIfTrue(): bool { return $this->stopIfTrue; } /** * Set StopIfTrue. * * @return $this */ public function setStopIfTrue(bool $stopIfTrue): static { $this->stopIfTrue = $stopIfTrue; return $this; } /** * Get Conditions. * * @return (bool|float|int|string)[] */ public function getConditions(): array { return $this->condition; } /** * Set Conditions. * * @param bool|(bool|float|int|string)[]|float|int|string $conditions Condition * * @return $this */ public function setConditions($conditions): static { if (!is_array($conditions)) { $conditions = [$conditions]; } $this->condition = $conditions; return $this; } /** * Add Condition. * * @param bool|float|int|string $condition Condition * * @return $this */ public function addCondition($condition): static { $this->condition[] = $condition; return $this; } /** * Get Style. */ public function getStyle(mixed $cellData = null): Style { if ($this->conditionType === self::CONDITION_COLORSCALE && $cellData !== null && $this->colorScale !== null && is_numeric($cellData)) { $style = new Style(isConditional: true); $style->getFill()->setFillType(Fill::FILL_SOLID); $style->getFill()->getStartColor()->setARGB($this->colorScale->getColorForValue((float) $cellData)); return $style; } return $this->style; } /** * Set Style. * * @return $this */ public function setStyle(Style $style): static { $this->style = $style; return $this; } public function getDataBar(): ?ConditionalDataBar { return $this->dataBar; } public function setDataBar(ConditionalDataBar $dataBar): static { $this->dataBar = $dataBar; return $this; } public function getColorScale(): ?ConditionalColorScale { return $this->colorScale; } public function setColorScale(ConditionalColorScale $colorScale): static { $this->colorScale = $colorScale; return $this; } public function getIconSet(): ?ConditionalIconSet { return $this->iconSet; } public function setIconSet(ConditionalIconSet $iconSet): static { $this->iconSet = $iconSet; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->conditionType . $this->operatorType . implode(';', $this->condition) . $this->style->getHashCode() . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** * Verify if param is valid condition type. */ public static function isValidConditionType(string $type): bool { return in_array($type, self::CONDITION_TYPES); } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php ================================================ '=', Conditional::OPERATOR_GREATERTHAN => '>', Conditional::OPERATOR_GREATERTHANOREQUAL => '>=', Conditional::OPERATOR_LESSTHAN => '<', Conditional::OPERATOR_LESSTHANOREQUAL => '<=', Conditional::OPERATOR_NOTEQUAL => '<>', ]; public const COMPARISON_RANGE_OPERATORS = [ Conditional::OPERATOR_BETWEEN => 'IF(AND(A1>=%s,A1<=%s),TRUE,FALSE)', Conditional::OPERATOR_NOTBETWEEN => 'IF(AND(A1>=%s,A1<=%s),FALSE,TRUE)', ]; public const COMPARISON_DUPLICATES_OPERATORS = [ Conditional::CONDITION_DUPLICATES => "COUNTIF('%s'!%s,%s)>1", Conditional::CONDITION_UNIQUE => "COUNTIF('%s'!%s,%s)=1", ]; protected Cell $cell; protected int $cellRow; protected Worksheet $worksheet; protected int $cellColumn; protected string $conditionalRange; protected string $referenceCell; protected int $referenceRow; protected int $referenceColumn; protected Calculation $engine; public function __construct(Cell $cell, string $conditionalRange) { $this->cell = $cell; $this->worksheet = $cell->getWorksheet(); [$this->cellColumn, $this->cellRow] = Coordinate::indexesFromString($this->cell->getCoordinate()); $this->setReferenceCellForExpressions($conditionalRange); $this->engine = Calculation::getInstance($this->worksheet->getParent()); } protected function setReferenceCellForExpressions(string $conditionalRange): void { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); [$this->referenceCell] = $conditionalRange[0]; [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); // Convert our conditional range to an absolute conditional range, so it can be used "pinned" in formulae $rangeSets = []; foreach ($conditionalRange as $rangeSet) { $absoluteRangeSet = array_map( [Coordinate::class, 'absoluteCoordinate'], $rangeSet ); $rangeSets[] = implode(':', $absoluteRangeSet); } $this->conditionalRange = implode(',', $rangeSets); } public function evaluateConditional(Conditional $conditional): bool { // Some calculations may modify the stored cell; so reset it before every evaluation. $cellColumn = Coordinate::stringFromColumnIndex($this->cellColumn); $cellAddress = "{$cellColumn}{$this->cellRow}"; $this->cell = $this->worksheet->getCell($cellAddress); return match ($conditional->getConditionType()) { Conditional::CONDITION_CELLIS => $this->processOperatorComparison($conditional), Conditional::CONDITION_DUPLICATES, Conditional::CONDITION_UNIQUE => $this->processDuplicatesComparison($conditional), // Expression is NOT(ISERROR(SEARCH("",))) Conditional::CONDITION_CONTAINSTEXT, // Expression is ISERROR(SEARCH("",)) Conditional::CONDITION_NOTCONTAINSTEXT, // Expression is LEFT(,LEN(""))="" Conditional::CONDITION_BEGINSWITH, // Expression is RIGHT(,LEN(""))="" Conditional::CONDITION_ENDSWITH, // Expression is LEN(TRIM())=0 Conditional::CONDITION_CONTAINSBLANKS, // Expression is LEN(TRIM())>0 Conditional::CONDITION_NOTCONTAINSBLANKS, // Expression is ISERROR() Conditional::CONDITION_CONTAINSERRORS, // Expression is NOT(ISERROR()) Conditional::CONDITION_NOTCONTAINSERRORS, // Expression varies, depending on specified timePeriod value, e.g. // Yesterday FLOOR(,1)=TODAY()-1 // Today FLOOR(,1)=TODAY() // Tomorrow FLOOR(,1)=TODAY()+1 // Last 7 Days AND(TODAY()-FLOOR(,1)<=6,FLOOR(,1)<=TODAY()) Conditional::CONDITION_TIMEPERIOD, Conditional::CONDITION_EXPRESSION => $this->processExpression($conditional), Conditional::CONDITION_COLORSCALE => $this->processColorScale($conditional), default => false, }; } protected function wrapValue(mixed $value): float|int|string { if (!is_numeric($value)) { if (is_bool($value)) { return $value ? 'TRUE' : 'FALSE'; } elseif ($value === null) { return 'NULL'; } return '"' . StringHelper::convertToString($value) . '"'; } return $value; } protected function wrapCellValue(): float|int|string { $this->cell = $this->worksheet->getCell([$this->cellColumn, $this->cellRow]); return $this->wrapValue($this->cell->getCalculatedValue()); } /** @param string[] $matches */ protected function conditionCellAdjustment(array $matches): float|int|string { $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { // $column = Coordinate::stringFromColumnIndex($this->cellColumn); $column = Coordinate::columnIndexFromString($column); $column += $this->cellColumn - $this->referenceColumn; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row = (int) $row + $this->cellRow - $this->referenceRow; } if (!empty($matches[4])) { $worksheet = $this->worksheet->getParentOrThrow()->getSheetByName(trim($matches[4], "'")); if ($worksheet === null) { return $this->wrapValue(null); } return $this->wrapValue( $worksheet ->getCell(str_replace('$', '', "{$column}{$row}")) ->getCalculatedValue() ); } return $this->wrapValue( $this->worksheet ->getCell(str_replace('$', '', "{$column}{$row}")) ->getCalculatedValue() ); } protected function cellConditionCheck(string $condition): string { $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', [$this, 'conditionCellAdjustment'], $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } /** * @param mixed[] $conditions * * @return mixed[] */ protected function adjustConditionsForCellReferences(array $conditions): array { return array_map( [$this, 'cellConditionCheck'], $conditions ); } protected function processOperatorComparison(Conditional $conditional): bool { if (array_key_exists($conditional->getOperatorType(), self::COMPARISON_RANGE_OPERATORS)) { return $this->processRangeOperator($conditional); } $operator = self::COMPARISON_OPERATORS[$conditional->getOperatorType()]; $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); /** @var float|int|string */ $temp1 = $this->wrapCellValue(); /** @var scalar */ $temp2 = array_pop($conditions); $expression = sprintf('%s%s%s', (string) $temp1, $operator, (string) $temp2); return $this->evaluateExpression($expression); } protected function processColorScale(Conditional $conditional): bool { if (is_numeric($this->wrapCellValue()) && $conditional->getColorScale()?->colorScaleReadyForUse()) { return true; } return false; } protected function processRangeOperator(Conditional $conditional): bool { $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); sort($conditions); $expression = sprintf( (string) preg_replace( '/\bA1\b/i', (string) $this->wrapCellValue(), self::COMPARISON_RANGE_OPERATORS[$conditional->getOperatorType()] ), ...$conditions //* @phpstan-ignore-line ); return $this->evaluateExpression($expression); } protected function processDuplicatesComparison(Conditional $conditional): bool { $worksheetName = $this->cell->getWorksheet()->getTitle(); $expression = sprintf( self::COMPARISON_DUPLICATES_OPERATORS[$conditional->getConditionType()], $worksheetName, $this->conditionalRange, $this->cellConditionCheck($this->cell->getCalculatedValueString()) ); return $this->evaluateExpression($expression); } protected function processExpression(Conditional $conditional): bool { $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); /** @var string */ $expression = array_pop($conditions); /** @var float|int|string */ $temp = $this->wrapCellValue(); $expression = (string) preg_replace( '/\b' . $this->referenceCell . '\b/i', (string) $temp, $expression ); return $this->evaluateExpression($expression); } protected function evaluateExpression(string $expression): bool { $expression = "={$expression}"; try { $this->engine->flushInstance(); $result = (bool) $this->engine->calculateFormula($expression); } catch (Exception) { return false; } return $result; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php ================================================ cell = $cell; $this->cellMatcher = new CellMatcher($cell, $conditionalRange); $this->styleMerger = new StyleMerger($cell->getStyle()); } /** * @param Conditional[] $conditionalStyles */ public function matchConditions(array $conditionalStyles = []): Style { foreach ($conditionalStyles as $conditional) { if ($this->cellMatcher->evaluateConditional($conditional) === true) { // Merging the conditional style into the base style goes in here $this->styleMerger->mergeStyle($conditional->getStyle($this->cell->getValue())); if ($conditional->getStopIfTrue() === true) { break; } } } return $this->styleMerger->getStyle(); } /** * @param Conditional[] $conditionalStyles */ public function matchConditionsReturnNullIfNoneMatched(array $conditionalStyles, string $cellData, bool $stopAtFirstMatch = false): ?Style { $matched = false; $value = (float) $cellData; foreach ($conditionalStyles as $conditional) { if ($this->cellMatcher->evaluateConditional($conditional) === true) { $matched = true; // Merging the conditional style into the base style goes in here $this->styleMerger->mergeStyle($conditional->getStyle($value)); if ($conditional->getStopIfTrue() === true || $stopAtFirstMatch) { break; } } } if ($matched) { return $this->styleMerger->getStyle(); } return null; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php ================================================ minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getMidpointConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->midpointConditionalFormatValueObject; } public function setMidpointConditionalFormatValueObject(ConditionalFormatValueObject $midpointConditionalFormatValueObject): self { $this->midpointConditionalFormatValueObject = $midpointConditionalFormatValueObject; return $this; } public function getMaximumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getMinimumColor(): ?Color { return $this->minimumColor; } public function setMinimumColor(Color $minimumColor): self { $this->minimumColor = $minimumColor; return $this; } public function getMidpointColor(): ?Color { return $this->midpointColor; } public function setMidpointColor(Color $midpointColor): self { $this->midpointColor = $midpointColor; return $this; } public function getMaximumColor(): ?Color { return $this->maximumColor; } public function setMaximumColor(Color $maximumColor): self { $this->maximumColor = $maximumColor; return $this; } public function getSqRef(): ?string { return $this->sqref; } public function setSqRef(string $sqref, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): self { $this->sqref = $sqref; $this->worksheet = $worksheet; return $this; } public function setScaleArray(): self { if ($this->sqref !== null && $this->worksheet !== null) { $values = $this->worksheet->rangesToArray($this->sqref, null, true, true, true); $this->valueArray = []; foreach ($values as $key => $value) { /** @var array $value */ foreach ($value as $k => $v) { $this->valueArray[] = (float) $v; } } $this->prepareColorScale(); } return $this; } public function getColorForValue(float $value): string { if ($this->minimumColor === null || $this->midpointColor === null || $this->maximumColor === null) { return 'FF000000'; } $minColor = $this->minimumColor->getARGB(); $midColor = $this->midpointColor->getARGB(); $maxColor = $this->maximumColor->getARGB(); if ($minColor === null || $midColor === null || $maxColor === null) { return 'FF000000'; } if ($value <= $this->minValue) { return $minColor; } if ($value >= $this->maxValue) { return $maxColor; } if ($value == $this->midValue) { return $midColor; } if ($value < $this->midValue) { $blend = ($value - $this->minValue) / ($this->midValue - $this->minValue); $alpha1 = hexdec(substr($minColor, 0, 2)); $alpha2 = hexdec(substr($midColor, 0, 2)); $red1 = hexdec(substr($minColor, 2, 2)); $red2 = hexdec(substr($midColor, 2, 2)); $green1 = hexdec(substr($minColor, 4, 2)); $green2 = hexdec(substr($midColor, 4, 2)); $blue1 = hexdec(substr($minColor, 6, 2)); $blue2 = hexdec(substr($midColor, 6, 2)); return strtoupper(dechex((int) ($alpha2 * $blend + $alpha1 * (1 - $blend))) . '' . dechex((int) ($red2 * $blend + $red1 * (1 - $blend))) . '' . dechex((int) ($green2 * $blend + $green1 * (1 - $blend))) . '' . dechex((int) ($blue2 * $blend + $blue1 * (1 - $blend)))); } $blend = ($value - $this->midValue) / ($this->maxValue - $this->midValue); $alpha1 = hexdec(substr($midColor, 0, 2)); $alpha2 = hexdec(substr($maxColor, 0, 2)); $red1 = hexdec(substr($midColor, 2, 2)); $red2 = hexdec(substr($maxColor, 2, 2)); $green1 = hexdec(substr($midColor, 4, 2)); $green2 = hexdec(substr($maxColor, 4, 2)); $blue1 = hexdec(substr($midColor, 6, 2)); $blue2 = hexdec(substr($maxColor, 6, 2)); return strtoupper(dechex((int) ($alpha2 * $blend + $alpha1 * (1 - $blend))) . '' . dechex((int) ($red2 * $blend + $red1 * (1 - $blend))) . '' . dechex((int) ($green2 * $blend + $green1 * (1 - $blend))) . '' . dechex((int) ($blue2 * $blend + $blue1 * (1 - $blend)))); } private function getLimitValue(string $type, float $value = 0, float $formula = 0): float { if (count($this->valueArray) === 0) { return 0; } switch ($type) { case 'min': /** @var float|int */ $temp = min($this->valueArray); return (float) $temp; case 'max': /** @var float|int */ $temp = max($this->valueArray); return (float) $temp; case 'percentile': return (float) Percentiles::PERCENTILE($this->valueArray, (float) ($value / 100)); case 'formula': return $formula; case 'percent': /** @var float|int */ $min = min($this->valueArray); $min = (float) $min; /** @var float|int */ $max = max($this->valueArray); $max = (float) $max; return $min + (float) ($value / 100) * ($max - $min); default: return 0; } } /** * Prepares color scale for execution, see the first if for variables that must be set beforehand. */ public function prepareColorScale(): self { if ($this->minimumConditionalFormatValueObject !== null && $this->maximumConditionalFormatValueObject !== null && $this->minimumColor !== null && $this->maximumColor !== null) { if ($this->midpointConditionalFormatValueObject !== null && $this->midpointConditionalFormatValueObject->getType() !== 'None') { $this->minValue = $this->getLimitValue($this->minimumConditionalFormatValueObject->getType(), (float) $this->minimumConditionalFormatValueObject->getValue(), (float) $this->minimumConditionalFormatValueObject->getCellFormula()); $this->midValue = $this->getLimitValue($this->midpointConditionalFormatValueObject->getType(), (float) $this->midpointConditionalFormatValueObject->getValue(), (float) $this->midpointConditionalFormatValueObject->getCellFormula()); $this->maxValue = $this->getLimitValue($this->maximumConditionalFormatValueObject->getType(), (float) $this->maximumConditionalFormatValueObject->getValue(), (float) $this->maximumConditionalFormatValueObject->getCellFormula()); } else { $this->minValue = $this->getLimitValue($this->minimumConditionalFormatValueObject->getType(), (float) $this->minimumConditionalFormatValueObject->getValue(), (float) $this->minimumConditionalFormatValueObject->getCellFormula()); $this->maxValue = $this->getLimitValue($this->maximumConditionalFormatValueObject->getType(), (float) $this->maximumConditionalFormatValueObject->getValue(), (float) $this->maximumConditionalFormatValueObject->getCellFormula()); $this->midValue = (float) ($this->minValue + $this->maxValue) / 2; $blend = 0.5; $minColor = $this->minimumColor->getARGB(); $maxColor = $this->maximumColor->getARGB(); if ($minColor !== null && $maxColor !== null) { $alpha1 = hexdec(substr($minColor, 0, 2)); $alpha2 = hexdec(substr($maxColor, 0, 2)); $red1 = hexdec(substr($minColor, 2, 2)); $red2 = hexdec(substr($maxColor, 2, 2)); $green1 = hexdec(substr($minColor, 4, 2)); $green2 = hexdec(substr($maxColor, 4, 2)); $blue1 = hexdec(substr($minColor, 6, 2)); $blue2 = hexdec(substr($maxColor, 6, 2)); $this->midpointColor = new Color(strtoupper(dechex((int) ($alpha2 * $blend + $alpha1 * (1 - $blend))) . '' . dechex((int) ($red2 * $blend + $red1 * (1 - $blend))) . '' . dechex((int) ($green2 * $blend + $green1 * (1 - $blend))) . '' . dechex((int) ($blue2 * $blend + $blue1 * (1 - $blend))))); } else { $this->midpointColor = null; } } } return $this; } /** * Checks that all needed color scale data is in place. */ public function colorScaleReadyForUse(): bool { if ($this->minimumColor === null || $this->midpointColor === null || $this->maximumColor === null) { return false; } return true; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php ================================================ showValue; } public function setShowValue(bool $showValue): self { $this->showValue = $showValue; return $this; } public function getMinimumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getMaximumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getColor(): string { return $this->color; } public function setColor(string $color): self { $this->color = $color; return $this; } public function getConditionalFormattingRuleExt(): ?ConditionalFormattingRuleExtension { return $this->conditionalFormattingRuleExt; } public function setConditionalFormattingRuleExt(ConditionalFormattingRuleExtension $conditionalFormattingRuleExt): self { $this->conditionalFormattingRuleExt = $conditionalFormattingRuleExt; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php ================================================ attributes */ private int $minLength; private int $maxLength; private ?bool $border = null; private ?bool $gradient = null; private ?string $direction = null; private ?bool $negativeBarBorderColorSameAsPositive = null; private ?string $axisPosition = null; // children private ConditionalFormatValueObject $maximumConditionalFormatValueObject; private ConditionalFormatValueObject $minimumConditionalFormatValueObject; private ?string $borderColor = null; private ?string $negativeFillColor = null; private ?string $negativeBorderColor = null; /** @var array{rgb: ?string, theme: ?string, tint: ?string} */ private array $axisColor = [ 'rgb' => null, 'theme' => null, 'tint' => null, ]; /** @return mixed[] */ public function getXmlAttributes(): array { $ret = []; foreach (['minLength', 'maxLength', 'direction', 'axisPosition'] as $attrKey) { if (null !== $this->{$attrKey}) { $ret[$attrKey] = $this->{$attrKey}; } } foreach (['border', 'gradient', 'negativeBarBorderColorSameAsPositive'] as $attrKey) { if (null !== $this->{$attrKey}) { $ret[$attrKey] = $this->{$attrKey} ? '1' : '0'; } } return $ret; } /** @return mixed[] */ public function getXmlElements(): array { $ret = []; $elms = ['borderColor', 'negativeFillColor', 'negativeBorderColor']; foreach ($elms as $elmKey) { if (null !== $this->{$elmKey}) { $ret[$elmKey] = ['rgb' => $this->{$elmKey}]; } } foreach (array_filter($this->axisColor) as $attrKey => $axisColorAttr) { if (!isset($ret['axisColor'])) { $ret['axisColor'] = []; } $ret['axisColor'][$attrKey] = $axisColorAttr; } return $ret; } public function getMinLength(): int { return $this->minLength; } public function setMinLength(int $minLength): self { $this->minLength = $minLength; return $this; } public function getMaxLength(): int { return $this->maxLength; } public function setMaxLength(int $maxLength): self { $this->maxLength = $maxLength; return $this; } public function getBorder(): ?bool { return $this->border; } public function setBorder(bool $border): self { $this->border = $border; return $this; } public function getGradient(): ?bool { return $this->gradient; } public function setGradient(bool $gradient): self { $this->gradient = $gradient; return $this; } public function getDirection(): ?string { return $this->direction; } public function setDirection(string $direction): self { $this->direction = $direction; return $this; } public function getNegativeBarBorderColorSameAsPositive(): ?bool { return $this->negativeBarBorderColorSameAsPositive; } public function setNegativeBarBorderColorSameAsPositive(bool $negativeBarBorderColorSameAsPositive): self { $this->negativeBarBorderColorSameAsPositive = $negativeBarBorderColorSameAsPositive; return $this; } public function getAxisPosition(): ?string { return $this->axisPosition; } public function setAxisPosition(string $axisPosition): self { $this->axisPosition = $axisPosition; return $this; } public function getMaximumConditionalFormatValueObject(): ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getMinimumConditionalFormatValueObject(): ConditionalFormatValueObject { return $this->minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getBorderColor(): ?string { return $this->borderColor; } public function setBorderColor(string $borderColor): self { $this->borderColor = $borderColor; return $this; } public function getNegativeFillColor(): ?string { return $this->negativeFillColor; } public function setNegativeFillColor(string $negativeFillColor): self { $this->negativeFillColor = $negativeFillColor; return $this; } public function getNegativeBorderColor(): ?string { return $this->negativeBorderColor; } public function setNegativeBorderColor(string $negativeBorderColor): self { $this->negativeBorderColor = $negativeBorderColor; return $this; } /** @return array{rgb: ?string, theme: ?string, tint: ?string} */ public function getAxisColor(): array { return $this->axisColor; } public function setAxisColor(?string $rgb, ?string $theme = null, ?string $tint = null): self { $this->axisColor = [ 'rgb' => $rgb, 'theme' => $theme, 'tint' => $tint, ]; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php ================================================ type = $type; $this->value = $value; $this->cellFormula = $cellFormula; } public function getType(): string { return $this->type; } public function setType(string $type): self { $this->type = $type; return $this; } public function getValue(): null|float|int|string { return $this->value; } public function setValue(null|float|int|string $value): self { $this->value = $value; return $this; } public function getCellFormula(): ?string { return $this->cellFormula; } public function setCellFormula(?string $cellFormula): self { $this->cellFormula = $cellFormula; return $this; } public function getGreaterThanOrEqual(): ?bool { return $this->greaterThanOrEqual; } public function setGreaterThanOrEqual(?bool $greaterThanOrEqual): self { $this->greaterThanOrEqual = $greaterThanOrEqual; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php ================================================ id = '{' . $this->generateUuid() . '}'; } else { $this->id = $id; } $this->cfRule = $cfRule; } private function generateUuid(): string { $chars = mb_str_split('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx', 1, 'UTF-8'); foreach ($chars as $i => $char) { if ($char === 'x') { $chars[$i] = dechex(random_int(0, 15)); } elseif ($char === 'y') { $chars[$i] = dechex(random_int(8, 11)); } } return implode('', $chars); } /** @return mixed[] */ public static function parseExtLstXml(?SimpleXMLElement $extLstXml): array { $conditionalFormattingRuleExtensions = []; $conditionalFormattingRuleExtensionXml = null; if ($extLstXml instanceof SimpleXMLElement) { foreach ((count($extLstXml) > 0 ? $extLstXml : [$extLstXml]) as $extLst) { //this uri is conditionalFormattings //https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 if (isset($extLst->ext['uri']) && (string) $extLst->ext['uri'] === '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { $conditionalFormattingRuleExtensionXml = $extLst->ext; } } if ($conditionalFormattingRuleExtensionXml) { $ns = $conditionalFormattingRuleExtensionXml->getNamespaces(true); $extFormattingsXml = $conditionalFormattingRuleExtensionXml->children($ns['x14']); foreach ($extFormattingsXml->children($ns['x14']) as $extFormattingXml) { $extCfRuleXml = $extFormattingXml->cfRule; $attributes = $extCfRuleXml->attributes(); if (!$attributes || ((string) $attributes->type) !== Conditional::CONDITION_DATABAR) { continue; } $extFormattingRuleObj = new self((string) $attributes->id); $extFormattingRuleObj->setSqref((string) $extFormattingXml->children($ns['xm'])->sqref); $conditionalFormattingRuleExtensions[$extFormattingRuleObj->getId()] = $extFormattingRuleObj; $extDataBarObj = new ConditionalDataBarExtension(); $extFormattingRuleObj->setDataBarExt($extDataBarObj); $dataBarXml = $extCfRuleXml->dataBar; self::parseExtDataBarAttributesFromXml($extDataBarObj, $dataBarXml); self::parseExtDataBarElementChildrenFromXml($extDataBarObj, $dataBarXml, $ns); } } } return $conditionalFormattingRuleExtensions; } private static function parseExtDataBarAttributesFromXml( ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml ): void { $dataBarAttribute = $dataBarXml->attributes(); if ($dataBarAttribute === null) { return; } if ($dataBarAttribute->minLength) { $extDataBarObj->setMinLength((int) $dataBarAttribute->minLength); } if ($dataBarAttribute->maxLength) { $extDataBarObj->setMaxLength((int) $dataBarAttribute->maxLength); } if ($dataBarAttribute->border) { $extDataBarObj->setBorder((bool) (string) $dataBarAttribute->border); } if ($dataBarAttribute->gradient) { $extDataBarObj->setGradient((bool) (string) $dataBarAttribute->gradient); } if ($dataBarAttribute->direction) { $extDataBarObj->setDirection((string) $dataBarAttribute->direction); } if ($dataBarAttribute->negativeBarBorderColorSameAsPositive) { $extDataBarObj->setNegativeBarBorderColorSameAsPositive((bool) (string) $dataBarAttribute->negativeBarBorderColorSameAsPositive); } if ($dataBarAttribute->axisPosition) { $extDataBarObj->setAxisPosition((string) $dataBarAttribute->axisPosition); } } /** @param string[] $ns */ private static function parseExtDataBarElementChildrenFromXml(ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml, array $ns): void { if ($dataBarXml->borderColor) { $attributes = $dataBarXml->borderColor->attributes(); if ($attributes !== null) { $extDataBarObj->setBorderColor((string) $attributes['rgb']); } } if ($dataBarXml->negativeFillColor) { $attributes = $dataBarXml->negativeFillColor->attributes(); if ($attributes !== null) { $extDataBarObj->setNegativeFillColor((string) $attributes['rgb']); } } if ($dataBarXml->negativeBorderColor) { $attributes = $dataBarXml->negativeBorderColor->attributes(); if ($attributes !== null) { $extDataBarObj->setNegativeBorderColor((string) $attributes['rgb']); } } if ($dataBarXml->axisColor) { $axisColorAttr = $dataBarXml->axisColor->attributes(); if ($axisColorAttr !== null) { $extDataBarObj->setAxisColor((string) $axisColorAttr['rgb'], (string) $axisColorAttr['theme'], (string) $axisColorAttr['tint']); } } $cfvoIndex = 0; foreach ($dataBarXml->cfvo as $cfvo) { $f = (string) $cfvo->children($ns['xm'])->f; $attributes = $cfvo->attributes(); if (!($attributes)) { continue; } if ($cfvoIndex === 0) { $extDataBarObj->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); } if ($cfvoIndex === 1) { $extDataBarObj->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); } ++$cfvoIndex; } } public function getId(): string { return $this->id; } public function setId(string $id): self { $this->id = $id; return $this; } public function getCfRule(): string { return $this->cfRule; } public function setCfRule(string $cfRule): self { $this->cfRule = $cfRule; return $this; } public function getDataBarExt(): ConditionalDataBarExtension { return $this->dataBar; } public function setDataBarExt(ConditionalDataBarExtension $dataBar): self { $this->dataBar = $dataBar; return $this; } public function getSqref(): string { return $this->sqref; } public function setSqref(string $sqref): self { $this->sqref = $sqref; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalIconSet.php ================================================ iconSetType; } public function setIconSetType(IconSetValues $type): self { $this->iconSetType = $type; return $this; } public function getReverse(): ?bool { return $this->reverse; } public function setReverse(bool $reverse): self { $this->reverse = $reverse; return $this; } public function getShowValue(): ?bool { return $this->showValue; } public function setShowValue(bool $showValue): self { $this->showValue = $showValue; return $this; } public function getCustom(): ?bool { return $this->custom; } public function setCustom(bool $custom): self { $this->custom = $custom; return $this; } /** * Get the conditional format value objects. * * @return ConditionalFormatValueObject[] */ public function getCfvos(): array { return $this->cfvos; } /** * Set the conditional format value objects. * * @param ConditionalFormatValueObject[] $cfvos */ public function setCfvos(array $cfvos): self { $this->cfvos = $cfvos; return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/IconSetValues.php ================================================ matched; } /** * Return a style that combines the base style for a cell * with any conditional or table styles applicable to the cell. * * @param bool $tableFormats True/false to indicate whether * custom table styles should be considered. * Note that builtin table styles are not supported. * @param bool $conditionals True/false to indicate whether * conditional styles should be considered. */ public function getMergedStyle(Worksheet $worksheet, string $coordinate, bool $tableFormats = true, bool $conditionals = true, ?bool $builtInTableStyles = null): Style { $builtInTableStyles ??= $tableFormats; $this->matched = false; $styleMerger = new StyleMerger($worksheet->getStyle($coordinate)); if ($tableFormats) { $this->assessTables($worksheet, $coordinate, $styleMerger); } if ($builtInTableStyles) { $this->assessBuiltinTables($worksheet, $coordinate, $styleMerger); } if ($conditionals) { $this->assessConditionals($worksheet, $coordinate, $styleMerger); } return $styleMerger->getStyle(); } private function assessTables(Worksheet $worksheet, string $coordinate, StyleMerger $styleMerger): void { $tables = $worksheet->getTablesWithStylesForCell($worksheet->getCell($coordinate)); foreach ($tables as $ts) { $dxfsTableStyle = $ts->getStyle()->getTableDxfsStyle(); if ($dxfsTableStyle !== null) { $tableRow = $ts->getRowNumber($coordinate); if ($tableRow === 0 && $dxfsTableStyle->getHeaderRowStyle() !== null) { $styleMerger->mergeStyle( $dxfsTableStyle->getHeaderRowStyle() ); $this->matched = true; } elseif ($tableRow % 2 === 1 && $dxfsTableStyle->getFirstRowStripeStyle() !== null) { $styleMerger->mergeStyle( $dxfsTableStyle->getFirstRowStripeStyle() ); $this->matched = true; } elseif ($tableRow % 2 === 0 && $dxfsTableStyle->getSecondRowStripeStyle() !== null) { $styleMerger->mergeStyle( $dxfsTableStyle->getSecondRowStripeStyle() ); $this->matched = true; } } } } private static ?Style $headerStyle = null; private static ?Style $firstRowStyle = null; private function assessBuiltinTables(Worksheet $worksheet, string $coordinate, StyleMerger $styleMerger): void { if (self::$headerStyle === null) { self::$headerStyle = new Style(); self::$headerStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getEndColor() ->setArgb('FF000000'); self::$headerStyle->getFill()->getStartColor() ->setArgb('FF000000'); self::$headerStyle->getFont() ->getColor()->setRgb('FFFFFF'); } if (self::$firstRowStyle === null) { self::$firstRowStyle = new Style(); self::$firstRowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getEndColor() ->setArgb('FFD9D9D9'); self::$firstRowStyle->getFill()->getStartColor() ->setArgb('FFD9D9D9'); } $tables = $worksheet->getTablesWithoutStylesForCell($worksheet->getCell($coordinate)); foreach ($tables as $table) { $tableRow = $table->getRowNumber($coordinate); if ($tableRow === 0 && $table->getShowHeaderRow()) { $styleMerger->mergeStyle(self::$headerStyle); $this->matched = true; } elseif ($tableRow % 2 === 1) { $styleMerger->mergeStyle(self::$firstRowStyle); $this->matched = true; } } } private function assessConditionals(Worksheet $worksheet, string $coordinate, StyleMerger $styleMerger): void { if ($worksheet->getConditionalRange($coordinate) !== null) { $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $worksheet->getConditionalRange($coordinate)); } else { $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $coordinate); } $matchedStyle = $assessor ->matchConditionsReturnNullIfNoneMatched( $worksheet->getConditionalStyles($coordinate), $worksheet->getCell($coordinate) ->getCalculatedValueString(), true ); if ($matchedStyle !== null) { $this->matched = true; $styleMerger->mergeStyle($matchedStyle); } } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php ================================================ exportArray(); $this->baseStyle = new Style(); $this->baseStyle->applyFromArray($array); } public function getStyle(): Style { return $this->baseStyle; } public function mergeStyle(Style $style): void { if ($style->getNumberFormat()->getFormatCode() !== null) { $this->baseStyle->getNumberFormat()->setFormatCode($style->getNumberFormat()->getFormatCode()); } $this->mergeFontStyle($this->baseStyle->getFont(), $style->getFont()); $this->mergeFillStyle($this->baseStyle->getFill(), $style->getFill()); $this->mergeBordersStyle($this->baseStyle->getBorders(), $style->getBorders()); } protected function mergeFontStyle(Font $baseFontStyle, Font $fontStyle): void { if ($fontStyle->getBold() !== null) { $baseFontStyle->setBold($fontStyle->getBold()); } if ($fontStyle->getItalic() !== null) { $baseFontStyle->setItalic($fontStyle->getItalic()); } if ($fontStyle->getStrikethrough() !== null) { $baseFontStyle->setStrikethrough($fontStyle->getStrikethrough()); } if ($fontStyle->getUnderline() !== null) { $baseFontStyle->setUnderline($fontStyle->getUnderline()); } if ($fontStyle->getColor()->getARGB() !== null) { $baseFontStyle->setColor($fontStyle->getColor()); } } protected function mergeFillStyle(Fill $baseFillStyle, Fill $fillStyle): void { if ($fillStyle->getFillType() !== null) { $baseFillStyle->setFillType($fillStyle->getFillType()); } $baseFillStyle->setRotation($fillStyle->getRotation()); if ($fillStyle->getStartColor()->getARGB() !== null) { $baseFillStyle->setStartColor($fillStyle->getStartColor()); } if ($fillStyle->getEndColor()->getARGB() !== null) { $baseFillStyle->setEndColor($fillStyle->getEndColor()); } } protected function mergeBordersStyle(Borders $baseBordersStyle, Borders $bordersStyle): void { $this->mergeBorderStyle($baseBordersStyle->getTop(), $bordersStyle->getTop()); $this->mergeBorderStyle($baseBordersStyle->getBottom(), $bordersStyle->getBottom()); $this->mergeBorderStyle($baseBordersStyle->getLeft(), $bordersStyle->getLeft()); $this->mergeBorderStyle($baseBordersStyle->getRight(), $bordersStyle->getRight()); } protected function mergeBorderStyle(Border $baseBorderStyle, Border $borderStyle): void { if ($borderStyle->getBorderStyle() !== Border::BORDER_OMIT) { $baseBorderStyle->setBorderStyle( $borderStyle->getBorderStyle() ); } if ($borderStyle->getColor()->getARGB() !== null) { $baseBorderStyle->setColor($borderStyle->getColor()); } } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php ================================================ false, 'isBlank' => true, 'notEmpty' => false, 'empty' => true, ]; protected const EXPRESSIONS = [ Wizard::NOT_BLANKS => 'LEN(TRIM(%s))>0', Wizard::BLANKS => 'LEN(TRIM(%s))=0', ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } protected function getExpression(): void { $this->expression = sprintf( self::EXPRESSIONS[$this->inverse ? Wizard::BLANKS : Wizard::NOT_BLANKS], $this->referenceCell ); } public function getConditional(): Conditional { $this->getExpression(); $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_CONTAINSBLANKS : Conditional::CONDITION_NOTCONTAINSBLANKS ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSBLANKS && $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSBLANKS ) { throw new Exception('Conditional is not a Blanks CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSBLANKS; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Blanks CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php ================================================ Conditional::OPERATOR_EQUAL, 'notEquals' => Conditional::OPERATOR_NOTEQUAL, 'greaterThan' => Conditional::OPERATOR_GREATERTHAN, 'greaterThanOrEqual' => Conditional::OPERATOR_GREATERTHANOREQUAL, 'lessThan' => Conditional::OPERATOR_LESSTHAN, 'lessThanOrEqual' => Conditional::OPERATOR_LESSTHANOREQUAL, 'between' => Conditional::OPERATOR_BETWEEN, 'notBetween' => Conditional::OPERATOR_NOTBETWEEN, ]; protected const SINGLE_OPERATORS = CellMatcher::COMPARISON_OPERATORS; protected const RANGE_OPERATORS = CellMatcher::COMPARISON_RANGE_OPERATORS; protected string $operator = Conditional::OPERATOR_EQUAL; /** @var array */ protected array $operand = [0]; /** * @var string[] */ protected array $operandValueType = []; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { if ((!isset(self::SINGLE_OPERATORS[$operator])) && (!isset(self::RANGE_OPERATORS[$operator]))) { throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); } $this->operator = $operator; } protected function operand(int $index, mixed $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void { if (is_string($operand)) { $operand = $this->validateOperand($operand, $operandValueType); } $this->operand[$index] = $operand; //* @phpstan-ignore-line $this->operandValueType[$index] = $operandValueType; } /** @param null|bool|float|int|string $value value to be wrapped */ protected function wrapValue(mixed $value, string $operandValueType): float|int|string { if (!is_numeric($value) && !is_bool($value) && null !== $value) { if ($operandValueType === Wizard::VALUE_TYPE_LITERAL) { return '"' . str_replace('"', '""', $value) . '"'; } return $this->cellConditionCheck($value); } if (null === $value) { $value = 'NULL'; } elseif (is_bool($value)) { $value = $value ? 'TRUE' : 'FALSE'; } return $value; } public function getConditional(): Conditional { if (!isset(self::RANGE_OPERATORS[$this->operator])) { unset($this->operand[1], $this->operandValueType[1]); } $values = array_map([$this, 'wrapValue'], $this->operand, $this->operandValueType); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_CELLIS); $conditional->setOperatorType($this->operator); $conditional->setConditions($values); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } protected static function unwrapString(string $condition): string { if ((str_starts_with($condition, '"')) && (str_starts_with(strrev($condition), '"'))) { $condition = substr($condition, 1, -1); } return str_replace('""', '"', $condition); } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_CELLIS) { throw new Exception('Conditional is not a Cell Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->operator = $conditional->getOperatorType(); $conditions = $conditional->getConditions(); foreach ($conditions as $index => $condition) { // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? $operandValueType = Wizard::VALUE_TYPE_LITERAL; if (is_string($condition)) { if (Calculation::keyInExcelConstants($condition)) { $condition = Calculation::getExcelConstants($condition); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { $operandValueType = Wizard::VALUE_TYPE_CELL; $condition = self::reverseAdjustCellRef($condition, $cellRange); } elseif ( preg_match('/\(\)/', $condition) || preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) ) { $operandValueType = Wizard::VALUE_TYPE_FORMULA; $condition = self::reverseAdjustCellRef($condition, $cellRange); } else { $condition = self::unwrapString($condition); } } $wizard->operand($index, $condition, $operandValueType); } return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName]) && $methodName !== 'and') { throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); } if ($methodName === 'and') { if (!isset(self::RANGE_OPERATORS[$this->operator])) { throw new Exception('AND Value is only appropriate for range operators'); } $this->operand(1, ...$arguments); return $this; } $this->operator(self::MAGIC_OPERATIONS[$methodName]); //$this->operand(0, ...$arguments); if (count($arguments) < 2) { $this->operand(0, $arguments[0]); } else { /** @var string */ $arg1 = $arguments[1]; $this->operand(0, $arguments[0], $arg1); } return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php ================================================ Conditional::TIMEPERIOD_YESTERDAY, 'today' => Conditional::TIMEPERIOD_TODAY, 'tomorrow' => Conditional::TIMEPERIOD_TOMORROW, 'lastSevenDays' => Conditional::TIMEPERIOD_LAST_7_DAYS, 'last7Days' => Conditional::TIMEPERIOD_LAST_7_DAYS, 'lastWeek' => Conditional::TIMEPERIOD_LAST_WEEK, 'thisWeek' => Conditional::TIMEPERIOD_THIS_WEEK, 'nextWeek' => Conditional::TIMEPERIOD_NEXT_WEEK, 'lastMonth' => Conditional::TIMEPERIOD_LAST_MONTH, 'thisMonth' => Conditional::TIMEPERIOD_THIS_MONTH, 'nextMonth' => Conditional::TIMEPERIOD_NEXT_MONTH, ]; protected const EXPRESSIONS = [ Conditional::TIMEPERIOD_YESTERDAY => 'FLOOR(%s,1)=TODAY()-1', Conditional::TIMEPERIOD_TODAY => 'FLOOR(%s,1)=TODAY()', Conditional::TIMEPERIOD_TOMORROW => 'FLOOR(%s,1)=TODAY()+1', Conditional::TIMEPERIOD_LAST_7_DAYS => 'AND(TODAY()-FLOOR(%s,1)<=6,FLOOR(%s,1)<=TODAY())', Conditional::TIMEPERIOD_LAST_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(%s,0)<(WEEKDAY(TODAY())+7))', Conditional::TIMEPERIOD_THIS_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(%s,0)-TODAY()<=7-WEEKDAY(TODAY()))', Conditional::TIMEPERIOD_NEXT_WEEK => 'AND(ROUNDDOWN(%s,0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(%s,0)-TODAY()<(15-WEEKDAY(TODAY())))', Conditional::TIMEPERIOD_LAST_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0-1)),YEAR(%s)=YEAR(EDATE(TODAY(),0-1)))', Conditional::TIMEPERIOD_THIS_MONTH => 'AND(MONTH(%s)=MONTH(TODAY()),YEAR(%s)=YEAR(TODAY()))', Conditional::TIMEPERIOD_NEXT_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0+1)),YEAR(%s)=YEAR(EDATE(TODAY(),0+1)))', ]; protected string $operator; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { $this->operator = $operator; } protected function setExpression(): void { $referenceCount = substr_count(self::EXPRESSIONS[$this->operator], '%s'); $references = array_fill(0, $referenceCount, $this->referenceCell); $this->expression = sprintf(self::EXPRESSIONS[$this->operator], ...$references); } public function getConditional(): Conditional { $this->setExpression(); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_TIMEPERIOD); $conditional->setText($this->operator); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_TIMEPERIOD) { throw new Exception('Conditional is not a Date Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->operator = $conditional->getText(); return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName])) { throw new Exception('Invalid Operation for Date Value CF Rule Wizard'); } $this->operator(self::MAGIC_OPERATIONS[$methodName]); return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php ================================================ false, 'unique' => true, ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } public function getConditional(): Conditional { $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_UNIQUE : Conditional::CONDITION_DUPLICATES ); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_DUPLICATES && $conditional->getConditionType() !== Conditional::CONDITION_UNIQUE ) { throw new Exception('Conditional is not a Duplicates CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_UNIQUE; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Errors CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php ================================================ false, 'isError' => true, ]; protected const EXPRESSIONS = [ Wizard::NOT_ERRORS => 'NOT(ISERROR(%s))', Wizard::ERRORS => 'ISERROR(%s)', ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } protected function getExpression(): void { $this->expression = sprintf( self::EXPRESSIONS[$this->inverse ? Wizard::ERRORS : Wizard::NOT_ERRORS], $this->referenceCell ); } public function getConditional(): Conditional { $this->getExpression(); $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_CONTAINSERRORS : Conditional::CONDITION_NOTCONTAINSERRORS ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSERRORS && $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSERRORS ) { throw new Exception('Conditional is not an Errors CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSERRORS; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Errors CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php ================================================ validateOperand($expression, Wizard::VALUE_TYPE_FORMULA); $this->expression = $expression; return $this; } public function getConditional(): Conditional { /** @var string[] */ $expression = $this->adjustConditionsForCellReferences([$this->expression]); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_EXPRESSION); $conditional->setConditions($expression); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_EXPRESSION) { throw new Exception('Conditional is not an Expression CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->expression = self::reverseAdjustCellRef((string) ($conditional->getConditions()[0]), $cellRange); return $wizard; } /** * @param string[] $arguments */ public function __call(string $methodName, array $arguments): self { if ($methodName !== 'formula') { throw new Exception('Invalid Operation for Expression CF Rule Wizard'); } $this->expression(...$arguments); return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php ================================================ Conditional::OPERATOR_CONTAINSTEXT, 'doesntContain' => Conditional::OPERATOR_NOTCONTAINS, 'doesNotContain' => Conditional::OPERATOR_NOTCONTAINS, 'beginsWith' => Conditional::OPERATOR_BEGINSWITH, 'startsWith' => Conditional::OPERATOR_BEGINSWITH, 'endsWith' => Conditional::OPERATOR_ENDSWITH, ]; protected const OPERATORS = [ Conditional::OPERATOR_CONTAINSTEXT => Conditional::CONDITION_CONTAINSTEXT, Conditional::OPERATOR_NOTCONTAINS => Conditional::CONDITION_NOTCONTAINSTEXT, Conditional::OPERATOR_BEGINSWITH => Conditional::CONDITION_BEGINSWITH, Conditional::OPERATOR_ENDSWITH => Conditional::CONDITION_ENDSWITH, ]; protected const EXPRESSIONS = [ Conditional::OPERATOR_CONTAINSTEXT => 'NOT(ISERROR(SEARCH(%s,%s)))', Conditional::OPERATOR_NOTCONTAINS => 'ISERROR(SEARCH(%s,%s))', Conditional::OPERATOR_BEGINSWITH => 'LEFT(%s,LEN(%s))=%s', Conditional::OPERATOR_ENDSWITH => 'RIGHT(%s,LEN(%s))=%s', ]; protected string $operator; protected string $operand; protected string $operandValueType; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { if (!isset(self::OPERATORS[$operator])) { throw new Exception('Invalid Operator for Text Value CF Rule Wizard'); } $this->operator = $operator; } protected function operand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void { $operand = $this->validateOperand($operand, $operandValueType); $this->operand = $operand; $this->operandValueType = $operandValueType; } protected function wrapValue(string $value): string { return '"' . $value . '"'; } protected function setExpression(): void { $operand = $this->operandValueType === Wizard::VALUE_TYPE_LITERAL ? $this->wrapValue(str_replace('"', '""', $this->operand)) : $this->cellConditionCheck($this->operand); if ( $this->operator === Conditional::OPERATOR_CONTAINSTEXT || $this->operator === Conditional::OPERATOR_NOTCONTAINS ) { $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $operand, $this->referenceCell); } else { $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $this->referenceCell, $operand, $operand); } } public function getConditional(): Conditional { $this->setExpression(); $conditional = new Conditional(); $conditional->setConditionType(self::OPERATORS[$this->operator]); $conditional->setOperatorType($this->operator); $conditional->setText( $this->operandValueType !== Wizard::VALUE_TYPE_LITERAL ? $this->cellConditionCheck($this->operand) : $this->operand ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if (!in_array($conditional->getConditionType(), self::OPERATORS, true)) { throw new Exception('Conditional is not a Text Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->operator = (string) array_search($conditional->getConditionType(), self::OPERATORS, true); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? $wizard->operandValueType = Wizard::VALUE_TYPE_LITERAL; $condition = $conditional->getText(); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { $wizard->operandValueType = Wizard::VALUE_TYPE_CELL; $condition = self::reverseAdjustCellRef($condition, $cellRange); } elseif ( preg_match('/\(\)/', $condition) || preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) ) { $wizard->operandValueType = Wizard::VALUE_TYPE_FORMULA; } $wizard->operand = $condition; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName])) { throw new Exception('Invalid Operation for Text Value CF Rule Wizard'); } $this->operator(self::MAGIC_OPERATIONS[$methodName]); //$this->operand(...$arguments); if (count($arguments) < 2) { /** @var string */ $arg0 = $arguments[0]; $this->operand($arg0); } else { /** @var string */ $arg0 = $arguments[0]; /** @var string */ $arg1 = $arguments[1]; $this->operand($arg0, $arg1); } return $this; } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php ================================================ setCellRange($cellRange); } public function getCellRange(): string { return $this->cellRange; } public function setCellRange(string $cellRange): void { $this->cellRange = $cellRange; $this->setReferenceCellForExpressions($cellRange); } protected function setReferenceCellForExpressions(string $conditionalRange): void { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); [$this->referenceCell] = $conditionalRange[0]; [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); } public function getStopIfTrue(): bool { return $this->stopIfTrue; } public function setStopIfTrue(bool $stopIfTrue): void { $this->stopIfTrue = $stopIfTrue; } public function getStyle(): Style { return $this->style ?? new Style(false, true); } public function setStyle(Style $style): void { $this->style = $style; } protected function validateOperand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): string { if ( $operandValueType === Wizard::VALUE_TYPE_LITERAL && str_starts_with($operand, '"') && str_ends_with($operand, '"') ) { $operand = str_replace('""', '"', substr($operand, 1, -1)); } elseif ($operandValueType === Wizard::VALUE_TYPE_FORMULA && str_starts_with($operand, '=')) { $operand = substr($operand, 1); } return $operand; } /** @param string[] $matches */ protected static function reverseCellAdjustment(array $matches, int $referenceColumn, int $referenceRow): string { $worksheet = $matches[1]; $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column -= $referenceColumn - 1; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row = (int) $row - ($referenceRow - 1); } return "{$worksheet}{$column}{$row}"; } public static function reverseAdjustCellRef(string $condition, string $cellRange): string { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellRange))); [$referenceCell] = $conditionalRange[0]; [$referenceColumnIndex, $referenceRow] = Coordinate::indexesFromString($referenceCell); $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', fn ($matches): string => self::reverseCellAdjustment($matches, $referenceColumnIndex, $referenceRow), $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } /** @param string[] $matches */ protected function conditionCellAdjustment(array $matches): string { $worksheet = $matches[1]; $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column += $this->referenceColumn - 1; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row = (int) $row + ($this->referenceRow - 1); } return "{$worksheet}{$column}{$row}"; } protected function cellConditionCheck(string $condition): string { $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', [$this, 'conditionCellAdjustment'], $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } /** * @param mixed[] $conditions * * @return mixed[] */ protected function adjustConditionsForCellReferences(array $conditions): array { return array_map( [$this, 'cellConditionCheck'], $conditions ); } } ================================================ FILE: src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php ================================================ cellRange = $cellRange; } public function newRule(string $ruleType): WizardInterface { return match ($ruleType) { self::CELL_VALUE => new Wizard\CellValue($this->cellRange), self::TEXT_VALUE => new Wizard\TextValue($this->cellRange), self::BLANKS => new Wizard\Blanks($this->cellRange, true), self::NOT_BLANKS => new Wizard\Blanks($this->cellRange, false), self::ERRORS => new Wizard\Errors($this->cellRange, true), self::NOT_ERRORS => new Wizard\Errors($this->cellRange, false), self::EXPRESSION, self::FORMULA => new Wizard\Expression($this->cellRange), self::DATES_OCCURRING => new Wizard\DateValue($this->cellRange), self::DUPLICATES => new Wizard\Duplicates($this->cellRange, false), self::UNIQUE => new Wizard\Duplicates($this->cellRange, true), default => throw new Exception('No wizard exists for this CF rule type'), }; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { $conditionalType = $conditional->getConditionType(); return match ($conditionalType) { Conditional::CONDITION_CELLIS => Wizard\CellValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSTEXT, Conditional::CONDITION_NOTCONTAINSTEXT, Conditional::CONDITION_BEGINSWITH, Conditional::CONDITION_ENDSWITH => Wizard\TextValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSBLANKS, Conditional::CONDITION_NOTCONTAINSBLANKS => Wizard\Blanks::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSERRORS, Conditional::CONDITION_NOTCONTAINSERRORS => Wizard\Errors::fromConditional($conditional, $cellRange), Conditional::CONDITION_TIMEPERIOD => Wizard\DateValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_EXPRESSION => Wizard\Expression::fromConditional($conditional, $cellRange), Conditional::CONDITION_DUPLICATES, Conditional::CONDITION_UNIQUE => Wizard\Duplicates::fromConditional($conditional, $cellRange), default => throw new Exception('No wizard exists for this CF rule type'), }; } } ================================================ FILE: src/PhpSpreadsheet/Style/Fill.php ================================================ fillType = null; } $this->startColor = new Color(Color::COLOR_WHITE, $isSupervisor, $isConditional); $this->endColor = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional); // bind parent if we are a supervisor if ($isSupervisor) { $this->startColor->bindParent($this, 'startColor'); $this->endColor->bindParent($this, 'endColor'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getFill(); } /** * Build style array from subcomponents. * * @param mixed[] $array * * @return array{fill: mixed[]} */ public function getStyleArray(array $array): array { return ['fill' => $array]; } /** * Apply styles from array. * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray( * [ * 'fillType' => Fill::FILL_GRADIENT_LINEAR, * 'rotation' => 0.0, * 'startColor' => [ * 'rgb' => '000000' * ], * 'endColor' => [ * 'argb' => 'FFFFFFFF' * ] * ] * ); * * * @param array{fillType?: string, rotation?: float, startColor?: array{rgb?: string, argb?: string}, endColor?: array{rgb?: string, argb?: string}, color?: array{rgb?: string, argb?: string}} $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['fillType'])) { $this->setFillType($styleArray['fillType']); } if (isset($styleArray['rotation'])) { $this->setRotation($styleArray['rotation']); } if (isset($styleArray['startColor'])) { $this->getStartColor() ->applyFromArray($styleArray['startColor']); } if (isset($styleArray['endColor'])) { $this->getEndColor() ->applyFromArray($styleArray['endColor']); } if (isset($styleArray['color'])) { $this->getStartColor() ->applyFromArray($styleArray['color']); $this->getEndColor() ->applyFromArray($styleArray['color']); } } return $this; } /** * Get Fill Type. */ public function getFillType(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getFillType(); } return $this->fillType; } /** * Set Fill Type. * * @param string $fillType Fill type, see self::FILL_* * * @return $this */ public function setFillType(string $fillType): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['fillType' => $fillType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->fillType = $fillType; } return $this; } /** * Get Rotation. */ public function getRotation(): float { if ($this->isSupervisor) { return $this->getSharedComponent()->getRotation(); } return $this->rotation; } /** * Set Rotation. * * @return $this */ public function setRotation(float $angleInDegrees): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->rotation = $angleInDegrees; } return $this; } /** * Get Start Color. */ public function getStartColor(): Color { return $this->startColor; } /** * Set Start Color. * * @return $this */ public function setStartColor(Color $color): static { $this->colorChanged = true; // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->startColor = $color; } return $this; } /** * Get End Color. */ public function getEndColor(): Color { return $this->endColor; } /** * Set End Color. * * @return $this */ public function setEndColor(Color $color): static { $this->colorChanged = true; // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->endColor = $color; } return $this; } public function getColorsChanged(): bool { if ($this->isSupervisor) { $changed = $this->getSharedComponent()->colorChanged; } else { $changed = $this->colorChanged; } return $changed || $this->startColor->getHasChanged() || $this->endColor->getHasChanged(); } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } // Note that we don't care about colours for fill type NONE, but could have duplicate NONEs with // different hashes if we don't explicitly prevent this return md5( $this->getFillType() . $this->getRotation() . ($this->getFillType() !== self::FILL_NONE ? $this->getStartColor()->getHashCode() : '') . ($this->getFillType() !== self::FILL_NONE ? $this->getEndColor()->getHashCode() : '') . ((string) $this->getColorsChanged()) . __CLASS__ ); } /** @return mixed[] */ protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'fillType', $this->getFillType()); $this->exportArray2($exportedArray, 'rotation', $this->getRotation()); if ($this->getColorsChanged()) { $this->exportArray2($exportedArray, 'endColor', $this->getEndColor()); $this->exportArray2($exportedArray, 'startColor', $this->getStartColor()); } return $exportedArray; } } ================================================ FILE: src/PhpSpreadsheet/Style/Font.php ================================================ name = null; $this->size = null; $this->bold = null; $this->italic = null; $this->superscript = null; $this->subscript = null; $this->underline = null; $this->strikethrough = null; $this->color = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional); } else { $this->color = new Color(Color::COLOR_BLACK, $isSupervisor); } // bind parent if we are a supervisor if ($isSupervisor) { $this->color->bindParent($this, 'color'); } } public function applyThemeFonts(Theme $theme): void { $this->setName($theme->getMinorFontLatin()); $this->setLatin($theme->getMinorFontLatin()); $this->setEastAsian($theme->getMinorFontEastAsian()); $this->setComplexScript($theme->getMinorFontComplexScript()); } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getFont(); } /** * Build style array from subcomponents. * * @param mixed[] $array * * @return array{font: mixed[]} */ public function getStyleArray(array $array): array { return ['font' => $array]; } /** * Apply styles from array. * * * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray( * [ * 'name' => 'Arial', * 'bold' => TRUE, * 'italic' => FALSE, * 'underline' => \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE, * 'strikethrough' => FALSE, * 'color' => [ * 'rgb' => '808080' * ] * ] * ); * * * @param array{ * autoColor?: bool, * bold?: bool, * cap?: string, * chartColor?: ChartColor, * color?: string[], * complexScript?: string, * eastAsian?: string, * italic?: bool, * latin?: string, * name?: string, * scheme?: string, * size?: null|float|int, * strikethrough?: bool, * superscript?: bool, * subscript?: bool, * underline?: bool|string, * } $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['name'])) { $this->setName($styleArray['name']); } if (isset($styleArray['latin'])) { $this->setLatin($styleArray['latin']); } if (isset($styleArray['eastAsian'])) { $this->setEastAsian($styleArray['eastAsian']); } if (isset($styleArray['complexScript'])) { $this->setComplexScript( $styleArray['complexScript'] ); } if (isset($styleArray['bold'])) { $this->setBold($styleArray['bold']); } if (isset($styleArray['italic'])) { $this->setItalic($styleArray['italic']); } if (isset($styleArray['superscript'])) { $this->setSuperscript($styleArray['superscript']); } if (isset($styleArray['subscript'])) { $this->setSubscript($styleArray['subscript']); } if (isset($styleArray['underline'])) { $this->setUnderline($styleArray['underline']); } if (isset($styleArray['strikethrough'])) { $this->setStrikethrough( $styleArray['strikethrough'] ); } if (isset($styleArray['color'])) { /** @var array{rgb?: string, argb?: string, theme?: int} */ $temp = $styleArray['color']; $this->getColor() ->applyFromArray($temp); } if (isset($styleArray['size'])) { $this->setSize($styleArray['size']); } if (isset($styleArray['chartColor'])) { $this->chartColor = $styleArray['chartColor']; } if (isset($styleArray['scheme'])) { $this->setScheme($styleArray['scheme']); } if (isset($styleArray['cap'])) { $this->setCap($styleArray['cap']); } if (isset($styleArray['autoColor'])) { $this->setAutoColor($styleArray['autoColor']); } } return $this; } /** * Get Name. */ public function getName(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getName(); } return $this->name; } public function getLatin(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getLatin(); } return $this->latin; } public function getEastAsian(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getEastAsian(); } return $this->eastAsian; } public function getComplexScript(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getComplexScript(); } return $this->complexScript; } /** * Set Name and turn off Scheme. */ public function setName(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['name' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->name = $fontname; } return $this->setScheme(''); } public function setLatin(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if (!$this->isSupervisor) { $this->latin = $fontname; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['latin' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function setEastAsian(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if (!$this->isSupervisor) { $this->eastAsian = $fontname; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['eastAsian' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function setComplexScript(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if (!$this->isSupervisor) { $this->complexScript = $fontname; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['complexScript' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } /** * Get Size. */ public function getSize(): ?float { if ($this->isSupervisor) { return $this->getSharedComponent()->getSize(); } return $this->size; } /** * Set Size. * * @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch) * * @return $this */ public function setSize(mixed $sizeInPoints, bool $nullOk = false): static { if (is_string($sizeInPoints) || is_int($sizeInPoints)) { $sizeInPoints = (float) $sizeInPoints; // $pValue = 0 if given string is not numeric } // Size must be a positive floating point number // ECMA-376-1:2016, part 1, chapter 18.4.11 sz (Font Size), p. 1536 if (!is_float($sizeInPoints) || !($sizeInPoints > 0)) { if (!$nullOk || $sizeInPoints !== null) { $sizeInPoints = 10.0; } } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['size' => $sizeInPoints]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->size = $sizeInPoints; } return $this; } /** * Get Bold. */ public function getBold(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getBold(); } return $this->bold; } /** * Set Bold. * * @return $this */ public function setBold(bool $bold): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['bold' => $bold]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->bold = $bold; } return $this; } /** * Get Italic. */ public function getItalic(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getItalic(); } return $this->italic; } /** * Set Italic. * * @return $this */ public function setItalic(bool $italic): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['italic' => $italic]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->italic = $italic; } return $this; } /** * Get Superscript. */ public function getSuperscript(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getSuperscript(); } return $this->superscript; } /** * Set Superscript. * * @return $this */ public function setSuperscript(bool $superscript): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['superscript' => $superscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->superscript = $superscript; if ($this->superscript) { $this->subscript = false; } } return $this; } /** * Get Subscript. */ public function getSubscript(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getSubscript(); } return $this->subscript; } /** * Set Subscript. * * @return $this */ public function setSubscript(bool $subscript): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['subscript' => $subscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->subscript = $subscript; if ($this->subscript) { $this->superscript = false; } } return $this; } public function getBaseLine(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getBaseLine(); } return $this->baseLine; } public function setBaseLine(int $baseLine): self { if (!$this->isSupervisor) { $this->baseLine = $baseLine; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['baseLine' => $baseLine]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function getStrikeType(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getStrikeType(); } return $this->strikeType; } public function setStrikeType(string $strikeType): self { if (!$this->isSupervisor) { $this->strikeType = $strikeType; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['strikeType' => $strikeType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function getUnderlineColor(): ?ChartColor { if ($this->isSupervisor) { return $this->getSharedComponent()->getUnderlineColor(); } return $this->underlineColor; } /** @param array{value: null|string, alpha: null|int|string, brightness?: null|int|string, type: null|string} $colorArray */ public function setUnderlineColor(array $colorArray): self { if (!$this->isSupervisor) { $this->underlineColor = new ChartColor($colorArray); } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['underlineColor' => $colorArray]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function getChartColor(): ?ChartColor { if ($this->isSupervisor) { return $this->getSharedComponent()->getChartColor(); } return $this->chartColor; } /** @param array{value: null|string, alpha: null|int|string, brightness?: null|int|string, type: null|string} $colorArray */ public function setChartColor(array $colorArray): self { if (!$this->isSupervisor) { $this->chartColor = new ChartColor($colorArray); } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['chartColor' => $colorArray]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function setChartColorFromObject(?ChartColor $chartColor): self { $this->chartColor = $chartColor; return $this; } /** * Get Underline. */ public function getUnderline(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getUnderline(); } return $this->underline; } /** * Set Underline. * * @param bool|string $underlineStyle \PhpOffice\PhpSpreadsheet\Style\Font underline type * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE, * false equates to UNDERLINE_NONE * * @return $this */ public function setUnderline($underlineStyle): static { if (is_bool($underlineStyle)) { $underlineStyle = ($underlineStyle) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; } elseif ($underlineStyle == '') { $underlineStyle = self::UNDERLINE_NONE; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['underline' => $underlineStyle]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->underline = $underlineStyle; } return $this; } /** * Get Strikethrough. */ public function getStrikethrough(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getStrikethrough(); } return $this->strikethrough; } /** * Set Strikethrough. * * @return $this */ public function setStrikethrough(bool $strikethru): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->strikethrough = $strikethru; } return $this; } /** * Get Color. */ public function getColor(): Color { return $this->color; } /** * Set Color. * * @return $this */ public function setColor(Color $color): static { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } return $this; } private function hashChartColor(?ChartColor $underlineColor): string { if ($underlineColor === null) { return ''; } return $underlineColor->getValue() . $underlineColor->getType() . (string) $underlineColor->getAlpha(); } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->name . $this->size . ($this->bold ? 't' : 'f') . ($this->italic ? 't' : 'f') . ($this->superscript ? 't' : 'f') . ($this->subscript ? 't' : 'f') . $this->underline . ($this->strikethrough ? 't' : 'f') . ($this->autoColor ? 't' : 'f') . $this->color->getHashCode() . $this->scheme . implode( '*', [ $this->latin, $this->eastAsian, $this->complexScript, $this->strikeType, $this->hashChartColor($this->chartColor), $this->hashChartColor($this->underlineColor), (string) $this->baseLine, (string) $this->cap, ] ) . __CLASS__ ); } /** @return mixed[] */ protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'baseLine', $this->getBaseLine()); $this->exportArray2($exportedArray, 'bold', $this->getBold()); $this->exportArray2($exportedArray, 'cap', $this->getCap()); $this->exportArray2($exportedArray, 'chartColor', $this->getChartColor()); $this->exportArray2($exportedArray, 'color', $this->getColor()); $this->exportArray2($exportedArray, 'complexScript', $this->getComplexScript()); $this->exportArray2($exportedArray, 'eastAsian', $this->getEastAsian()); $this->exportArray2($exportedArray, 'italic', $this->getItalic()); $this->exportArray2($exportedArray, 'latin', $this->getLatin()); $this->exportArray2($exportedArray, 'name', $this->getName()); $this->exportArray2($exportedArray, 'scheme', $this->getScheme()); $this->exportArray2($exportedArray, 'size', $this->getSize()); $this->exportArray2($exportedArray, 'strikethrough', $this->getStrikethrough()); $this->exportArray2($exportedArray, 'strikeType', $this->getStrikeType()); $this->exportArray2($exportedArray, 'subscript', $this->getSubscript()); $this->exportArray2($exportedArray, 'superscript', $this->getSuperscript()); $this->exportArray2($exportedArray, 'underline', $this->getUnderline()); $this->exportArray2($exportedArray, 'underlineColor', $this->getUnderlineColor()); $this->exportArray2($exportedArray, 'autoColor', $this->getAutoColor()); return $exportedArray; } public function getScheme(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getScheme(); } return $this->scheme; } public function setScheme(string $scheme): self { if ($scheme === '' || $scheme === 'major' || $scheme === 'minor') { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['scheme' => $scheme]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->scheme = $scheme; } } return $this; } /** * Set capitalization attribute. If not one of the permitted * values (all, small, or none), set it to null. * This will be honored only for the font for chart titles. * None is distinguished from null because null will inherit * the current value, whereas 'none' will override it. */ public function setCap(string $cap): self { $this->cap = in_array($cap, self::VALID_CAPS, true) ? $cap : null; return $this; } public function getCap(): ?string { return $this->cap; } public function setHyperlinkTheme(): self { $this->color->setHyperlinkTheme(); $this->setUnderline(self::UNDERLINE_SINGLE); return $this; } public function setAutoColor(bool $autoColor): self { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['autoColor' => $autoColor]); $this->getActiveSheet() ->getStyle($this->getSelectedCells()) ->applyFromArray($styleArray); } else { $this->autoColor = $autoColor; } return $this; } public function getAutoColor(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getAutoColor(); } return $this->autoColor; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->color = clone $this->color; $this->chartColor = ($this->chartColor === null) ? null : clone $this->chartColor; $this->underlineColor = ($this->underlineColor === null) ? null : clone $this->underlineColor; } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php ================================================ '', // 12-hour suffix 'am/pm' => 'A', // 4-digit year 'e' => 'Y', 'yyyy' => 'Y', // 2-digit year 'yy' => 'y', // first letter of month - no php equivalent 'mmmmm' => 'M', // full month name 'mmmm' => 'F', // short month name 'mmm' => 'M', // mm is minutes if time, but can also be month w/leading zero // so we try to identify times be the inclusion of a : separator in the mask // It isn't perfect, but the best way I know how ':mm' => ':i', 'mm:' => 'i:', // full day of week name 'dddd' => 'l', // short day of week name 'ddd' => 'D', // days leading zero 'dd' => 'd', // days no leading zero 'd' => 'j', // fractional seconds - no php equivalent '.s' => '', ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). */ private const DATE_FORMAT_REPLACEMENTS24 = [ 'hh' => 'H', 'h' => 'G', // month leading zero 'mm' => 'm', // month no leading zero 'm' => 'n', // seconds 'ss' => 's', ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). */ private const DATE_FORMAT_REPLACEMENTS12 = [ 'hh' => 'h', 'h' => 'g', // month leading zero 'mm' => 'm', // month no leading zero 'm' => 'n', // seconds 'ss' => 's', ]; private const HOURS_IN_DAY = 24; private const MINUTES_IN_DAY = 60 * self::HOURS_IN_DAY; private const SECONDS_IN_DAY = 60 * self::MINUTES_IN_DAY; private const INTERVAL_PRECISION = 10; private const INTERVAL_LEADING_ZERO = [ '[hh]', '[mm]', '[ss]', ]; private const INTERVAL_ROUND_PRECISION = [ // hours and minutes truncate '[h]' => self::INTERVAL_PRECISION, '[hh]' => self::INTERVAL_PRECISION, '[m]' => self::INTERVAL_PRECISION, '[mm]' => self::INTERVAL_PRECISION, // seconds round '[s]' => 0, '[ss]' => 0, ]; private const INTERVAL_MULTIPLIER = [ '[h]' => self::HOURS_IN_DAY, '[hh]' => self::HOURS_IN_DAY, '[m]' => self::MINUTES_IN_DAY, '[mm]' => self::MINUTES_IN_DAY, '[s]' => self::SECONDS_IN_DAY, '[ss]' => self::SECONDS_IN_DAY, ]; /** @param float|int|numeric-string $value */ private static function tryInterval(bool &$seekingBracket, string &$block, mixed $value, string $format): void { if ($seekingBracket) { if (str_contains($block, $format)) { $hours = (string) (int) round( self::INTERVAL_MULTIPLIER[$format] * $value, self::INTERVAL_ROUND_PRECISION[$format] ); if (strlen($hours) === 1 && in_array($format, self::INTERVAL_LEADING_ZERO, true)) { $hours = "0$hours"; } $block = str_replace($format, $hours, $block); $seekingBracket = false; } } } /** @param float|int $value value to be formatted */ public static function format(mixed $value, string $format): string { if ($value < 0 && Preg::isMatch('/^\[?[hms]/i', $format)) { return '-' . self::format(-$value, $format); } // strip off first part containing e.g. [$-F800] or [$USD-409] // general syntax: [$-] // language info is in hexadecimal // strip off chinese part like [DBNum1][$-804] $format = Preg::replace('/^(\[DBNum\d\])*(\[\$[^\]]*\])/i', '', $format); // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; // but we don't want to change any quoted strings $format = Preg::replaceCallback('/(?:^|")([^"]*)(?:$|")/', self::setLowerCaseCallback(...), $format); // Only process the non-quoted blocks for date format characters $blocks = explode('"', $format); foreach ($blocks as $key => &$block) { if ($key % 2 == 0) { $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS); if (!strpos($block, 'A')) { // 24-hour time format // when [h]:mm format, the [h] should replace to the hours of the value * 24 $seekingBracket = true; self::tryInterval($seekingBracket, $block, $value, '[h]'); self::tryInterval($seekingBracket, $block, $value, '[hh]'); self::tryInterval($seekingBracket, $block, $value, '[mm]'); self::tryInterval($seekingBracket, $block, $value, '[m]'); self::tryInterval($seekingBracket, $block, $value, '[s]'); self::tryInterval($seekingBracket, $block, $value, '[ss]'); $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS24); } else { // 12-hour time format $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS12); } } } $format = implode('"', $blocks); // escape any quoted characters so that DateTime format() will render them correctly $format = Preg::replaceCallback('/"(.*)"/U', self::escapeQuotesCallback(...), $format); try { $dateObj = Date::excelToDateTimeObject($value); } catch (Throwable) { return StringHelper::convertToString($value); } // If the colon preceding minute had been quoted, as happens in // Excel 2003 XML formats, m will not have been changed to i above. // Change it now. $format = Preg::replace('/\\\:m/', ':i', $format); $microseconds = (int) $dateObj->format('u'); if (str_contains($format, ':s.000')) { $milliseconds = (int) round($microseconds / 1000.0); if ($milliseconds === 1000) { $milliseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.000', ':s.' . sprintf('%03d', $milliseconds), $format); } elseif (str_contains($format, ':s.00')) { $centiseconds = (int) round($microseconds / 10000.0); if ($centiseconds === 100) { $centiseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.00', ':s.' . sprintf('%02d', $centiseconds), $format); } elseif (str_contains($format, ':s.0')) { $deciseconds = (int) round($microseconds / 100000.0); if ($deciseconds === 10) { $deciseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.0', ':s.' . sprintf('%1d', $deciseconds), $format); } else { // no fractional second if ($microseconds >= 500000) { $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); } return $dateObj->format($format); } /** @param array $matches */ private static function setLowercaseCallback(array $matches): string { /** @var string[] $matches */ return mb_strtolower($matches[0]); } /** @param array $matches */ private static function escapeQuotesCallback(array $matches): string { /** @var string[] $matches */ return '\\' . implode('\\', mb_str_split($matches[1], 1, 'UTF-8')); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php ================================================ ' => $value > $comparisonValue, '<' => $value < $comparisonValue, '<=' => $value <= $comparisonValue, '<>' => $value != $comparisonValue, '=' => $value == $comparisonValue, default => $value >= $comparisonValue, }; } /** * @param float|int|numeric-string $value value to be formatted * @param string[] $sections * * @return mixed[] */ private static function splitFormatForSectionSelection(array $sections, mixed $value): array { // Extract the relevant section depending on whether number is positive, negative, or zero? // Text not supported yet. // Here is how the sections apply to various values in Excel: // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] $sectionCount = count($sections); // Colour could be a named colour, or a numeric index entry in the colour-palette $color_regex = '/\[(' . implode('|', Color::NAMED_COLORS) . '|color\s*(\d+))\]/mui'; $cond_regex = '/\[(>|>=|<|<=|=|<>)([+-]?\d+([.]\d+)?)\]/'; $colors = ['', '', '', '', '']; $conditionOperations = ['', '', '', '', '']; $conditionComparisonValues = [0, 0, 0, 0, 0]; for ($idx = 0; $idx < $sectionCount; ++$idx) { if (preg_match($color_regex, $sections[$idx], $matches)) { if (isset($matches[2])) { $colors[$idx] = '#' . BIFF8::lookup((int) $matches[2] + 7)['rgb']; } else { $colors[$idx] = $matches[0]; } $sections[$idx] = (string) preg_replace($color_regex, '', $sections[$idx]); } if (preg_match($cond_regex, $sections[$idx], $matches)) { $conditionOperations[$idx] = $matches[1]; $conditionComparisonValues[$idx] = $matches[2]; $sections[$idx] = (string) preg_replace($cond_regex, '', $sections[$idx]); } } $color = $colors[0]; $format = $sections[0]; $absval = $value; switch ($sectionCount) { case 2: $absval = abs($value + 0); if (!self::splitFormatComparison($value, $conditionOperations[0], $conditionComparisonValues[0], '>=', 0)) { $color = $colors[1]; $format = $sections[1]; } break; case 3: case 4: $absval = abs($value + 0); if (!self::splitFormatComparison($value, $conditionOperations[0], $conditionComparisonValues[0], '>', 0)) { if (self::splitFormatComparison($value, $conditionOperations[1], $conditionComparisonValues[1], '<', 0)) { $color = $colors[1]; $format = $sections[1]; } else { $color = $colors[2]; $format = $sections[2]; } } break; } return [$color, $format, $absval]; } /** * Convert a value in a pre-defined format to a PHP string. * * @param null|array|bool|float|int|RichText|string $value Value to format * @param string $format Format code: see = self::FORMAT_* for predefined values; * or can be any valid MS Excel custom format string * @param null|array|callable $callBack Callback function for additional formatting of string * @param bool $lessFloatPrecision If true, unstyled floats will be converted to a more human-friendly but less computationally accurate value * * @return string Formatted string */ public static function toFormattedString($value, string $format, null|array|callable $callBack = null, bool $lessFloatPrecision = false): string { while (is_array($value)) { $value = array_shift($value); } if (is_bool($value)) { return $value ? Calculation::getTRUE() : Calculation::getFALSE(); } // For now we do not treat strings in sections, although section 4 of a format code affects strings // Process a single block format code containing @ for text substitution $formatx = str_replace('\"', self::QUOTE_REPLACEMENT, $format); if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $formatx) === 1) { if (!str_contains($format, '"')) { return str_replace('@', StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision), $format); } //escape any dollar signs on the string, so they are not replaced with an empty value $value = str_replace( ['$', '"'], ['\$', self::QUOTE_REPLACEMENT], StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision) ); return str_replace( ['"', self::QUOTE_REPLACEMENT], ['', '"'], preg_replace(self::SYMBOL_AT, $value, $formatx) ?? $value ); } // If we have a text value, return it "as is" if (!is_numeric($value)) { return StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision); } // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, // it seems to round numbers to a total of 10 digits. if (($format === NumberFormat::FORMAT_GENERAL) || ($format === NumberFormat::FORMAT_TEXT)) { if (is_float($value) && $lessFloatPrecision) { return self::adjustSeparators((string) $value); } return self::adjustSeparators( StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision) ); } // Ignore square-$-brackets prefix in format string, like "[$-411]ge.m.d", "[$-010419]0%", etc $format = (string) preg_replace('/^\[\$-[^\]]*\]/', '', $format); $format = (string) preg_replace_callback( '/(["])(?:(?=(\\\?))\2.)*?\1/u', fn (array $matches): string => str_replace('.', chr(0x00), $matches[0]), $format ); // Convert any other escaped characters to quoted strings, e.g. (\T to "T") $format = (string) preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format); // Get the sections, there can be up to four sections, separated with a semicolon (but only if not a quoted literal) $sections = preg_split(self::SECTION_SPLIT, $format) ?: []; [$colors, $format, $value] = self::splitFormatForSectionSelection($sections, $value); // In Excel formats, "_" is used to add spacing, // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space /** @var string */ $temp = $format; $format = (string) preg_replace('/_.?/ui', ' ', $temp); // Let's begin inspecting the format and converting the value to a formatted string if ( // Check for date/time characters (not inside quotes) (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format)) // Look out for Currency formats Issue 4124 && !(preg_match('/\[\$[A-Z]{3}\]/miu', $format)) // A date/time with a decimal time shouldn't have a digit placeholder before the decimal point && (preg_match('/[0\?#]\.(?![^\[]*\])/miu', $format) === 0) ) { // datetime format /** @var float|int */ $temp = $value; $value = DateFormatter::format($temp, $format); } else { if (str_starts_with($format, '"') && str_ends_with($format, '"') && substr_count($format, '"') === 2) { $value = substr($format, 1, -1); } elseif (preg_match('/[0#, ]%/', $format)) { // % number format - avoid weird '-0' problem /** @var float */ $temp = $value; $value = PercentageFormatter::format(0 + (float) $temp, $format); } else { /** @var float|int|numeric-string */ $temp = $value; $value = NumberFormatter::format($temp, $format); } } // Additional formatting provided by callback function if (is_callable($callBack)) { $value = $callBack($value, $colors); } /** @var string $value */ return str_replace(chr(0x00), '.', $value); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php ================================================ 0); return [ implode('.', $masks), implode('.', array_reverse($postDecimalMasks)), ]; } private static function processComplexNumberFormatMask(mixed $number, string $mask): string { /** @var string $result */ $result = $number; $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE); if ($maskingBlockCount > 1) { $maskingBlocks = array_reverse($maskingBlocks[0]); $offset = 0; foreach ($maskingBlocks as $block) { $size = strlen($block[0]); $divisor = 10 ** $size; $offset = $block[1]; /** @var float $numberFloat */ $numberFloat = $number; $blockValue = sprintf("%0{$size}d", fmod($numberFloat, $divisor)); $number = floor($numberFloat / $divisor); $mask = substr_replace($mask, $blockValue, $offset, $size); } /** @var string $numberString */ $numberString = $number; if ($number > 0) { $mask = substr_replace($mask, $numberString, $offset, 0); } $result = $mask; } return self::makeString($result); } private static function complexNumberFormatMask(mixed $number, string $mask, bool $splitOnPoint = true): string { /** @var float $numberFloat */ $numberFloat = $number; if ($splitOnPoint) { $masks = explode('.', $mask); if (count($masks) <= 2) { $decmask = $masks[1] ?? ''; $decpos = substr_count($decmask, '0'); $numberFloat = round($numberFloat, $decpos); } } $sign = ($numberFloat < 0.0) ? '-' : ''; $number = self::f2s(abs($numberFloat)); if ($splitOnPoint && str_contains($mask, '.') && str_contains($number, '.')) { $numbers = explode('.', $number); $masks = explode('.', $mask); if (count($masks) > 2) { $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); } /** @var string[] $masks */ $integerPart = self::complexNumberFormatMask($numbers[0], $masks[0], false); $numlen = strlen($numbers[1]); $msklen = strlen($masks[1]); if ($numlen < $msklen) { $numbers[1] .= str_repeat('0', $msklen - $numlen); } $decimalPart = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); $decimalPart = substr($decimalPart, 0, $msklen); return "{$sign}{$integerPart}.{$decimalPart}"; } if (strlen($number) < strlen($mask)) { $number = str_repeat('0', strlen($mask) - strlen($number)) . $number; } $result = self::processComplexNumberFormatMask($number, $mask); return "{$sign}{$result}"; } public static function f2s(float $f): string { return self::floatStringConvertScientific((string) $f); } public static function floatStringConvertScientific(string $s): string { // convert only normalized form of scientific notation: // optional sign, single digit 1-9, // decimal point and digits (allowed to be omitted), // E (e permitted), optional sign, one or more digits if (preg_match('/^([+-])?([1-9])([.]([0-9]+))?[eE]([+-]?[0-9]+)$/', $s, $matches) === 1) { $exponent = (int) $matches[5]; $sign = ($matches[1] === '-') ? '-' : ''; if ($exponent >= 0) { $exponentPlus1 = $exponent + 1; $out = $matches[2] . $matches[4]; $len = strlen($out); if ($len < $exponentPlus1) { $out .= str_repeat('0', $exponentPlus1 - $len); } $out = substr($out, 0, $exponentPlus1) . ((strlen($out) === $exponentPlus1) ? '' : ('.' . substr($out, $exponentPlus1))); $s = "$sign$out"; } else { $s = $sign . '0.' . str_repeat('0', -$exponent - 1) . $matches[2] . $matches[4]; } } return $s; } /** @param string[] $matches */ private static function formatStraightNumericValue(mixed $value, string $format, array $matches, bool $useThousands): string { /** @var float $valueFloat */ $valueFloat = $value; $left = $matches[1]; $dec = $matches[2]; $right = $matches[3]; // minimum width of formatted number (including dot) $minWidth = strlen($left) + strlen($dec) + strlen($right); if ($useThousands) { $value = number_format( $valueFloat, strlen($right), StringHelper::getDecimalSeparator(), StringHelper::getThousandsSeparator() ); return self::pregReplace(self::NUMBER_REGEX, $value, $format); } if (preg_match('/[0#]E[+-]0/i', $format)) { // Scientific format $decimals = strlen($right); $size = $decimals + 3; return sprintf("%{$size}.{$decimals}E", $valueFloat); } if (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { if ($valueFloat == floor($valueFloat) && substr_count($format, '.') === 1) { $value *= 10 ** strlen(explode('.', $format)[1]); //* @phpstan-ignore-line } $result = self::complexNumberFormatMask($value, $format); if (str_contains($result, 'E')) { // This is a hack and doesn't match Excel. // It will, at least, be an accurate representation, // even if formatted incorrectly. // This is needed for absolute values >=1E18. $result = self::f2s($valueFloat); } return $result; } $sprintf_pattern = "%0$minWidth." . strlen($right) . 'F'; /** @var float $valueFloat */ $valueFloat = $value; $value = self::adjustSeparators(sprintf($sprintf_pattern, round($valueFloat, strlen($right)))); return self::pregReplace(self::NUMBER_REGEX, $value, $format); } /** @param float|int|numeric-string $value value to be formatted */ public static function format(mixed $value, string $format): string { // The "_" in this string has already been stripped out, // so this test is never true. Furthermore, testing // on Excel shows this format uses Euro symbol, not "EUR". // if ($format === NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE) { // return 'EUR ' . sprintf('%1.2f', $value); // } $baseFormat = $format; $useThousands = self::areThousandsRequired($format); $scale = self::scaleThousandsMillions($format); if (preg_match('/[#\?0]?.*[#\?0]\/(\?+|\d+|#)/', $format)) { // It's a dirty hack; but replace # and 0 digit placeholders with ? $format = (string) preg_replace('/[#0]+\//', '?/', $format); $format = (string) preg_replace('/\/[#0]+/', '/?', $format); $value = FractionFormatter::format($value, $format); } else { // Handle the number itself // scale number $value = $value / $scale; $paddingPlaceholder = (str_contains($format, '?')); // Replace # or ? with 0 $format = self::pregReplace('/[\#\?](?=(?:[^"]*"[^"]*")*[^"]*\Z)/', '0', $format); // Remove locale code [$-###] for an LCID $format = self::pregReplace('/\[\$\-.*\]/', '', $format); $n = '/\[[^\]]+\]/'; $m = self::pregReplace($n, '', $format); // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols $format = self::makeString(str_replace(['"', '*'], '', $format)); if (preg_match(self::NUMBER_REGEX, $m, $matches)) { // There are placeholders for digits, so inject digits from the value into the mask $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands); if ($paddingPlaceholder === true) { $value = self::padValue($value, $baseFormat); } } elseif ($format !== NumberFormat::FORMAT_GENERAL) { // Yes, I know that this is basically just a hack; // if there's no placeholders for digits, just return the format mask "as is" $value = self::makeString(str_replace('?', '', $format)); } } if (preg_match('/\[\$(.*)\]/u', $format, $m)) { // Currency or Accounting $value = preg_replace('/-0+(( |\xc2\xa0))?\[/', '- [', (string) $value) ?? $value; $currencyCode = $m[1]; [$currencyCode] = explode('-', $currencyCode); if ($currencyCode == '') { $currencyCode = StringHelper::getCurrencyCode(); } $value = self::pregReplace('/\[\$([^\]]*)\]/u', $currencyCode, (string) $value); } if ( (str_contains((string) $value, '0.')) && ((str_contains($baseFormat, '#.')) || (str_contains($baseFormat, '?.'))) ) { $value = preg_replace('/(\b)0\.|([^\d])0\./', '${2}.', (string) $value); } return (string) $value; } /** @param mixed[]|string $value */ private static function makeString(array|string $value): string { return is_array($value) ? '' : "$value"; } private static function pregReplace(string $pattern, string $replacement, string $subject): string { return self::makeString(preg_replace($pattern, $replacement, $subject) ?? ''); } public static function padValue(string $value, string $baseFormat): string { $preDecimal = $postDecimal = ''; $pregArray = preg_split('/\.(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu', $baseFormat . '.?'); if (is_array($pregArray)) { $preDecimal = $pregArray[0]; $postDecimal = $pregArray[1] ?? ''; } $length = strlen($value); if (str_contains($postDecimal, '?')) { $value = str_pad(rtrim($value, '0. '), $length, ' ', STR_PAD_RIGHT); } if (str_contains($preDecimal, '?')) { $value = str_pad(ltrim($value, '0, '), $length, ' ', STR_PAD_LEFT); } return $value; } /** * Find out if we need thousands separator * This is indicated by a comma enclosed by a digit placeholders: #, 0 or ? */ public static function areThousandsRequired(string &$format): bool { $useThousands = (bool) preg_match('/([#\?0]),([#\?0])/', $format); if ($useThousands) { $format = self::pregReplace('/([#\?0]),([#\?0])/', '${1}${2}', $format); } return $useThousands; } /** * Scale thousands, millions,... * This is indicated by a number of commas after a digit placeholder: #, or 0.0,, or ?,. */ public static function scaleThousandsMillions(string &$format): int { $scale = 1; // same as no scale if (preg_match('/(#|0|\?)(,+)/', $format, $matches)) { $scale = 1000 ** strlen($matches[2]); // strip the commas $format = self::pregReplace('/([#\?0]),+/', '${1}', $format); } return $scale; } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php ================================================ 0); $replacement = "0{$wholePartSize}.{$decimalPartSize}"; $mask = (string) preg_replace('/[#0,]+\.?[?#0,]*/ui', "%{$replacement}F{$placeHolders}", $format); /** @var float $valueFloat */ $valueFloat = $value; return self::adjustSeparators(sprintf($mask, round($valueFloat, $decimalPartSize))); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/Accounting.php ================================================ fullLocale, NumberFormatter::CURRENCY_ACCOUNTING); $mask = $formatter->format($this->stripLeadingRLM); if ($this->decimals === 0) { $mask = (string) preg_replace('/\.0+/miu', '', $mask); } return str_replace('¤', $this->formatCurrencyCode(), $mask); } public static function icuVersion(): float { [$major, $minor] = explode('.', INTL_ICU_VERSION); return (float) "{$major}.{$minor}"; } private function formatCurrencyCode(): string { if ($this->locale === null) { return $this->currencyCode . '*'; } return "[\${$this->currencyCode}-{$this->locale}]"; } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/Currency.php ================================================ setCurrencyCode($currencyCode); $this->setThousandsSeparator($thousandsSeparator); $this->setDecimals($decimals); $this->setCurrencySymbolPosition($currencySymbolPosition); $this->setCurrencySymbolSpacing($currencySymbolSpacing); $this->setLocale($locale); $this->stripLeadingRLM = $stripLeadingRLM; $this->negative = $negative; } public function setCurrencyCode(string $currencyCode): void { $this->currencyCode = $currencyCode; } public function setCurrencySymbolPosition(bool $currencySymbolPosition = self::LEADING_SYMBOL): void { $this->currencySymbolPosition = $currencySymbolPosition; } public function setCurrencySymbolSpacing(bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING): void { $this->currencySymbolSpacing = $currencySymbolSpacing; } public function setStripLeadingRLM(bool $stripLeadingRLM): void { $this->stripLeadingRLM = $stripLeadingRLM; } public function setNegative(CurrencyNegative $negative): void { $this->negative = $negative; } protected function getLocaleFormat(): string { $formatter = new Locale($this->fullLocale, NumberFormatter::CURRENCY); $mask = $formatter->format($this->stripLeadingRLM); if ($this->decimals === 0) { $mask = (string) preg_replace('/\.0+/miu', '', $mask); } return str_replace('¤', $this->formatCurrencyCode(), $mask); } private function formatCurrencyCode(): string { if ($this->locale === null) { return $this->currencyCode; } return "[\${$this->currencyCode}-{$this->locale}]"; } public function format(): string { if ($this->localeFormat !== null) { return $this->localeFormat; } $symbolWithSpacing = $this->overrideSpacing ?? ($this->currencySymbolSpacing === self::SYMBOL_WITH_SPACING); $negative = $this->overrideNegative ?? $this->negative; // format if positive $format = '_('; if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { $format .= '"' . $this->currencyCode . '"'; if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } if ($symbolWithSpacing) { $format .= '*' . $this->spaceOrNbsp; } } $format .= $this->thousandsSeparator ? '#,##0' : '0'; if ($this->decimals > 0) { $format .= '.' . str_repeat('0', $this->decimals); } if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { if ($symbolWithSpacing) { $format .= $this->spaceOrNbsp; } elseif (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } $format .= '[$' . $this->currencyCode . ']'; } $format .= '_)'; // format if negative $format .= ';_('; $format .= $negative->color(); $negativeStart = $negative->start(); if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { if ($negativeStart === '-' && !$symbolWithSpacing) { $format .= $negativeStart; } $format .= '"' . $this->currencyCode . '"'; if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } if ($symbolWithSpacing) { $format .= '*' . $this->spaceOrNbsp; } if ($negativeStart === '\(' || ($symbolWithSpacing && $negativeStart === '-')) { $format .= $negativeStart; } } else { $format .= $negative->start(); } $format .= $this->thousandsSeparator ? '#,##0' : '0'; if ($this->decimals > 0) { $format .= '.' . str_repeat('0', $this->decimals); } $format .= $negative->end(); if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { if ($symbolWithSpacing) { // Do nothing - I can't figure out how to get // everything to align if I put any kind of space here. //$format .= "\u{2009}"; } elseif (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } $format .= '[$' . $this->currencyCode . ']'; } if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { $format .= '_)'; } elseif ($symbolWithSpacing && $negativeStart === '-') { $format .= ' '; } // format if zero $format .= ';_('; if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { $format .= '"' . $this->currencyCode . '"'; } if ($symbolWithSpacing) { if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { $format .= '*' . $this->spaceOrNbsp; } $format .= '"-"'; if ($this->decimals > 0) { $format .= str_repeat('?', $this->decimals); } } else { if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } $format .= '0'; if ($this->decimals > 0) { $format .= '.' . str_repeat('0', $this->decimals); } } if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { if ($symbolWithSpacing) { $format .= $this->spaceOrNbsp; } $format .= '[$' . $this->currencyCode . ']'; } $format .= '_)'; // format if text $format .= ';_(@_)'; return $format; } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/CurrencyNegative.php ================================================ '-', self::parentheses, self::redParentheses => '\(', }; } public function end(): string { return match ($this) { self::minus, self::redMinus => '', self::parentheses, self::redParentheses => '\)', }; } public function color(): string { return match ($this) { self::redParentheses, self::redMinus => '[Red]', self::parentheses, self::minus => '', }; } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/Date.php ================================================ */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; /** * @param null|array|string $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_DASH, string|null ...$formatBlocks) { $separators ??= self::SEPARATOR_DASH; $formatBlocks = (count($formatBlocks) === 0) ? self::DATE_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(string $value): string { // Any date masking codes are returned as lower case values if (in_array(mb_strtolower($value), self::DATE_BLOCKS, true)) { return mb_strtolower($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTime.php ================================================ */ protected array $separators; /** * @var array */ protected array $formatBlocks; /** * @param null|string|string[] $separators * If you want to use only a single format block, then pass a null as the separator argument * @param DateTimeWizard|string ...$formatBlocks */ public function __construct($separators, ...$formatBlocks) { $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(DateTimeWizard|string $value): string { // Any date masking codes are returned as lower case values if ($value instanceof DateTimeWizard) { return $value->__toString(); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTimeWizard.php ================================================ = "; /** * @param array $separators * * @return array */ protected function padSeparatorArray(array $separators, int $count): array { $lastSeparator = (string) array_pop($separators); return $separators + array_fill(0, $count, $lastSeparator); } protected function escapeSingleCharacter(string $value): string { if (str_contains(self::NO_ESCAPING_NEEDED, $value)) { return $value; } return "\\{$value}"; } protected function wrapLiteral(string $value): string { if (mb_strlen($value, 'UTF-8') === 1) { return $this->escapeSingleCharacter($value); } // Wrap any other string literals in quotes, so that they're clearly defined as string literals return '"' . str_replace('"', '""', $value) . '"'; } protected function intersperse(string $formatBlock, ?string $separator): string { return "{$formatBlock}{$separator}"; } public function __toString(): string { return $this->format(); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/Duration.php ================================================ self::DAYS_DURATION, self::HOURS_DURATION => self::HOURS_SHORT, self::MINUTES_DURATION => self::MINUTES_LONG, self::SECONDS_DURATION => self::SECONDS_LONG, ]; protected const DURATION_DEFAULTS = [ self::HOURS_LONG => self::HOURS_DURATION, self::HOURS_SHORT => self::HOURS_DURATION, self::MINUTES_LONG => self::MINUTES_DURATION, self::MINUTES_SHORT => self::MINUTES_DURATION, self::SECONDS_LONG => self::SECONDS_DURATION, self::SECONDS_SHORT => self::SECONDS_DURATION, ]; public const SEPARATOR_COLON = ':'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; public const DURATION_DEFAULT = [ self::HOURS_DURATION, self::MINUTES_LONG, self::SECONDS_LONG, ]; /** * @var array */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; protected bool $durationIsSet = false; /** * @param null|string|string[] $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_COLON, string ...$formatBlocks) { $separators ??= self::SEPARATOR_COLON; $formatBlocks = (count($formatBlocks) === 0) ? self::DURATION_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); if ($this->durationIsSet === false) { // We need at least one duration mask, so if none has been set we change the first mask element // to a duration. $this->formatBlocks[0] = self::DURATION_DEFAULTS[mb_strtolower($this->formatBlocks[0])]; } } private function mapFormatBlocks(string $value): string { // Any duration masking codes are returned as lower case values if (in_array(mb_strtolower($value), self::DURATION_BLOCKS, true)) { if (array_key_exists(mb_strtolower($value), self::DURATION_MASKS)) { if ($this->durationIsSet) { // We should only have a single duration mask, the first defined in the mask set, // so convert any additional duration masks to standard time masks. $value = self::DURATION_MASKS[mb_strtolower($value)]; } $this->durationIsSet = true; } return mb_strtolower($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } ================================================ FILE: src/PhpSpreadsheet/Style/NumberFormat/Wizard/Locale.php ================================================ [a-z]{2})([-_](?P'; $scriptSingle = new RichText(); $scriptSingle->createText($scriptTextSingle); return [ 'single line plain text' => [$plainSingle, '
' . 'I am comment.
' . PHP_EOL . 'Comment'], 'multi-line plain text' => [$plainMulti, '
' . 'I am
' . PHP_EOL . 'multi-line
' . PHP_EOL . 'comment.
' . PHP_EOL . 'Comment'], 'single line simple rich text' => [$richSingle, '
' . "I am comment.
" . PHP_EOL . 'Comment'], 'multi-line simple rich text' => [$richMultiSimple, '
' . "I am
" . PHP_EOL . 'multi-line
' . PHP_EOL . 'comment.
' . PHP_EOL . 'Comment'], 'multi-line mixed rich text' => [$richMultiMixed, '
I am
' . PHP_EOL . "multi-line
" . PHP_EOL . 'comment!
' . PHP_EOL . 'Comment'], 'script single' => [$scriptSingle, '
' . 'I am <script>alert("Hello")</script>
' . PHP_EOL . 'Comment'], ]; } #[DataProvider('providerCommentRichText')] public function testComments(RichText $richText, string $expected): void { $spreadsheet = new Spreadsheet(); $spreadsheet->getActiveSheet() ->getCell('A1') ->setValue('Comment'); $spreadsheet->getActiveSheet() ->getComment('A1') ->setText($richText); $writer = new Html($spreadsheet); $writer->setLineEnding(PHP_EOL); $output = $writer->generateHtmlAll(); self::assertStringContainsString($expected, $output); $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $actual = $reloadedSpreadsheet->getActiveSheet()->getComment('A1')->getText()->getPlainText(); self::assertSame($richText->getPlainText(), $actual); $reloadedSpreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/HtmlConditionalFormattingTest.php ================================================ load($file); $writer = new HtmlWriter($spreadsheet); $writer->setConditionalFormatting(true); $this->data = $writer->generateHtmlAll(); $spreadsheet->disconnectWorksheets(); } private function extractCell(string $coordinate): string { [$column, $row] = Coordinate::indexesFromString($coordinate); --$column; --$row; // extract row into $matches $match = preg_match('~~s', $this->data, $matches); if ($match !== 1) { return 'unable to match row'; } $rowData = $matches[0]; // extract cell into $matches $match = preg_match('~Jan<', 'no conditional styling for B1'], ['F2', 'background-color:#C6EFCE;">120<', 'conditional style for F2'], ['H2', 'background-color:#FFEB9C;">90<', 'conditional style for H2'], ['F3', 'background-color:#C6EFCE;">70<', 'conditional style for cell F3'], ['H3', 'background-color:#FFEB9C;">60<', 'conditional style for cell H3'], ['F4', 'background-color:#C6EFCE;">1<', 'conditional style for cell F4'], ['L4', 'background-color:#FFC7CE;">5<', 'conditional style for cell L4'], ['F5', 'class="column5 style1 n">0<', 'no conditional styling for F5'], ]; foreach ($expectedMatches as $expected) { [$coordinate, $expectedString, $message] = $expected; $string = $this->extractCell($coordinate); self::assertStringContainsString($expectedString, $string, $message); } } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/HtmlDifferentConditionalFormattingsTest.php ================================================ load($file); $writer = new HtmlWriter($spreadsheet); $writer->setConditionalFormatting(true); $this->data = $writer->generateHtmlAll(); $spreadsheet->disconnectWorksheets(); } private function extractCell(string $coordinate): string { [$column, $row] = Coordinate::indexesFromString($coordinate); --$column; --$row; // extract row into $matches $match = preg_match('~~s', $this->data, $matches); if ($match !== 1) { return 'unable to match row'; } $rowData = $matches[0]; // extract cell into $matches $match = preg_match('~1<', 'A1 equals hit'], ['B1', 'class="column1 style1 n">2<', 'B1 equals miss'], ['E1', 'background-color:#B7E1CD;">1<', 'E1 equals horizontal reference hit'], ['F1', 'class="column5 style1 n">2<', 'F1 equals horizontal reference miss'], ['G1', 'class="column6 style1 n">3<', 'G1 equals horizontal reference miss'], ['A2', 'background-color:#B7E1CD;">terve<', 'A2 text contains hit'], ['B2', 'class="column1 style1 s">moi<', 'B2 text contains miss'], ['A3', 'background-color:#B7E1CD;">terve<', 'A3 text does not contain hit'], ['B3', 'class="column1 style1 s">moi<', 'B2 text does not contain miss'], ['A4', 'background-color:#B7E1CD;">terve<', 'A4 text starts with hit'], ['B4', 'class="column1 style1 s">moi<', 'B2 text starts with miss'], ['A5', 'background-color:#B7E1CD;">terve<', 'A5 text ends with hit'], ['B5', 'class="column1 style1 s">moi<', 'B5 text ends with miss'], ['A6', 'background-color:#B7E1CD;">2025/01/01<', 'A6 date after hit'], ['B6', 'class="column1 style2 n">2020/01/01<', 'B6 date after miss'], ['A7', 'background-color:#B7E1CD;">terve vaan<', 'A7 text contains hit'], ['B7', 'class="column1 style1 s">moi<', 'B7 text contains miss'], ['A8', 'background-color:#B7E1CD;">terve<', 'A8 text does not contain hit'], ['B8', 'class="column1 style1 s">terve vaan<', 'B2 does not contain miss'], ['A9', 'background-color:#B7E1CD;">#DIV/0!<', 'A10 own formula is error hit'], ['B9', 'class="column1 style1 s">moi<', 'B9 own formula is error miss'], ['A10', 'background-color:#B7E1CD;">moi<', 'A10 own formula is not error hit'], ['B10', 'class="column1 style3 s">#DIV/0!<', 'B10 own formula is not error miss'], ['A11', 'background-color:#B7E1CD;">terve<', 'A11 own formula count instances of cell on line and hit when more than one hit'], ['B11', 'background-color:#B7E1CD;">terve<', 'B11 own formula count instances of cell on line and hit when more than one hit'], ['C11', 'class="column2 style1 s">moi<', 'C11 own formula count instances of cell on line and hit when more than one miss'], ['A12', 'background-color:#B7E1CD;">moi<', 'A12 own formula count instances of cell on line and hit when at most 1 hit'], ['B12', 'class="column1 style1 s">terve<', 'B12 own formula count instances of cell on line and hit when at most 1 miss'], ['C12', 'class="column2 style1 s">terve<', 'C11 own formula count instances of cell on line and hit when at most 1 miss'], ['A13', 'background-color:#B7E1CD;">12<', 'A13 own formula self reference hit'], ['B13', 'class="column1 style1 n">10<', 'B13 own formula self reference miss'], ['A14', 'background-color:#B7E1CD;">10<', 'A14 multiple conditional hits'], ['B14', 'class="column1 style1 n">1<', 'B14 multiple conditionals miss'], ['F7', 'background-color:#B7E1CD;">1<', 'F7 equals vertical reference hit'], ['F8', 'class="column5 style1 n">2<', 'F8 equals vertical reference miss'], ['F9', 'class="column5 style1 n">3<', 'F9 equals vertical reference miss'], ['F10', 'class="column5 style1 n">4<', 'F10 equals vertical reference miss'], ]; foreach ($expectedMatches as $expected) { [$coordinate, $expectedString, $message] = $expected; $string = $this->extractCell($coordinate); self::assertStringContainsString($expectedString, $string, $message); } } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/HtmlExtend2.php ================================================ fileHandle) && self::$alwaysFalse; } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/HtmlNumberFormatTest.php ================================================ getActiveSheet(); $sheet->setCellValue('A1', -50); $sheet->setCellValue('A2', 3000); $sheet->setCellValue('A3', 0); $sheet->setCellValue('A4', '
'); $fmt = '[Blue]$#,##0;[Red]$#,##0;$#,##0'; $sheet->getStyle('A1:A4')->getNumberFormat()->setFormatCode($fmt); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tabl = $divs->item(0)?->getElementsByTagName('table'); $tbod = $tabl?->item(0)?->getElementsByTagName('tbody'); $rows = $tbod?->item(0)?->getElementsByTagName('tr'); self::assertCount(4, $rows); $tds = $rows?->item(0)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(1, $spans); $style = $spans?->item(0)?->getAttribute('style'); self::assertSame(1, preg_match('/color:red/', "$style")); self::assertSame('$50', $spans?->item(0)?->textContent); $tds = $rows?->item(1)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(1, $spans); $style = $spans?->item(0)?->getAttribute('style'); self::assertSame(1, preg_match('/color:blue/', "$style")); self::assertSame('$3,000', $spans?->item(0)?->textContent); $tds = $rows?->item(2)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(0, $spans); self::assertSame('$0', $tds?->item(0)?->textContent); $tds = $rows?->item(3)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(0, $spans); self::assertEquals('
', $tds?->item(0)?->textContent); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } public function testColorNumberFormatComplex(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', -50); $sheet->setCellValue('A2', 3000.75); $sheet->setCellValue('A3', 0); $sheet->setCellValue('A4', 3000.25); $fmt = '[Blue][>=3000.5]$#,##0.00;[Red][<0]$#,##0.00;$#,##0.00'; $sheet->getStyle('A1:A4')->getNumberFormat()->setFormatCode($fmt); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tabl = $divs->item(0)?->getElementsByTagName('table'); $tbod = $tabl?->item(0)?->getElementsByTagName('tbody'); $rows = $tbod?->item(0)?->getElementsByTagName('tr'); self::assertCount(4, $rows); $tds = $rows?->item(0)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(1, $spans); $style = $spans?->item(0)?->getAttribute('style'); self::assertSame(1, preg_match('/color:red/', "$style")); self::assertSame('$50.00', $spans?->item(0)?->textContent); $tds = $rows?->item(1)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(1, $spans); $style = $spans?->item(0)?->getAttribute('style'); self::assertSame(1, preg_match('/color:blue/', "$style")); self::assertSame('$3,000.75', $spans?->item(0)?->textContent); $tds = $rows?->item(2)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(0, $spans); self::assertSame('$0.00', $tds?->item(0)?->textContent); $tds = $rows?->item(3)?->getElementsByTagName('td'); self::assertCount(1, $tds); $spans = $tds?->item(0)?->getElementsByTagName('span'); self::assertCount(0, $spans); self::assertSame('$3,000.25', $tds?->item(0)?->textContent); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } #[DataProvider('numberFormatProvider')] public function testFormatValueWithMask(mixed $expectedResult, mixed $val, string $fmt): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->getCell('A1')->setValue($val)->getStyle()->getNumberFormat()->setFormatCode($fmt); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); $html = str_replace('> <', '><', $html); // clear empty cells $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tabl = $divs->item(0)?->getElementsByTagName('table'); $tbod = $tabl?->item(0)?->getElementsByTagName('tbody'); $rows = $tbod?->item(0)?->getElementsByTagName('tr'); $tds = $rows?->item(0)?->getElementsByTagName('td'); $nbsp = html_entity_decode(' ', Settings::htmlEntityFlags()); self::assertEquals($expectedResult, str_replace($nbsp, ' ', (string) $tds?->item(0)?->textContent)); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } /** @return mixed[] */ public static function numberFormatProvider(): array { /** @var mixed[] */ $retVal = require __DIR__ . '/../../../data/Style/NumberFormat.php'; return $retVal; } #[DataProvider('numberFormatDatesProvider')] public function testFormatValueWithMaskDate(mixed $expectedResult, mixed $val, string $fmt): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->getCell('A1')->setValue($val)->getStyle()->getNumberFormat()->setFormatCode($fmt); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tabl = $divs->item(0)?->getElementsByTagName('table'); $tbod = $tabl?->item(0)?->getElementsByTagName('tbody'); $rows = $tbod?->item(0)?->getElementsByTagName('tr'); $tds = $rows?->item(0)?->getElementsByTagName('td'); $nbsp = html_entity_decode(' ', Settings::htmlEntityFlags()); self::assertSame($expectedResult, str_replace($nbsp, ' ', (string) $tds?->item(0)?->textContent)); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } /** @return mixed[] */ public static function numberFormatDatesProvider(): array { /** @var mixed[] */ $retVal = require __DIR__ . '/../../../data/Style/NumberFormatDates.php'; return $retVal; } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/HtmlTableFormatTest.php ================================================ ~s', $this->data, $matches); if ($match !== 1) { return 'unable to match row'; } $rowData = $matches[0]; // extract cell into $matches $match = preg_match('~Sep<', 'table style for header row cell J1'], ['J2', 'background-color:#C0E4F5;">110<', 'table style for cell J2'], ['I3', 'background-color:#82CAEB;">70<', 'table style for cell I3'], ['J3', 'background-color:#82CAEB;">70<', 'table style for cell J3'], // as conditional calculations are off ['K3', 'background-color:#82CAEB;">70<', 'table style for cell K3'], ['J4', 'background-color:#C0E4F5;">1<', 'table style for cell J4'], ['J5', 'background-color:#82CAEB;">1<', 'table style for cell J5'], ]; foreach ($expectedMatches as $expected) { [$coordinate, $expectedString, $message] = $expected; $string = $this->extractCell($coordinate); self::assertStringContainsString($expectedString, $string, $message); } $spreadsheet->disconnectWorksheets(); } public function testBuiltinApplied(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $dataArray = [ ['Year', 'Quarter', 'Country', 'Sales'], ['2010', 'Q1', 'United States', 790], ['2010', 'Q2', 'United States', 730], ['2010', 'Q3', 'United States', 860], ['2010', 'Q4', 'United States', 850], ]; $sheet->fromArray($dataArray); $table = new Table('A1:D5', 'Sales_Data'); $tableStyle = new TableStyle(); $tableStyle->setTheme(TableStyle::TABLE_STYLE_MEDIUM2); $tableStyle->setShowRowStripes(true); $tableStyle->setShowColumnStripes(true); $tableStyle->setShowFirstColumn(true); $tableStyle->setShowLastColumn(true); $table->setStyle($tableStyle); $sheet->addTable($table); $writer = new HtmlWriter($spreadsheet); $writer->setTableFormats(true); // format all tables using a default style for unstyled $this->data = $writer->generateHtmlAll(); $expectedMatches = [ ['A1', 'Year', 'table style for header row cell A1'], ['B2', 'Q1', 'table style for cell B2'], ['C3', 'United States', 'table style for cell C3'], ]; foreach ($expectedMatches as $expected) { [$coordinate, $expectedString, $message] = $expected; $string = $this->extractCell($coordinate); self::assertStringContainsString($expectedString, $string, $message); } $spreadsheet->disconnectWorksheets(); } public function testBuiltinNotApplied(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $dataArray = [ ['Year', 'Quarter', 'Country', 'Sales'], ['2010', 'Q1', 'United States', 790], ['2010', 'Q2', 'United States', 730], ['2010', 'Q3', 'United States', 860], ['2010', 'Q4', 'United States', 850], ]; $sheet->fromArray($dataArray); $table = new Table('A1:D5', 'Sales_Data'); $tableStyle = new TableStyle(); $tableStyle->setTheme(TableStyle::TABLE_STYLE_MEDIUM2); $tableStyle->setShowRowStripes(true); $tableStyle->setShowColumnStripes(true); $tableStyle->setShowFirstColumn(true); $tableStyle->setShowLastColumn(true); $table->setStyle($tableStyle); $sheet->addTable($table); $writer = new HtmlWriter($spreadsheet); $writer->setTableFormats(true, false); // format styled tables but not unstyled $this->data = $writer->generateHtmlAll(); $expectedMatches = [ ['A1', 'Year', 'table style for header row cell A1'], ['B2', 'Q1', 'table style for cell B2'], ['C3', 'United States', 'table style for cell C3'], ]; foreach ($expectedMatches as $expected) { [$coordinate, $expectedString, $message] = $expected; $string = $this->extractCell($coordinate); self::assertStringContainsString($expectedString, $string, $message); } $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/HtmlTableFormatWithConditionalTest.php ================================================ ~s', $this->data, $matches); if ($match !== 1) { return 'unable to match row'; } $rowData = $matches[0]; // extract cell into $matches $match = preg_match('~Sep<', 'table style for header row cell J1'], ['J2', 'background-color:#C0E4F5;">110<', 'table style for cell J2'], ['I3', 'background-color:#82CAEB;">70<', 'table style for cell I3'], ['J3', 'background-color:#B7E1CD;">70<', 'conditional style for cell J3'], // as conditional calculations are on ['K3', 'background-color:#82CAEB;">70<', 'table style for cell K3'], ['J4', 'background-color:#C0E4F5;">1<', 'table style for cell J4'], ['J5', 'background-color:#82CAEB;">1<', 'table style for cell J5'], ]; foreach ($expectedMatches as $expected) { [$coordinate, $expectedString, $message] = $expected; $string = $this->extractCell($coordinate); self::assertStringContainsString($expectedString, $string, $message); } } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/ImageCopyTest.php ================================================ xlsxFile !== '') { unlink($this->xlsxFile); $this->xlsxFile = ''; } } public function testImageCopyXls(): void { $file = 'samples/templates/27template.xls'; $reader = new XlsReader(); $reloadedSpreadsheet = $reader->load($file); $writer = new Html($reloadedSpreadsheet); $writer->writeAllSheets(); self::assertFalse($writer->getEmbedImages()); $html = $writer->generateHTMLAll(); self::assertSame(4, substr_count($html, 'writeAndReload($reloadedSpreadsheet, 'Html'); $reloadedSpreadsheet->disconnectWorksheets(); } public function testImageCopyXlsx(): void { $file = 'samples/templates/27template.xls'; $reader = new XlsReader(); $spreadsheet = $reader->load($file); $this->xlsxFile = File::temporaryFilename(); $writer = new XlsxWriter($spreadsheet); $writer->save($this->xlsxFile); $spreadsheet->disconnectWorksheets(); $reader2 = new XlsxReader(); $reloadedSpreadsheet = $reader2->load($this->xlsxFile); $writer = new Html($reloadedSpreadsheet); $writer->writeAllSheets(); self::assertFalse($writer->getEmbedImages()); $html = $writer->generateHTMLAll(); self::assertSame(4, substr_count($html, 'writeAndReload($reloadedSpreadsheet, 'Html'); $reloadedSpreadsheet->disconnectWorksheets(); } public function testSimulateFailedClose(): void { $this->expectException(WriterException::class); $this->expectExceptionMessage('Could not close file '); $file = 'samples/templates/27template.xls'; $reader = new XlsReader(); $spreadsheet = $reader->load($file); $this->xlsxFile = File::temporaryFilename(); $writer = new HtmlExtend2($spreadsheet); $writer->save($this->xlsxFile); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/ImageEmbedTest.php ================================================ getActiveSheet(); $drawing = new Drawing(); $drawing->setName('Not an image'); $drawing->setDescription('Non-image'); $drawing->setPath(__FILE__, false); $drawing->setCoordinates('A1'); $drawing->setCoordinates2('E4'); $drawing->setWorksheet($sheet); $drawing = new Drawing(); $drawing->setName('Blue Square'); $drawing->setPath('tests/data/Writer/XLSX/blue_square.png'); $drawing->setCoordinates('A5'); $drawing->setCoordinates2('E8'); $drawing->setWorksheet($sheet); $writer = new HtmlWriter($spreadsheet); $writer->setEmbedImages(true); $html = $writer->generateHTMLAll(); self::assertSame(1, substr_count($html, 'disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/ImagesRootTest.php ================================================ curdir = $curdir; } } protected function tearDown(): void { chdir($this->curdir); } public function testImagesRoot(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $drawing->setName('Test'); $drawing->setDescription('Test'); $root = 'http://www.example.com'; $newdir = __DIR__ . '/../../../data/Reader/HTML'; $stub = 'image.jpg'; $imagePath = "./$stub"; chdir($newdir); self::assertFileExists($imagePath); $drawing->setPath($imagePath); $desc = 'Test tag'; $drawing->setDescription($desc); $drawing->setHeight(36); $drawing->setWorksheet($spreadsheet->getActiveSheet()); $drawing->setCoordinates('A1'); $sheet->setCellValue('A2', 'Image Above?'); $writer = new Html($spreadsheet); $writer->setImagesRoot($root); $html = $writer->generateHTMLAll(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tabl = $divs->item(0)?->getElementsByTagName('table'); $tbod = $tabl?->item(0)?->getElementsByTagName('tbody'); $rows = $tbod?->item(0)?->getElementsByTagName('tr'); self::assertCount(2, $rows); $tds = $rows?->item(0)?->getElementsByTagName('td'); self::assertCount(1, $tds); $img = $tds?->item(0)?->getElementsByTagName('img'); self::assertCount(1, $img); self::assertSame("$root/$stub", $img?->item(0)?->getAttribute('src')); self::assertSame($desc, $img->item(0)->getAttribute('alt')); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/InvalidFileNameTest.php ================================================ expectException(WriterException::class); $spreadsheet = new Spreadsheet(); $spreadsheet->getActiveSheet()->getCell('A1')->setValue('Cell 1'); $writer = new Html($spreadsheet); $writer->save(''); } public function testEmptyFileNamePdf(): void { $this->expectException(WriterException::class); $spreadsheet = new Spreadsheet(); $spreadsheet->getActiveSheet()->getCell('A1')->setValue('Cell 1'); $writer = new Mpdf($spreadsheet); $writer->save(''); } public function testNotEmptyTempdirNamePdf(): void { $spreadsheet = new Spreadsheet(); $spreadsheet->getActiveSheet()->getCell('A1')->setValue('Cell 1'); $writer = new Mpdf($spreadsheet); $writer->setFont('Helvetica'); self::assertEquals('Helvetica', $writer->getFont()); $writer->setPaperSize(PageSetup::PAPERSIZE_LEDGER); self::assertEquals($writer->getPaperSize(), PageSetup::PAPERSIZE_LEDGER); self::assertEquals(File::sysGetTempDir() . '/phpsppdf', $writer->getTempDir()); $writer->setTempDir(File::sysGetTempDir()); self::assertEquals(File::sysGetTempDir(), $writer->getTempDir()); } public function testEmptyTempdirNamePdf(): void { $this->expectException(WriterException::class); $spreadsheet = new Spreadsheet(); $spreadsheet->getActiveSheet()->getCell('A1')->setValue('Cell 1'); $writer = new Mpdf($spreadsheet); $writer->setTempDir(''); } public function testWinFileNames(): void { self::assertEquals('file:///C:/temp/filename.xlsx', Html::winFileToUrl('C:\temp\filename.xlsx')); self::assertEquals('/tmp/filename.xlsx', Html::winFileToUrl('/tmp/filename.xlsx')); self::assertEquals('a:bfile', Html::winFileToUrl('a:bfile')); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/Issue1319Test.php ================================================ load($file); $writer = new HtmlWriter($spreadsheet); $html = $writer->generateHtmlAll(); $html = (string) preg_replace('/\r?\n\s+/m', '', $html); $spreadsheet->disconnectWorksheets(); $expectedArray = [ 'table.sheet0 col.col0 { width:42pt }', 'table.sheet0 col.col1 { width:42pt }', 'table.sheet0 col.col2 { width:42pt }', 'table.sheet0 col.col3 { width:42pt }', 'table.sheet0 col.col4 { width:42pt }', 'test', '', '', ]; foreach ($expectedArray as $expected) { self::assertStringContainsString($expected, $html); } } public static function testFromScratch(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->getCell('A1')->setValue('test'); $sheet->mergeCells('A1:E3'); $sheet->getStyle('A1')->getFont() ->setBold(true) ->setSize(18); $sheet->getStyle('A1')->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_CENTER) ->setVertical(Alignment::VERTICAL_CENTER); // Following not needed when reading Excel, only from scratch. // columnDimension needed, rowDimension not needed //$sheet->getRowDimension(3); $sheet->getColumnDimension('E'); $writer = new HtmlWriter($spreadsheet); $html = $writer->generateHtmlAll(); $html = (string) preg_replace('/\r?\n\s+/m', '', $html); $spreadsheet->disconnectWorksheets(); $expectedArray = [ '', '', '', '', '', 'test', '', '', ]; foreach ($expectedArray as $expected) { self::assertStringContainsString($expected, $html); } } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/Issue3678Test.php ================================================ getActiveSheet(); $sheet->setShowGridlines(false); $sheet->setPrintGridlines(true); $sheet->getCell('A1')->setValue(1); $styleArray = [ 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => 'FFFF00'], ], ]; $sheet->getStyle('A1')->applyFromArray($styleArray); $style1 = "vertical-align:bottom; border-bottom:none #000000; border-top:none #000000; border-left:none #000000; border-right:none #000000; color:#000000; font-family:'Calibri'; font-size:11pt; background-color:#FFFF00"; $style2 = "vertical-align:bottom; color:#000000; font-family:'Calibri'; font-size:11pt; background-color:#FFFF00"; $style2 .= '; text-align:right; width:42pt'; $writer = new Html($spreadsheet); $html = $writer->generateHtmlAll(); self::assertStringContainsString('td.style1, th.style1 { ' . $style1 . ' }', $html); self::assertStringContainsString('1', $html); self::assertStringContainsString('table.sheet0 col.col0 { width:42pt }', $html); self::assertStringContainsString('.n { text-align:right }', $html); $writer->setUseInlineCss(true); $html = $writer->generateHtmlAll(); self::assertStringContainsString('1', $html); $sheet->setPrintGridlines(false); $html = $writer->generateHtmlAll(); self::assertStringContainsString('1', $html); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/Issue4539Test.php ================================================ load($infile); $writer = new Html($spreadsheet); $writer->setConditionalFormatting(true); $writer->setUseInlineCss(true); $html = $writer->generateHtmlAll(); $expected = '5'; self::assertStringContainsString($expected, $html, 'inline conditional style'); $expected = 'Column Heading'; self::assertStringContainsString($expected, $html, 'inline no conditional style'); $expected = '1'; self::assertStringContainsString($expected, $html, 'inline border-top'); $expected = '2'; self::assertStringContainsString($expected, $html, 'inline border-top and bold'); $expected = '3'; self::assertStringContainsString($expected, $html, 'inline nomatch'); $writer->setUseInlineCss(false); $html = $writer->generateHtmlAll(); $expected = '5'; self::assertStringContainsString($expected, $html, 'notinline conditional style'); $expected = 'Column Heading'; self::assertStringContainsString($expected, $html, 'notinline no conditional style'); $expected = '1'; self::assertStringContainsString($expected, $html, 'notinline border-top'); $expected = '2'; self::assertStringContainsString($expected, $html, 'notinline border-top bold'); $expected = '3'; self::assertStringContainsString($expected, $html, 'notinline nomatch'); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/Issue4773Test.php ================================================ getActiveSheet(); $sheet->getPageSetup()->setFitToWidth(1); $sheet->getPageSetup()->setFitToHeight(0); $sheet->getPageMargins()->setTop(0.2); $sheet->getPageMargins()->setRight(0.2); $sheet->getPageMargins()->setLeft(0.2); $sheet->getPageMargins()->setBottom(0.5); $sheet->getColumnDimension('A')->setWidth(20); $sheet->getColumnDimension('B')->setWidth(20); $sheet->getStyle('A1')->getFont() ->setSize(12) ->setItalic(true); $sheet->getStyle('A1')->getAlignment() ->setWrapText(true); $sheet->setCellValue('A1', "ABC\nDEF\nGHI"); $richText = new RichText(); $run1 = $richText->createTextRun("bold\n"); $run1->getFont()?->setBold(true); $run3 = $richText->createTextRun('italic'); $run3->getFont()?->setItalic(true); $sheet->getStyle('B1')->getAlignment() ->setVertical(Alignment::VERTICAL_CENTER) ->setWrapText(true); $sheet->setCellValue('B1', $richText); $writer = new HtmlWriter($spreadsheet); $eol = $writer->getLineEnding(); $content = $writer->generateHtmlAll(); $expected1 = 'ABC
' . $eol . 'DEF
' . $eol . 'GHI'; self::assertStringContainsString($expected1, $content, 'br tags without newline in normal text'); $expected2 = 'bold
' . $eol . '
italic'; self::assertStringContainsString($expected2, $content, 'only one br tag, plus newline, in rich text'); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/LineEndingTest.php ================================================ spreadsheet->disconnectWorksheets(); unset($this->spreadsheet); } public function testDefault(): void { $this->spreadsheet = new Spreadsheet(); $sheet = $this->spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $writer = new HtmlWriter($this->spreadsheet); self::assertSame(PHP_EOL, $writer->getLineEnding()); $html = $writer->generateHtmlAll(); $count = substr_count($html, PHP_EOL); self::assertSame($this->expectedLines, $count); } public function testUnix(): void { $this->spreadsheet = new Spreadsheet(); $sheet = $this->spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $writer = new HtmlWriter($this->spreadsheet); $writer->setLineEnding("\n"); $html = $writer->generateHtmlAll(); $count = substr_count($html, "\n"); self::assertSame($this->expectedLines, $count); $count = substr_count($html, "\r"); self::assertSame(0, $count); } public function testWindows(): void { $this->spreadsheet = new Spreadsheet(); $sheet = $this->spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $writer = new HtmlWriter($this->spreadsheet); $writer->setLineEnding("\r\n"); $html = $writer->generateHtmlAll(); $count = substr_count($html, "\n"); self::assertSame($this->expectedLines, $count); $count = substr_count($html, "\r"); self::assertSame($this->expectedLines, $count); $count = substr_count($html, "\r\n"); self::assertSame($this->expectedLines, $count); } public function testInvalidLineEnding(): void { $this->expectException(WriterException::class); $this->expectExceptionMessage('Line ending must be'); $this->spreadsheet = new Spreadsheet(); $sheet = $this->spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $writer = new HtmlWriter($this->spreadsheet); $writer->setLineEnding("\r"); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/LongTitleTest.php ================================================ getProperties() ->setTitle($title); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); self::assertSame($expected, $reloadedSpreadsheet->getActiveSheet()->getTitle()); $reloadedSpreadsheet->disconnectWorksheets(); } public static function providerTitles(): array { return [ ['Worksheet', 'This title is just a bit too long'], ['Worksheet', 'Invalid * character'], ['Legitimate Title', 'Legitimate Title'], ]; } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/MailtoTest.php ================================================ getActiveSheet(); $worksheet->setCellValue('A1', 'Mail Me!'); $worksheet->getCell('A1') ->getHyperlink() ->setUrl('mailto:me@example.com'); $worksheet->setCellValue('A2', 'Mail You!'); $worksheet->getCell('A2') ->getHyperlink() ->setTooltip('go ahead') ->setUrl('mailto:you@example.com'); $writer = new HtmlWriter($spreadsheet); $html = $writer->generateHtmlAll(); self::assertStringContainsString('Mail Me!', $html); self::assertStringContainsString('Mail You!', $html); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/MemoryDrawingOffsetTest.php ================================================ getActiveSheet(); $image = file_get_contents(__DIR__ . '/../../../data/Reader/HTML/memoryDrawingTest.jpg'); self::assertNotFalse($image, 'unable to read file'); $image = imagecreatefromstring($image); self::assertNotFalse($image, 'unable to create image from string'); $drawing = new MemoryDrawing(); $drawing->setImageResource($image) ->setResizeProportional(false) //是否保持比例 ->setWidthAndHeight($w, $h) //图片宽高,原始尺寸 100*100 ->setOffsetX($x) ->setOffsetY($y) ->setWorksheet($sheet); $writer = new Html($spreadsheet); $html = $writer->generateHtmlAll(); self::assertStringContainsString('width:' . $w . 'px;left: ' . $x . 'px; top: ' . $y . 'px;position: absolute;', $html); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); } public static function dataProvider(): array { return [ [33, 19, 0, 20], [129, 110, 12, -3], [55, 110, 33, 42], ]; } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/NavigationBadTitleTest.php ================================================ getActiveSheet(); $sheet->getCell('A1')->setValue(1); $sheet2 = $spreadsheet->createSheet(); $sheet2->setTitle(''); $sheet2->getCell('A2')->setValue(2); $writer = new HtmlWriter($spreadsheet); $writer->writeAllSheets(); $eol = $writer->getLineEnding(); $html = $writer->generateHTMLAll(); $expected = ''; self::assertStringContainsString($expected, $html, 'appropriate characters are escaped'); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/NoJavascriptLinksTest.php ================================================ getActiveSheet(); $sheet->getCell('A1')->setValue('Click me'); $hyperlink = new Hyperlink('http://www.example.com'); $sheet->getCell('A1')->setHyperlink($hyperlink); $sheet->getCell('A2')->setValue('JS link'); $hyperlink2 = new Hyperlink('javascript:alert(\'hello1\')'); $sheet->getCell('A2')->setHyperlink($hyperlink2); $sheet->getCell('A3')->setValue('=HYPERLINK("javascript:alert(\'hello2\')", "jsfunc click")'); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); self::assertStringContainsString('Click me', $html, 'http hyperlink retained'); self::assertStringContainsString('javascript:alert(\'hello1\')', $html, 'javascript hyperlink dropped'); self::assertStringContainsString('javascript:alert(\'hello2\')', $html, 'javascript hyperlink function dropped'); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/NoTitleTest.php ================================================ load($file); self::assertSame('', $spreadsheet->getProperties()->getTitle()); $writer = new Html($spreadsheet); $writer->setUseInlineCss(true); $html = $writer->generateHTMLAll(); self::assertStringContainsString('Sheet1', $html); self::assertStringContainsString('C1', $html); $writer->setUseInlineCss(false); $html = $writer->generateHTMLAll(); self::assertStringContainsString('C1', $html); $spreadsheet->disconnectWorksheets(); } public function testHideSomeGridlines(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->fromArray( [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [17, 18, 19, 20, 21, 22], [27, 28, 29, 30, 31, 32], [37, 38, 39, 40, 41, 42], ] ); $sheet->getStyle('B2:D4')->getBorders()->applyFromArray( [ 'allBorders' => [ 'borderStyle' => Border::BORDER_NONE, 'color' => ['rgb' => '808080'], ], ], ); $writer = new Html($spreadsheet); $writer->setUseInlineCss(true); $html = $writer->generateHTMLAll(); self::assertStringContainsString('7', $html); self::assertStringContainsString('19', $html); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/PrintAreaTest.php ================================================ getActiveSheet(); $inArray = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], ]; $sheet->fromArray($inArray); $sheet->getPageSetup()->setPrintArea('B2:D4'); $writer = new HtmlWriter($spreadsheet); $eol = $writer->getLineEnding(); $html = $writer->generateHtmlAll(); self::assertStringContainsString( "", $html ); $expectedArray = [ '@media print {', ' table.sheet0 tr.row0 td { display:none }', ' table.sheet0 tr.row4 td { display:none }', ' table.sheet0 tr.row5 td { display:none }', ' table.sheet0 td.column0 { display:none }', ' table.sheet0 td.column4 { display:none }', '}', ]; $expectedString = implode($eol, $expectedArray); self::assertStringContainsString( $expectedString, $html ); $spreadsheet->disconnectWorksheets(); $reader = new HtmlReader(); $spreadsheet2 = $reader->loadFromString($html); $sheet2 = $spreadsheet2->getActiveSheet(); self::assertSame('B2:D4', $sheet2->getPageSetup()->getPrintArea()); self::assertSame($inArray, $sheet2->toArray(null, false, false)); $spreadsheet2->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/ReadOrderTest.php ================================================ getActiveSheet(); $sheet->setCellValue('A1', '1-' . 'منصور حسين الناصر'); $sheet->setCellValue('A2', '1-' . 'منصور حسين الناصر'); $sheet->setCellValue('A3', '1-' . 'منصور حسين الناصر'); $sheet->getStyle('A1') ->getAlignment()->setReadOrder(Alignment::READORDER_RTL); $sheet->getStyle('A2') ->getAlignment()->setReadOrder(Alignment::READORDER_LTR); $sheet->getStyle('A2')->getFont()->setName('Arial'); $sheet->getStyle('A3')->getFont()->setName('Times New Roman'); $sheet->setCellValue('A5', 'hello'); $sheet->getStyle('A5')->getFont()->setName('Tahoma'); $sheet->getStyle('A5') ->getAlignment()->setIndent(2); $writer = new HtmlWriter($spreadsheet); $writer->setUseInlineCss(true); $html = $writer->generateHtmlAll(); self::assertStringContainsString( '', $html, 'third text element'); $spreadsheet->disconnectWorksheets(); } public function testNoFont(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $rtf = new RichText(); $rtf->createTextRun('no font')->setFont(null); $sheet->setCellValue('A1', $rtf); $writer = new HtmlWriter($spreadsheet); $html = $writer->generateHtmlAll(); self::assertStringContainsString('', $html); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/TextRotationTest.php ================================================ getActiveSheet(); $sheet->setPrintGridlines(true); $sheet->getStyle('A7')->getAlignment()->setTextRotation(90); $sheet->setCellValue('A7', 'Lorem Ipsum'); $writer = new Html($spreadsheet); $html = $writer->generateHtmlAll(); self::assertStringContainsString(' transform:rotate(90deg);', $html); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/TransparentDrawingsTest.php ================================================ getActiveSheet(); $sheet->setShowGridLines(false); $drawing = new Drawing(); $drawing->setName('Blue Square'); $drawing->setPath('tests/data/Writer/XLSX/blue_square.png'); self::assertEquals($drawing->getWidth(), 100); self::assertEquals($drawing->getHeight(), 100); $drawing->setCoordinates('A1'); $drawing->setCoordinates2('E8'); $drawing->setOpacity(25000); $drawing->setWorksheet($sheet); $writer = new HtmlWriter($spreadsheet); $content = $writer->generateHTMLAll(); self::assertStringContainsString('opacity:0.25;', $content); $spreadsheet->disconnectWorksheets(); } public function testHtmlTransparentMemoryDrawing(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setShowGridLines(false); $contents = file_get_contents('tests/data/Writer/XLSX/blue_square.png'); $drawing = MemoryDrawing::fromString("$contents"); $drawing->setName('Blue Square'); self::assertEquals($drawing->getWidth(), 100); self::assertEquals($drawing->getHeight(), 100); $drawing->setCoordinates('A1'); $drawing->setCoordinates2('E8'); $drawing->setOpacity(25000); $drawing->setWorksheet($sheet); $writer = new HtmlWriter($spreadsheet); $content = $writer->generateHTMLAll(); self::assertStringContainsString('opacity:0.25;', $content); $spreadsheet->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/VisibilityTest.php ================================================ getActiveSheet(); $sheet->setCellValue('A1', 1); $sheet->setCellValue('A2', 2); $sheet->setCellValue('A3', 3); $sheet->setCellValue('B1', 4); $sheet->setCellValue('B2', 5); $sheet->setCellValue('B3', 6); $sheet->setCellValue('C1', 7); $sheet->setCellValue('C2', 8); $sheet->setCellValue('C3', 9); $sheet->getColumnDimension('B')->setVisible(false); $sheet->getRowDimension(2)->setVisible(false); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); $reg = '/^\s*table[.]sheet0 tr { display:none; visibility:hidden }\s*$/m'; $rowsrch = preg_match($reg, $html); self::assertEquals($rowsrch, 0); $reg = '/^\s*table[.]sheet0 tr[.]row1 { display:none; visibility:hidden }\s*$/m'; $rowsrch = preg_match($reg, $html); self::assertEquals($rowsrch, 1); $reg = '/^\s*table[.]sheet0 [.]column1 [{] display:none [}]\s*$/m'; $colsrch = preg_match($reg, $html); self::assertEquals($colsrch, 1); $this->writeAndReload($spreadsheet, 'Html'); } public function testVisibility2(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $sheet->setCellValue('A2', 2); $sheet->setCellValue('A3', 3); $sheet->setCellValue('B1', 4); $sheet->setCellValue('B2', 5); $sheet->setCellValue('B3', 6); $sheet->setCellValue('C1', 7); $sheet->setCellValue('C2', 8); $sheet->setCellValue('C3', 9); $sheet->getDefaultRowDimension()->setVisible(false); $sheet->getColumnDimension('B')->setVisible(false); $sheet->getRowDimension(1)->setVisible(true); $sheet->getRowDimension(3)->setVisible(true); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); $reg = '/^\s*table[.]sheet0 tr { height:15pt; display:none; visibility:hidden }\s*$/m'; $rowsrch = preg_match($reg, $html); self::assertEquals($rowsrch, 1); $reg = '/^\s*table[.]sheet0 tr[.]row1 { display:none; visibility:hidden }\s*$/m'; $rowsrch = preg_match($reg, $html); self::assertEquals($rowsrch, 0); $reg = '/^\s*table[.]sheet0 [.]column1 [{] display:none [}]\s*$/m'; $colsrch = preg_match($reg, $html); self::assertEquals($colsrch, 1); $this->writeAndReload($spreadsheet, 'Html'); } public function testDefaultRowHeight(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 1); $sheet->getStyle('A1')->getFont()->setStrikethrough(true); $sheet->setCellValue('A2', 2); $sheet->setCellValue('A3', 3); $sheet->getStyle('A3')->getFont()->setStrikethrough(true)->setUnderline(Font::UNDERLINE_SINGLE); $sheet->setCellValue('B1', 4); $sheet->setCellValue('B2', 5); $sheet->setCellValue('B3', 6); $sheet->setCellValue('C1', 7); $sheet->setCellValue('C2', 8); $sheet->setCellValue('C3', 9); $sheet->getStyle('C3')->getFont()->setUnderline(Font::UNDERLINE_SINGLE); $sheet->getDefaultRowDimension()->setRowHeight(20); $sheet->getRowDimension(2)->setRowHeight(25); $writer = new Html($spreadsheet); $html = $writer->generateHTMLAll(); self::assertEquals(1, substr_count($html, 'height:20pt')); self::assertEquals(1, substr_count($html, 'height:25pt')); $rowsrch = preg_match('/^\s*table[.]sheet0 tr [{] height:20pt [}]\s*$/m', $html); self::assertEquals(1, $rowsrch); $rowsrch = preg_match('/^\s*table[.]sheet0 tr[.]row1 [{] height:25pt [}]\s*$/m', $html); self::assertEquals(1, $rowsrch); $rowsrch = preg_match('/^\s*td[.]style1, th[.]style1 [{].*text-decoration:line-through;.*[}]\s*$/m', $html); self::assertEquals(1, $rowsrch); $rowsrch = preg_match('/^\s*td[.]style2, th[.]style2 [{].*text-decoration:underline line-through;.*[}]\s*$/m', $html); self::assertEquals(1, $rowsrch); $rowsrch = preg_match('/^\s*td[.]style3, th[.]style3 [{].*text-decoration:underline;.*[}]\s*$/m', $html); self::assertEquals(1, $rowsrch); $this->writeAndReload($spreadsheet, 'Html'); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/XssVulnerabilityTest.php ================================================ ['Hello, I am safely viewing your site', 'Hello, I am safely viewing your site'], 'link eliminated' => ["Google is here", "<a href='Visit Google'>Google is here</a>"], 'script tag' => ["Hello, I am trying to your site", "Hello, I am trying to <script>alert('Hack');</script> your site"], 'script tag with quotes' => ['Hello, I am trying to your site', 'Hello, I am trying to <script>alert("Hack");</script> your site'], 'javascript tag no hex' => ["CLICK", "<a href='javascript:alert(1)'>CLICK</a>"], 'javascript tag' => ["CLICK", "<a href='&#x2000;javascript:alert(1)'>CLICK</a>"], 'with unicode' => ['CLICK', '<a href="\u0001java\u0003script:alert(1)">CLICK</a>'], 'inline css' => ['
  • ', '<li style="list-style-image: url(javascript:alert(0))">'], 'char value chevron' => ["\x3cscript src=http://www.example.com/malicious-code.js\x3e\x3c/script\x3e", '<script src=http://www.example.com/malicious-code.js></script>'], 'hexadecimal html' => ['', '<IMG SRC=&#106&#x61&#x76&#x61&#x73&#109&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>'], 'iframe' => ['', '<iframe width="560" onclick="alert(\'xss\')" height="315" src="https://www.youtube.com/embed/whatever?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>'], ]; } #[\PHPUnit\Framework\Attributes\DataProvider('providerXssRichText')] public function testXssInComment(string $xssTextString, ?string $expected = null): void { $spreadsheet = new Spreadsheet(); $startCell = '
  • '; $richText = new RichText(); $richText->createText($xssTextString); $spreadsheet->getActiveSheet()->getCell('A1') ->setValue($cellText); $spreadsheet->getActiveSheet() ->getComment('A1') ->setText($richText); $writer = new Html($spreadsheet); $eol = $writer->getLineEnding(); if ($expected === null) { // whole comment stripped away $expected = $startCell . $endCell; } else { $expected = $startCell . '
    ' . $expected . '
    ' . $eol . $endCell; } $verify = $writer->generateHtmlAll(); // Ensure that executable js has been stripped from the comments self::assertStringContainsString($expected, $verify); $spreadsheet->disconnectWorksheets(); } public function testXssInFontName(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->getCell('A1')->setValue('here'); $used = 'Calibri
    generateHTMLall(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tbl = $divs->item(0)?->getElementsByTagName('table'); self::assertSame('', $tbl?->item(0)?->getAttribute('style')); $thd = $divs->item(0)?->getElementsByTagName('thead'); self::assertCount(1, $thd); $trw = $thd?->item(0)?->getElementsByTagName('tr'); self::assertCount(2, $trw); $tbd = $divs->item(0)?->getElementsByTagName('tbody'); self::assertCount(1, $tbd); $trw = $tbd?->item(0)?->getElementsByTagName('tr'); self::assertCount(98, $trw); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } public function testWriteNoRepeats(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); //$sheet->getPageSetup()->setRowsToRepeatAtTop([1, 2]); $sheet->setCellValue('A1', 'Repeat1'); $sheet->setCellValue('A2', 'Repeat2'); for ($row = 3; $row <= 100; ++$row) { $sheet->setCellValue("A$row", $row); } $writer = new Html($spreadsheet); $html = $writer->generateHTMLall(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tbl = $divs->item(0)?->getElementsByTagName('table'); $thd = $tbl?->item(0)?->getElementsByTagName('thead'); self::assertCount(0, $thd); //$trw = $thd->item(0)->getElementsByTagName('tr'); //self::assertCount(2, $trw); $tbd = $divs->item(0)?->getElementsByTagName('tbody'); self::assertCount(1, $tbd); $trw = $tbd?->item(0)?->getElementsByTagName('tr'); self::assertCount(100, $trw); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } public function testWriteRepeatsInline(): void { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->getPageSetup()->setRowsToRepeatAtTop([1, 2]); $sheet->setCellValue('A1', 'Repeat1'); $sheet->setCellValue('A2', 'Repeat2'); for ($row = 3; $row <= 100; ++$row) { $sheet->setCellValue("A$row", $row); } $writer = new Html($spreadsheet); self::assertFalse($writer->getUseInlineCss()); $writer->setUseInlineCss(true); $html = $writer->generateHTMLall(); $dom = new DOMDocument(); $dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); self::assertNotNull($body); $divs = $body->getElementsByTagName('div'); $tbl = $divs->item(0)?->getElementsByTagName('table'); self::assertSame('border-collapse:collapse', $tbl?->item(0)?->getAttribute('style')); $thd = $divs->item(0)?->getElementsByTagName('thead'); self::assertCount(1, $thd); $trw = $thd?->item(0)?->getElementsByTagName('tr'); self::assertCount(2, $trw); $tbd = $divs->item(0)?->getElementsByTagName('tbody'); self::assertCount(1, $tbd); $trw = $tbd?->item(0)?->getElementsByTagName('tr'); self::assertCount(98, $trw); $rls = $this->writeAndReload($spreadsheet, 'Html'); $spreadsheet->disconnectWorksheets(); $rls->disconnectWorksheets(); } } ================================================ FILE: tests/PhpSpreadsheetTests/Writer/Html/RichTextTest.php ================================================ getActiveSheet(); $rtf = new RichText(); $rtf->createText('~Cell Style~'); $rtf->createTextRun('~RTF Style~')->getFont()?->setItalic(true); $rtf->createText('~No Style~'); $sheet->getCell('A1')->setValue($rtf); $sheet->getStyle('A1')->getFont()->setBold(true); $fontStyle = $sheet->getStyle('A1')->getFont(); self::assertTrue($fontStyle->getBold()); self::assertFalse($fontStyle->getItalic()); $a1Value = $sheet->getCell('A1')->getValue(); self::assertInstanceOf(RichText::class, $a1Value); $elements = $a1Value->getRichTextElements(); self::assertCount(3, $elements); self::assertNull($elements[0]->getFont()); $fontStyle = $elements[1]->getFont(); self::assertNotNull($fontStyle); self::assertFalse($fontStyle->getBold()); self::assertTrue($fontStyle->getItalic()); self::assertNull($elements[0]->getFont()); $writer = new HtmlWriter($spreadsheet); $html = $writer->generateHtmlAll(); self::assertStringContainsString('td.style1, th.style1 { vertical-align:bottom; border-bottom:none #000000; border-top:none #000000; border-left:none #000000; border-right:none #000000; font-weight:bold; color:#000000; font-family:\'Calibri\'; font-size:11pt }', $html, 'cell style'); self::assertStringContainsString('~Cell Style~', $html, 'cell style and first text element'); self::assertStringContainsString('~RTF Style~', $html, 'second text element'); self::assertStringContainsString('~No Style~no font'; $cellText = 'XSS Test'; $endCell = $cellText . '
          Embedded image
    ================================================ FILE: tests/data/Reader/HTML/rowspan.html ================================================
    A1 B1 C1 D1
    A2 with invalid colspan D2
    ================================================ FILE: tests/data/Reader/HTML/utf8chars.charset.html ================================================ Test Utf-8 characters voilà
    éàâèî αβγδε
    𐐁𐐂𐐃 & だけち אבגדה 𪔀𪔁𪔂
    ᠐᠑᠒ അആ กขฃ ✀✐✠
    second table
    third table second cell
    ================================================ FILE: tests/data/Reader/HTML/utf8chars.html ================================================ Test Utf-8 characters voilà
    éàâèî αβγδε
    𐐁𐐂𐐃 & だけち אבגדה 𪔀𪔁𪔂
    ᠐᠑᠒ അആ กขฃ ✀✐✠
    ================================================ FILE: tests/data/Reader/HTML/xhtml4.entity.xhtml ================================================ ]> HTML Entities
    &test;
    ================================================ FILE: tests/data/Reader/Slk/issue.2267c.slk ================================================ ID;PWXL;N;E P;PGeneral P;P0 P;P0.00 P;P#,##0 P;P#,##0.00 P;P#,##0_);;\(#,##0\) P;P#,##0_);;[Red]\(#,##0\) P;P#,##0.00_);;\(#,##0.00\) P;P#,##0.00_);;[Red]\(#,##0.00\) P;P"$"#,##0_);;\("$"#,##0\) P;P"$"#,##0_);;[Red]\("$"#,##0\) P;P"$"#,##0.00_);;\("$"#,##0.00\) P;P"$"#,##0.00_);;[Red]\("$"#,##0.00\) P;P0% P;P0.00% P;P0.00E+00 P;P##0.0E+0 P;P#\ ?/? P;P#\ ??/?? P;Pyyyy/mm/dd P;Pdd/mmm/yy P;Pdd/mmm P;Pmmm/yy P;Ph:mm\ AM/PM P;Ph:mm:ss\ AM/PM P;Ph:mm P;Ph:mm:ss P;Pyyyy/mm/dd\ h:mm P;Pmm:ss P;Pmm:ss.0 P;P@ P;P[h]:mm:ss P;P_("$"* #,##0_);;_("$"* \(#,##0\);;_("$"* "-"_);;_(@_) P;P_(* #,##0_);;_(* \(#,##0\);;_(* "-"_);;_(@_) P;P_("$"* #,##0.00_);;_("$"* \(#,##0.00\);;_("$"* "-"??_);;_(@_) P;P_(* #,##0.00_);;_(* \(#,##0.00\);;_(* "-"??_);;_(@_) P;FCalibri;M220;L9 P;FCalibri;M220;L9 P;FCalibri;M220;L9 P;FCalibri;M220;L9 P;ECalibri;M220;L9 P;ECalibri Light;M360;L55 P;ECalibri;M300;SB;L55 P;ECalibri;M260;SB;L55 P;ECalibri;M220;SB;L55 P;ECalibri;M220;L18 P;ECalibri;M220;L21 P;ECalibri;M220;L61 P;ECalibri;M220;L63 P;ECalibri;M220;SB;L64 P;ECalibri;M220;SB;L53 P;ECalibri;M220;L53 P;ECalibri;M220;SB;L10 P;ECalibri;M220;L11 P;ECalibri;M220;SI;L24 P;ECalibri;M220;SB;L9 P;ECalibri;M220;L10 P;ESegoe UI;M200;L9 F;P0;DG0G8;M320 B;Y6;X5;D0 0 5 4 O;D;V0;K47;G100 0.001 F;W1 16384 10 C;Y1;X1;K1 C;X2;K10 C;X3;K100 C;X4;K101 C;X5;K102 C;Y2;X1;K2;ER[-1]C+1 C;X2;K11;ER[-1]C+1 C;X3;K101;S;R2;C1 C;X4;K102;S;R2;C1 C;X5;K103;S;R2;C1 C;Y3;X1;K3;S;R2;C1 C;X2;K12;ER[-1]C+1 C;X3;K102;S;R2;C1 C;X4;K103;S;R2;C1 C;X5;K104;S;R2;C1 C;Y4;X1;K4;S;R2;C1 C;X2;K13;ER[-1]C+1 C;X3;K103;S;R2;C1 C;X4;K104;S;R2;C1 C;X5;K105;S;R2;C1 C;Y5;X1;K5;S;R2;C1 C;X2;K14;ER[-1]C+1 C;X3;K104;S;R2;C1 C;X4;K105;S;R2;C1 C;X5;K106;S;R2;C1 E ================================================ FILE: tests/data/Reader/Slk/issue.2276.slk ================================================ ID;PWXL;N;E P;PGeneral F;P0;DG0G10;M320 B;Y3;X1;D0 0 9 0 C;Y1;X1;AZeratul: :En Taro Adun! C;Y2;X2;AArthas: :Frostmourne Hungers. C;Y1;X1;K1 C;Y1;X2;K2 C;Y2;X1;K3 E ================================================ FILE: tests/data/Reader/Slk/issue.3658.slk ================================================ ID;PWXL;N;E P;PGeneral P;P0 P;P0.00 P;P#,##0 P;P#,##0.00 P;P#,##0_);;\(#,##0\) P;P#,##0_);;[Red]\(#,##0\) P;P#,##0.00_);;\(#,##0.00\) P;P#,##0.00_);;[Red]\(#,##0.00\) P;P"$"#,##0_);;\("$"#,##0\) P;P"$"#,##0_);;[Red]\("$"#,##0\) P;P"$"#,##0.00_);;\("$"#,##0.00\) P;P"$"#,##0.00_);;[Red]\("$"#,##0.00\) P;P0% P;P0.00% P;P0.00E+00 P;P##0.0E+0 P;P#\ ?/? P;P#\ ??/?? P;Pyyyy/mm/dd P;Pdd/mmm/yy P;Pdd/mmm P;Pmmm/yy P;Ph:mm\ AM/PM P;Ph:mm:ss\ AM/PM P;Ph:mm P;Ph:mm:ss P;Pyyyy/mm/dd\ h:mm P;Pmm:ss P;Pmm:ss.0 P;P@ P;P[h]:mm:ss P;P_("$"* #,##0_);;_("$"* \(#,##0\);;_("$"* "-"_);;_(@_) P;P_(* #,##0_);;_(* \(#,##0\);;_(* "-"_);;_(@_) P;P_("$"* #,##0.00_);;_("$"* \(#,##0.00\);;_("$"* "-"??_);;_(@_) P;P_(* #,##0.00_);;_(* \(#,##0.00\);;_(* "-"??_);;_(@_) P;FCalibri;M220;L9 P;FCalibri;M220;L9 P;FCalibri;M220;L9 P;FCalibri;M220;L9 P;ECalibri;M220;L9 P;ECalibri Light;M360;L55 P;ECalibri;M300;SB;L55 P;ECalibri;M260;SB;L55 P;ECalibri;M220;SB;L55 P;ECalibri;M220;L18 P;ECalibri;M220;L21 P;ECalibri;M220;L61 P;ECalibri;M220;L63 P;ECalibri;M220;SB;L64 P;ECalibri;M220;SB;L53 P;ECalibri;M220;L53 P;ECalibri;M220;SB;L10 P;ECalibri;M220;L11 P;ECalibri;M220;SI;L24 P;ECalibri;M220;SB;L9 P;ECalibri;M220;L10 P;ECalibri;M220;L9 P;ECalibri Light;M360;L55 P;ECalibri;M300;SB;L55 P;ECalibri;M260;SB;L55 P;ECalibri;M220;SB;L55 P;ECalibri;M220;L18 P;ECalibri;M220;L21 P;ECalibri;M220;L61 P;ECalibri;M220;L63 P;ECalibri;M220;SB;L64 P;ECalibri;M220;SB;L53 P;ECalibri;M220;L53 P;ECalibri;M220;SB;L10 P;ECalibri;M220;L11 P;ECalibri;M220;SI;L24 P;ECalibri;M220;SB;L9 P;ECalibri;M220;L10 P;ESegoe UI;M200;L9 P;ECalibri;M220;L9 F;P0;DG0G8;M290 B;Y4;X1;D0 0 3 0 O;L;D;V0;G100 0.001 C;Y1;X1;K123 C;Y2;K124;ER[-1]C+1 C;Y3;K"00123";E"00"&R[-2]C C;Y4;K"pcdos";EINFO("SYSTEM") E ================================================ FILE: tests/data/Reader/Xml/ArrayFormula.xml ================================================ Owen Leibman Owen Leibman 2024-06-17T19:03:14Z 2024-06-17T19:04:33Z 16.00 10300 19420 32767 32767 False False a a-1 1 b b-2 2 c c-3 3