How to generate dynamic columns using Maatwebsite Excel in Laravel 5.1

6k views Asked by At

I can generate rows dynamically like this

$row_count = 2;
for($i=0; $i < count($student_data); $i++) {
  $sheet->Row($row_count, array(
    $student_data[$i]->stud_number, 
    $student_data[$i]->first_name .' ' .$student_data[$i]->last_name 
  ));
  $row_count++;
}

$sheet->cells('A1:I'.$row_count, function($cells) {
  $cells->setAlignment('center');
}); 

But I can't generate column dynamically, I want to do something like this

$current_column = 'C';
for($i=0; $i < count($subject_data); $i++) {
  //I want here my column incremented by 1 like D, E, F, G....
  //Do something..
}
3

There are 3 answers

0
baikho On BEST ANSWER

You can increment alphabetically too:

$current_column = 'C';

for($i=0; $i < count($subject_data); $i++) {
    print $current_column; // Will be C, D, E, etc...
    $current_column++; // Increment letter
}
0
vijaykumar On

As per doc you can manpulate any cell by cell name

$sheet->cell('A1', function($cell) {

    // manipulate the cell
    $cell->setValue('data1');

});
0
pankaj On

I am using user model. so you can check this soltion.

 $data =  User::get();  // Model 

  Excel::create('Project_sheet', function($excel) use($data)  {
        $excel->sheet('user_list', function($sheet) use( $data ) {

            $from = "A1"; // or any value
            $to = "G1"; // or any value

            //$sheet->getActiveSheet()->mergeCells('A1:G1');
            //$sheet->getActiveSheet()->setCellValue('A1','The quick brown fox.');


            $sheet->getStyle("$from:$to")->getFont()->setBold( true );
            $sheet->getStyle("$from:$to")->getFont()->setSize( '12' );
            $sheet->setBorder("$from:$to", 'thin' );
            // Set background color for a specific cell
            $sheet->getStyle("$from:$to")->applyFromArray(array(
                'fill' => array(
                    'type'  => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'A5D9FF')
                )
            ));
            $sheet->fromArray($data);
        });
    })->export('xls');