-1

Using PHPSpreadsheet, I created a Style object and set everything it needed. For instance:

$dateformat = new PhpOffice\PhpSpreadsheet\Style\NumberFormat();
$dateformat->setFormatCode($row['format']);

But I don't see any way to pass that object to style my cells, the only method I can see is setStyleArray($array).

So then I looked at the style object, and I noticed that this had a getStyleArray($array) method. But it takes IN an array, and just returns it in another key:

/**
 * Build style array from subcomponents.
 *
 * @param array $array
 *
 * @return array
 */
public function getStyleArray($array)
{
    return ['quotePrefix' => $array];
} 

So that's also pretty useless. So my question is simple. Is it even possible? Or must we work with the arrays? If so, what is the point of these objects if we can't use them effectively?

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
  • _“I created a Style object”_ - show what you mean by that. If it is just a StdClass instance, you can probably just cast it to an array, directly in your method call. _“If so, what is the point of these objects if we can't use them effectively?”_ - they are two different things, and whoever wrote your library, decided to use an array in that place. That alone says _nothing_ about what their point might or might not be, that is just an individual decision. – 04FS Feb 04 '20 at 14:44
  • Its not a stdClass, it is a PHPSpreadsheet Style class – delboy1978uk Feb 04 '20 at 14:54
  • I have actually dealt with older version,i.e, `PHPExcel`in which we did like `return array( 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, ) );` So you mean doing the same by passing an object? – nice_dev Feb 04 '20 at 15:19
  • i am literally replacing that old library. i dont see how commenting on a different lib would help. – delboy1978uk Feb 04 '20 at 16:49

2 Answers2

1

You should not create Style object yourself. Instead ask PhpSpreadsheet to give you one, and then modify that object. Something like:

use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

// Get the style
$style = $spreadsheet->getActiveSheet()->getStyle('B2');

// Update it as fit
$style->getFont()->getColor()->setARGB(Color::COLOR_RED);
$style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);

All of this is documented in official documentation: https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#formatting-cells

PowerKiKi
  • 4,539
  • 4
  • 39
  • 47
0

It doesn't look like it's possible. I had to create arrays in the end.

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39