如何在Laravel 5.1中使用Maatwebsite Excel生成动态列

时间:2016-12-30 09:53:24

标签: laravel maatwebsite-excel

我可以像这样动态生成行

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

但是我无法动态生成列,我想做类似的事情

$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 个答案:

答案 0 :(得分:4)

您也可以按字母顺序递增:

$current_column = 'C';

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

答案 1 :(得分:0)

根据doc,您可以按单元名称对任何单元格进行操作

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

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

});

答案 2 :(得分:0)

我正在使用用户模型。因此您可以检查此解决方案。

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