与导入对比。项目中导出场景比较多。估计有十多个出口。我之前写了导入,这将添加导出。安装前说了,这里说一下配置。虽然有默认配置,但还是有修改配置的场景,所以建议生成配置文件。Configuration//Generateconfig/excel.phpphpartisanvendor:publish--provider="Maatwebsite\Excel\ExcelServiceProvider"配置只提了一个,其他注释都挺详细的,'csv'=>['delimiter'=>',','enclosure'=>'"','line_ending'=>PHP_EOL,//导出csv中文乱码,设置use_bom为true'use_bom'=>true,'include_separator_line'=>false,'excel_compatibility'=>false,],接下来我们来完成一个导出的demo,对一些常用的点进行说明。DEMOphpartisanmake:exportMultiExport生成文件如下:){//}}自定义sheet,添加WithTitle自定义列名,添加WithHeadings不想用Collection,替换FromCollection使用FromArray多张,替换FromCollection使用WithMultipleSheets转换后:date=$date;}publicfunctionsheets():array{$sheets=[];$sheets[]=newMultiExportA($this->date);$sheets[]=newMultiExportB($this->date);返回$表;}}---//MultiExportA,MultiExportB类比可以是date=$date;}publicfunctionheadings():array{return['ID','Name','Price','Mobile'];}/***@returnarray*/publicfunctionarray():array{$data=ExportA::where('date',$this->date)->get()->toArray();$ret=[];foreach($dataas$val){//一段神奇的代码计算价格$price=...;$ret[]=['id'=>$val['id']."\t",'name'=>$val['name'],'price'=>$price,//转换为文本,excel编码使用科学记数法'mobile'=>$瓦尔['移动']。"\t",];}返回$ret;}/***@returnstring*/publicfunctiontitle():string{return'FormA';}}使用//保存$obj=newMultiExport($date);Excel::store($obj,'MultiExport'.$date.'.xlsx');//下载csvExcel::download($obj,'MultiExport'.$date.'.csv',\Maatwebsite\Excel\Excel::CSV,['Content-Type'=>'text/csv']);思考问题当数据量过大时,导出时很可能会内存溢出建议:使用其他高性能组件,或者使用原生代码流式输出到浏览器,或者直接使用其他语言(比如go)写的文件太大,Excel在打开大数据文件时也很鸡肋,很容易卡顿甚至死机。文件导出,比如1w,一个文件的导出过程中的一部分可能会有计算,可以提前计算好,导出时直接读取表格,使用LazyCollection,使用LazyCollections提高LaravelExcel读取性能(轻松支持百万数据)
