From 927684486e7a4b971529375f36ee5847bbc63bd2 Mon Sep 17 00:00:00 2001 From: Eli Y Date: Wed, 8 Aug 2018 11:19:06 +0300 Subject: [PATCH] Added Formula support --- src/Spout/Writer/XLSX/Formula.php | 40 +++++++++++++ src/Spout/Writer/XLSX/Internal/Worksheet.php | 5 +- tests/Spout/Writer/XLSX/FormulaTest.php | 60 ++++++++++++++++++++ 3 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 src/Spout/Writer/XLSX/Formula.php create mode 100644 tests/Spout/Writer/XLSX/FormulaTest.php diff --git a/src/Spout/Writer/XLSX/Formula.php b/src/Spout/Writer/XLSX/Formula.php new file mode 100644 index 0000000..f2d5eaa --- /dev/null +++ b/src/Spout/Writer/XLSX/Formula.php @@ -0,0 +1,40 @@ +formula = $formula; + $this->value = $value; + } + + public function getXml() + { + return '>' . $this->formula . '' . $this->value . ''; + } + +} \ No newline at end of file diff --git a/src/Spout/Writer/XLSX/Internal/Worksheet.php b/src/Spout/Writer/XLSX/Internal/Worksheet.php index 0bd909d..a1cb486 100644 --- a/src/Spout/Writer/XLSX/Internal/Worksheet.php +++ b/src/Spout/Writer/XLSX/Internal/Worksheet.php @@ -5,6 +5,7 @@ namespace Box\Spout\Writer\XLSX\Internal; use Box\Spout\Common\Exception\InvalidArgumentException; use Box\Spout\Common\Exception\IOException; use Box\Spout\Common\Helper\StringHelper; +use Box\Spout\Writer\XLSX\Formula; use Box\Spout\Writer\Common\Helper\CellHelper; use Box\Spout\Writer\Common\Internal\WorksheetInterface; @@ -184,7 +185,7 @@ EOD; $rowXML = ''; - foreach($dataRow as $cellValue) { + foreach ($dataRow as $cellValue) { $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId()); $cellNumber++; } @@ -227,6 +228,8 @@ EOD; // NOTE: not appending to $cellXML is the right behavior!! $cellXML = ''; } + } elseif ($cellValue instanceof Formula) { + $cellXML .= $cellValue->getXml(); } else { throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue)); } diff --git a/tests/Spout/Writer/XLSX/FormulaTest.php b/tests/Spout/Writer/XLSX/FormulaTest.php new file mode 100644 index 0000000..b7107eb --- /dev/null +++ b/tests/Spout/Writer/XLSX/FormulaTest.php @@ -0,0 +1,60 @@ +createGeneratedFolderIfNeeded($fileName); + $resourcePath = $this->getGeneratedResourcePath($fileName); + + $writer = WriterFactory::create(Type::XLSX); + $writer->openToFile($resourcePath); + + $writer->addRows([ + [1], + [1], + [1], + [1], + ]); + + $writer->addRow([ + new Formula('SUM(A1:A4)', 4) + ]); + $writer->close(); + + + $reader = ReaderFactory::create(Type::XLSX); + $reader->open($resourcePath); + + $i = 0; + /** @var Sheet $sheet */ + foreach ($reader->getSheetIterator() as $sheet) { + foreach ($sheet->getRowIterator() as $item) { + $i++; + if ($i == 5) { + static::assertEquals(4, $item[0]); + } + } + } + } +}