0

I want to change the name of the column heading. How do you do?

This is the code in the controller:

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');   
    }
}

output current:

current OUTPUT

Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
Siti Rahmah
  • 267
  • 1
  • 3
  • 15

1 Answers1

1

By default the fromArray() method of LaravelExcelWorksheet instance will auto-generate the heading for you based on the given array keys. In order to disable this auto-generation, you need to pass false to the fifth parameter (the $headingGeneration). Here's the fromArray() method signature for your reference:

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

You can use the row() method to add a custom heading. Using your code example, now the code should look like this:

$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');

Or you can actually just keep the fromArray() method calling, but later replace the auto-generated header with row() method like so:

$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']);
});

Hope this help!

Risan Bagja Pradana
  • 4,494
  • 1
  • 20
  • 22
  • Can you help me with this question https://stackoverflow.com/questions/54244168/laravel-excel-not-exporting-in-correct-format?noredirect=1#comment95315360_54244168 – Geoff_S Jan 18 '19 at 01:48