Search code examples
phpphpexcelxlsx

PHP Excel from array merge cells


I export a table of participants. I have a form for the participants, where I have dynamically generated section for choosing meals. It comes from array like this:

$days = array(
    array(
        'title' => 'Saturday',
        'meals' => array(
            array(
                'title' => 'Brf',
                'price' => 25
            ),
            array(
                'title' => 'Lnch',
                'price' => 60
            ),
            array(
                'title' => 'Dnr',
                'price' => 35
            )
        )
    )
);

I need to merge and center day titles (Thursday, Friday...) and merge with number of cells on the right. The number of merged cells equals to count($days[$day]['meals']).

The goal looks like this: The goal of all this

I use creating table from array $PHPexcelsheet->from_array($a); for table data. If it could be used for the header too, would be nice, but not necessary.


Solution

  • Finally I got to the solution. Doesn't seem so pretty, as I supposed, and also doesn*t work with more than 26 cols (which I don't need), but works.

    $i = 0;
    $c = 4;
    $alphabet = range('A', 'Z');
    while ($i < count($ceny_jidlo)) {
        $den = $ceny_jidlo[$i];
    
        $s = $alphabet[$c];
    
        $sheet->setCellValue("{$s}1", $den['short']);
    
        $co = $c;
        $c = $c + count($den['opts']) - 1;
        $e = $alphabet[$c];
    
        for ($j = $co; $j <= $c; $j++)
            colstyle($shit, $alphabet[$j], $eRow, 10);
    
        $sheet->mergeCells("{$s}1:{$e}1");
    
        $c++;
        $i++;
    }