Answer the question
In order to leave comments, you need to log in
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:
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:
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
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 questionAsk a Question
731 491 924 answers to any question