A
A
Aleksandr Yurchenko2021-07-13 11:52:49
PHP
Aleksandr Yurchenko, 2021-07-13 11:52:49

How to implement "complex" table creation with PhpSpreadsheet?

Hello.

Tell me how to implement the creation of a "complex" table through the PhpSpreadsheet library. It should look something like this:
60ed5003e5189188861527.png
That is, the columns: "Field 2", "Field 3" can have a different number of cells (depending on the incoming data). No matter how much I tried, I could only achieve this result:
60ed50733497b489597582.png
I achieved the creation of a different number of cells (depending on the input data) for columns 3 and 4. The problem is that the values ​​in "Field 4" are written to the next cell relative to "Field 3". I just can not achieve the result, as in 1 photo.

The process of creating an excel file:

$data = $this->getData();
$spreadsheet = new Spreadsheet();

$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Лист 1');
$columns = range('A', 'D');

$c = 0;
$sheet->setCellValue($columns[$c++] . 1, 'Поле 1');
$sheet->setCellValue($columns[$c++] . 1, 'Поле 2');
$sheet->setCellValue($columns[$c++] . 1, 'Поле 3');
$sheet->setCellValue($columns[$c++] . 1, 'Поле 4');

foreach ($data as $value) {
    $sheet->setCellValue($columns[$c++] . $r, $value->getData1());
    $sheet->setCellValue($columns[$c++] . $r, $value->getData2());

    $c = 2;
    foreach ($value->getData3() as $item3) {
                    $sheet->setCellValue($columns[$c] . $r, $item3);
                    $r++;
    }
    $c = 3;
    foreach ($value->getData4() as $item4) {
                    $sheet->setCellValue($columns[$c] . $r, $item4);
                    $r++;
    }
    
    $r++;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-07-13
@yaleksandr89

Keep separate counters for line numbers for columns 1-2, 3, and 4.
Sample code in a hurry:

foreach ($data as $value) {
    $sheet->setCellValue($columns[$c++] . $r, $value->getData1());
    $sheet->setCellValue($columns[$c++] . $r, $value->getData2());

    $originalRowId = $r;

    $c = 2;
    $c2r = $originalRowId;
    foreach ($value->getData3() as $item3) {
                    $sheet->setCellValue($columns[$c] . $r, $item3);
                    $c2r++;
    }

    $c = 3;
    $c3r = $originalRowId;
    foreach ($value->getData4() as $item4) {
                    $sheet->setCellValue($columns[$c] . $r, $item4);
                    $c3r++;
    }
    
    $r += max(count($value->getData3()), count($value->getData4()));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question