A
A
Andrew2020-01-14 09:41:29
PHP
Andrew, 2020-01-14 09:41:29

How can you templatize Excel in PHP?

The system is written in PHP, reports are uploaded to Excel (xlsx) using PHPSpreadSheet. You need to write nested loops. There are no problems with loops without nesting, but how to make 2 nestings in loops is not clear.
The array looks something like this:

$a = [
    [
        'id'   => 1,
        'name' => 'Test',
        'items' => [
            [
                'label' => 'item 1',
                'price' => 4000,
            ]
        ]
    ],
    [
        'id'   => 2,
        'name' => 'Test 2',
        'items' => [
            [
                'label' => 'item 1',
                'price' => 4000,
            ],
            [
                'label' => 'item 2',
                'price' => 3000,
            ]
        ]
    ]
];

The template I was able to come up with is this:
5e1d623276e10866726361.jpeg
Does anyone have any ideas how to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Khomenko, 2020-01-14
@iiifx

I do not think that it will be possible to template cycles in this way. I have not seen this in PhpSpreadsheet.
You can insert N rows(1) followed by filling(2):

$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($template);

if ($rowsCurrentPeriod) {
    $sheet = $spreadsheet->setActiveSheetIndex(1);
    if (($count = count($rowsCurrentPeriod)) > 2) {
        $sheet->insertNewRowBefore(8, $count - 2); # <-- 1
    }
    $sheet->fromArray($rowsCurrentPeriod, null, 'A7', true); # <-- 2
}

$spreadsheet->setActiveSheetIndex(0);
$writer = new Xlsx($spreadsheet);
$writer->save($filepath);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question