Add numeric columns and formatted as currency if has specific form (#5)

* add numeric columns and formatted as currency if has specific form

* Update src/Spout/Writer/Common/Helper/CellHelper.php

Co-Authored-By: Eliurkis Diaz <eliurkis@gmail.com>
This commit is contained in:
Dariel Ramos 2019-11-15 17:26:02 -05:00 committed by Eliurkis Diaz
parent 9dff3a5421
commit a8daa45468
3 changed files with 25 additions and 4 deletions

View File

@ -61,7 +61,7 @@ class CellHelper
*/
public static function isNonEmptyString($value)
{
return (gettype($value) === 'string' && $value !== '');
return (gettype($value) === 'string' && $value !== '' && !$this->isNumeric($value));
}
/**
@ -73,8 +73,7 @@ class CellHelper
*/
public static function isNumeric($value)
{
$valueType = gettype($value);
return ($valueType === 'integer' || $valueType === 'double');
return preg_match('#^-?\d+\.?\d*$#', $value) === 1;
}
/**

View File

@ -151,6 +151,7 @@ class StyleHelper extends AbstractStyleHelper
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
EOD;
$content .= $this->getNumberFormatSectionContent();
$content .= $this->getFontsSectionContent();
$content .= $this->getFillsSectionContent();
$content .= $this->getBordersSectionContent();
@ -165,6 +166,21 @@ EOD;
return $content;
}
/**
* Return the content of the "<numFmt>" section
*
* @return string
*/
protected function getNumberFormatSectionContent()
{
$content = <<<EOL
<numFmts count="1">
<numFmt formatCode="$#,##0.00" numFmtId="164"/>
</numFmts>
EOL;
return $content;
}
/**
* Returns the content of the "<fonts>" section.
*
@ -298,8 +314,9 @@ EOD;
protected function getCellXfsSectionContent()
{
$registeredStyles = $this->getRegisteredStyles();
$countStyles = count($registeredStyles) + 1;
$content = '<cellXfs count="' . count($registeredStyles) . '">';
$content = '<cellXfs count="' . $countStyles . '">';
foreach ($registeredStyles as $style) {
$styleId = $style->getId();
@ -323,6 +340,9 @@ EOD;
}
}
// Add default style for numberFormat
$content .= '<xf numFmtId="164" borderId="0" fillId="0" fontId="0" applyFont="1" xfId="0" applyNumberFormat="1"/>';
$content .= '</cellXfs>';
return $content;

View File

@ -238,6 +238,8 @@ EOD;
*/
protected function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
{
// If $cellValue has double format then assign style from numFmt section (2) else default (1)
$styleId = preg_match('#^\d+\.\d+$#', $cellValue) === 1 ? 2 : $styleId;
$columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
$cellXML = '<c r="'.$columnIndex.$rowIndex.'"';
$cellXML .= ' s="'.$styleId.'"';