拉腊维尔9|Laravel Excel 3.1-在一个单元格中分组多个记录

w7t8yxp5  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(114)

这是我的应用程序如何从我的应用程序生成报告(excel文件):

一个月一次
public function collection()
{
    return Actividad::whereMonth('fecha_inicio', '12')
                    ->whereYear('fecha_inicio', '2022')
                    ->orderBy('servicio_id', 'ASC')
                    ->with('servicio')
                    ->get();
}

public function headings(): array
{

    return [
        'SERVICIO',
        'DESCRIPCION',
    ];
}

public function map($actividad) : array 
{
    $nombre = [];
    $descripcion = [];
    foreach($actividad as $activity){
        // dump($actividad);
        $nombre[]=$actividad->descripcion;
        foreach($actividad->servicio as $key => $servicio){
            $descripcion = $actividad->servicio->nombre;
        }
    }
    return [
        [
            $nombre[0],
            $descripcion,
            '',
            '',
        ],
    ];
}

屏幕截图显示了4行中的4条记录,我想尝试转换一行中唯一单元格中的4条记录,如以下示例:

lymnna71

lymnna711#

您可以在视图中轻松完成此操作。https://docs.laravel-excel.com/3.1/exports/from-view.html

namespace App\Exports;

use App\Models\Actividad;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class ActividadesporTodosServiciosExport implements FromView
{
    public function view(): View
    {
        $actividades = Actividad::query()
            ->whereMonth('fecha_inicio', '12')
            ->whereYear('fecha_inicio', '2022')
            ->orderBy('servicio_id', 'ASC')
            ->with('servicio')
            ->get();

        return view('exports.your_view', [
            'actividades' => $actividades,
        ]);
    }
}

resources/views/exports/your_view.blade.php

<table>
  <thead>
    <tr>
      <th>SERVICIO</th>
      <th>DESCRIPCION</th>
    </tr>
  </thead>
  <tbody>
    @foreach($actividades as $actividad)
      <tr>
        <td>{{ $actividad->descripcion }}</td>
        <td>{{ $actividad->servicio->implode('nombre', "\n") }}</td>
      </tr>
    @endforeach
  </tbody>
</table>

或者使用rowspan属性获取电子表格中的分组单元格

<table>
  <thead>
    <tr>
      <th>SERVICIO</th>
      <th>DESCRIPCION</th>
    </tr>
  </thead>
  <tbody>
    @foreach($actividades as $actividad)
      <tr>
        <td rowspan="{{ $actividad->servicio->count() + 1">{{ $actividad->descripcion }}</td>
      </tr>
      @foreach($actividad->servicio as $servicio)
        <tr>
          <td>{{ $servicio->nombre }}</td>
        </tr>
      @endforeach
    @endforeach
  </tbody>
</table>

相关问题