Skip to content

Commit

Permalink
Escale any dollar signs when formatting cell data
Browse files Browse the repository at this point in the history
When a cell is formatted as text and contains a number prefixed with dollar sign, this number is getting replaced with 0. The replacement happens due to the preg_replace function.
This commit escapes any sollar signs on the cell data, so those are not replaced.
  • Loading branch information
sirbaconjr committed Nov 25, 2024
1 parent fd562af commit 61c0f25
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ public static function toFormattedString($value, string $format, ?array $callBac
// 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
if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $format) === 1) {
return str_replace('"', '', preg_replace(self::SYMBOL_AT, (string) $value, $format) ?? '');
//escape any dollar signs on the string, so they are not replaced with an empty value
$value = str_replace('$', '\\$', (string) $value);

return str_replace('"', '', preg_replace(self::SYMBOL_AT, $value, $format) ?? '');
}

// If we have a text value, return it "as is"
Expand Down
16 changes: 16 additions & 0 deletions tests/PhpSpreadsheetTests/Worksheet/ToArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace PhpOffice\PhpSpreadsheetTests\Worksheet;

use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;

Expand Down Expand Up @@ -76,4 +77,19 @@ public static function testMaxCol(): void
self::assertSame('start', $array[0][0]);
self::assertSame('end', $array[0][16383]);
}

public static function testDollarSign(): void
{
$filename = 'tests/data/Reader/XLSX/issue.4242.xlsx';
$reader = new Xlsx();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();

$expected = [
['General', '$0', 'Value is $100', '200 number - $200 value', null],
['Text', '$0', 'Value is $100', '200 number - $200 value', null],
];
$result = $sheet->toArray();
self::assertSame($expected, $result);
}
}
Binary file added tests/data/Reader/XLSX/issue.4242.xlsx
Binary file not shown.

0 comments on commit 61c0f25

Please sign in to comment.