Different colors in one cell

Topics: User Forum
Nov 30, 2014 at 11:26 AM
Hi, all :)

How can i do it when create XLS file with PHPExcel?

in php i can do that:
  <span style='color:#eeeeee'>text</span>
  <span style='color:#ff0000'>text</span>
  <span style='color:#0000ff'>text</span>
but PHPExcel can do that only one color in one cell :(
I need different colors in cell :(
Nov 30, 2014 at 11:44 AM
Edited Nov 30, 2014 at 11:46 AM
Take a look at Rich Text Runs, there's a good example in 05featuredemo.inc.php where cell A18 is mixed black (default colour) and green text, and Rich Text is described in section 4.6.38 (Add rich text to a cell) of the developer documentation
Nov 30, 2014 at 11:55 AM
I tried these code:
$objRichText = new PHPExcel_RichText();
$objRed = $objRichText->createTextRun('red');
$objRed->getFont()->setColor(new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_RED ) );

$objGreen = $objRichText->createTextRun('green');
$objGreen->getFont()->setColor(new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_GREEN ) );

$aSheet->setCellValue("A1", "$objRichText");
And i see in cell "A1" two words "red" and "green" of black color :(
Nov 30, 2014 at 12:05 PM
Edited Nov 30, 2014 at 12:06 PM
Solved. Thanks.

Another example:
$objRichText = new PHPExcel_RichText();

$objPayable = $objRichText->createTextRun('Text');
$objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );


Nov 30, 2014 at 12:08 PM
This works perfectly well, as long as you don't do silly things like quoting the rich text object when you write it to the cell
$aSheet->setCellValue("A1", "$objRichText");
should be
$aSheet->setCellValue("A1", $objRichText);
Quoting the object in the way you did means that PHP will treat it as a string, so it will execute the __toString() magic method of the Rich Text object and simply store that returned string in the cell.... you need to store the actual Rich Text object, not simply the string that it contains.
$objRichText = new PHPExcel_RichText();

$objRed = $objRichText->createTextRun('RED');
$objRed->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKRED ) );

$objRichText->createText(' and ');

$objGreen = $objRichText->createTextRun('GREEN');
$objGreen->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );

Nov 30, 2014 at 12:39 PM
MarkBaker , thank you!

I usually write all text in quotes (habit when write code in PHP) and did not pay attention to quotes. :(