Xls Writer and Empty RichText

Fix #918, which went stale in 2019 and is now reopened. Writing out a RichText object with no text to Xls creates a file which Excel considers corrupt. Treating such an object as a null string rather than a RichText object when writing eliminates the problem.
This commit is contained in:
oleibman
2026-01-02 12:46:24 -08:00
parent 0544868f90
commit e11a6afb5e
3 changed files with 36 additions and 0 deletions
+3
View File
@@ -150,6 +150,9 @@ class Xls extends BaseWriter
/** @var Cell $cell */
$cell = $this->writerWorksheets[$i]->phpSheet->getCellCollection()->get($coordinate);
$cVal = $cell->getValue();
if ($cVal instanceof RichText && (string) $cVal === '') {
$cVal = '';
}
if ($cVal instanceof RichText) {
$active = $this->spreadsheet->getActiveSheetIndex();
$sheet = $cell->getWorksheet();
@@ -369,6 +369,9 @@ class Worksheet extends BIFFwriter
$xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
$cVal = $cell->getValue();
if ($cVal instanceof RichText && (string) $cVal === '') {
$cVal = '';
}
if ($cVal instanceof RichText) {
$arrcRun = [];
$str_pos = 0;
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Helper\Html as HtmlHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class Issue918Test extends AbstractFunctional
{
public function testEmptyRichText(): void
{
// Issue 918 - Xls Writer creates corrupt file with empty RichText.
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$helper = new HtmlHelper();
$html = '<div></div>';
$richValue = $helper->toRichTextObject($html);
self::assertCount(0, $richValue->getRichTextElements());
$sheet->getCell('A1')->setValue($richValue);
$robj = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$sheet0 = $robj->getActiveSheet();
self::assertNull($sheet0->getCell('A1')->getValue(), 'empty text object has been changed to null');
$robj->disconnectWorksheets();
}
}