下面由Laravel教程栏目给大家介绍Laravel Excel3.0导出方法,希望对需要的朋友有所帮助!
导出方法抽离:
<?PHPnamespace App\Exports;use Maatwebsite\Excel\Concerns\FromCollection;use Maatwebsite\Excel\Concerns\ShouldautoSize;use Maatwebsite\Excel\Concerns\WithColumnFormatting;use Maatwebsite\Excel\Concerns\WithCustomValueBinder;use Maatwebsite\Excel\Concerns\WithEvents;use Maatwebsite\Excel\Concerns\WithStrictNullComparison;use Maatwebsite\Excel\Events\AfterSheet;use PHPOffice\PHPSpreadsheet\Cell\StringValueBinder;use PHPOffice\PHPSpreadsheet\Style\NumberFormat;class Export extends StringValueBinder implements FromCollection, ShouldautoSize,WithColumnFormatting,WithCustomValueBinder,WithStrictNullComparison,WithEvents{ private $row; private $data; private $mergeCell; private $columnname; private $formatNumber; /* * $mergeCell $columnname :合并单元格所需参数; * $mergeCell 需要合并的位置数组以MAP形式存储 [开始行=>结束行] * $columnname 需要合并列 与合并行数结合使用ARRAY存储 ['A','B'] */ public function __construct($row,$data,$mergeCell=null,$columnname=null,$formatNumber=[]) { $this->row = $row; $this->data = $data; $this->mergeCell = $mergeCell; $this->columnname = $columnname; $this->formatNumber = $formatNumber; } public function collection() { $row = $this->row; $data = $this->data;//设置表头 foreach ($row[0] as $key => $value) { $key_arr[] = $key; }//输入数据 foreach ($data as $key => &$value) { $Js = []; for ($i=0; $i < count($key_arr); $i++) { $Js = array_merge($Js,[ $key_arr[$i] => $value[ $key_arr[$i] ] ]); } array_push($row, $Js); unset($val); } return collect($row); } public function registerEvents(): array { // Todo: Implement registerEvents() method. if ($this->mergeCell && $this->columnname){ return [ AfterSheet::class => function(AfterSheet $event){ foreach ($this->columnname as $column){ foreach ($this->mergeCell as $key=>$value){ $event->sheet->getDelegate()->mergeCells($column.$key.':'.$column.$value); } } } ]; } return []; } public function columnFormats(): array{ $formatNumber = []; foreach ($this->formatNumber as $column){ $formatNumber[$column] = NumberFormat::FORMAT_TEXT; } return $formatNumber; }}
使用:
/*表头表体都为二维数组*/$row=[['row1'=>'列1','row2'=>'列2']];/*与表头key对应,缺少数据报错*/$List=[['row1'=>'行1列1','row2'=>'行1列2'],['row1'=>'行2列1','row2'=>'行2列2']];/*将第一行到第三行,第五行到第七行的A,B,C列各自合并*/$mergeCell=[1=>3,5=>7];$columnname=["A","B","C"];/*数字过长的列转换格式防止科学计数*/$formatNumber=['A','B','C'];//上方A,B,C列都为示意,根据自己需求调整,对应EXCEL的列return Excel::download(new Export($row,$List,$mergeCell,$columnname,$formatNumber),'filename');总结
以上是内存溢出为你收集整理的Laravel Excel3.0如何导出全部内容,希望文章能够帮你解决Laravel Excel3.0如何导出所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)