Laravel 与 Maatwebsite

Laravel with Maatwebsite

我想更改列标题的名称。 你好吗?

这是控制器中的代码:

public function  excelterima($nm_perusahaan){
    if($user = Auth::user()->admin == 2){
        $users = Mstbeasiswa::select('NO_ANGGOTA', 'NM_ANGGOTA', 'GOLONGAN', 'NPK', 'CABANG', 'NM_ANAK', 'NM_SKL', 'id')
                 ->where('flag_terima', '1')
                 ->where('NM_PERUSAHAAN', $nm_perusahaan)
                 ->orderBy('id', 'asc')
                 ->get()->toArray();

        //work on the export
        Excel::create($nm_perusahaan, function($excel) use ($users){
            $excel->sheet('sheet 1', function($sheet) use ($users)
            {
                $sheet->fromArray($users);
                ob_end_clean();
            });
        })->download('xlsx');
        return redirect('/beasiswaditerima');   
    }else{
      return redirect('/home');   
    }
}

输出电流:

默认情况下,LaravelExcelWorksheet 实例的 fromArray() 方法将 auto-generate 基于给定数组键的标题。为了禁用此 auto-generation,您需要将 false 传递给第五个参数($headingGeneration)。这是供您参考的 fromArray() 方法签名:

public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false, $headingGeneration = true)

您可以使用 row() 方法添加自定义标题。使用您的代码示例,现在代码应如下所示:

$users = Mstbeasiswa::select('NO_ANGGOTA', 'NM_ANGGOTA', 'GOLONGAN', 'NPK', 'CABANG', 'NM_ANAK', 'NM_SKL', 'id')
    ->where('flag_terima', '1')
    ->where('NM_PERUSAHAAN', $nm_perusahaan)
    ->orderBy('id', 'asc')
    ->get()
    ->toArray();

Excel::create($nm_perusahaan, function ($excel) use ($users) {
    $excel->sheet('sheet 1', function ($sheet) use ($users) {
        // Set your custom header.
        $sheet->row(1, ['COL1', 'COL2', 'COL3', 'COL4', 'COL5', 'COL6', 'COL7', 'COL8']);

        // Set the data starting from cell A2 without heading auto-generation.
        $sheet->fromArray($users, null, 'A2', false, false);
    });
})->download('xlsx');

或者您实际上可以保持 fromArray() 方法调用,但稍后将 auto-generated header 替换为 row() 方法,如下所示:

$excel->sheet('sheet 1', function ($sheet) use ($users) {
    $sheet->fromArray($users);

    // Replace the header, but this should come after fromArray().
    $sheet->row(1, ['COL1', 'COL2', 'COL3', 'COL4', 'COL5', 'COL6', 'COL7', 'COL8']);
});

希望对您有所帮助!