当前位置: 首页 > 后端技术 > PHP

PHP导出Excel的优化

时间:2023-03-29 19:07:30 PHP

背景PHP导出Excel的优化在我之前的文章:PHP内存溢出的思考中有介绍,本文主要介绍一个高性能的导出组件--xlswriter,他是一个PHPC扩展名,官方文档地址,请点击。安装pecl当我们发现没有安装pecl时,我们需要安装pecl。一般情况下安装在PHP安装目录下。示例命令如下:#进入PHP安装目录cd/usr/local/php/bincurl-ogo-pear.phphttp://pear.php.net/go-pear.pharphpgo-pear.php#安装完成后,软链接到bin目录下ln-s/usr/local/php/bin/pecl/usr/bin/peclinstallxlswriterpeclinstallxlswriter#在ini中添加extension=xlswriter.so配置使用可以参考到官方文档,里面会有更详细的介绍。这是我在最后一段中使用的代码:封装的导出服务/***下载*@param$header*@param$data*@param$fileName*@param$type*@returnbool*@throws*/public函数下载($header,$data,$fileName){$config=['path'=>$this->getTmpDir().'/',];$now=date('YmdHis');$文件名=$文件名。$现在。'.xlsx';$xlsxObject=new\Vtiful\Kernel\Excel($config);//初始化文件$fileObject=$xlsxObject->fileName($fileName);//设置样式$fileHandle=$fileObject->getHandle();$format=new\Vtiful\Kernel\Format($fileHandle);$样式=$format->bold()->background(\Vtiful\Kernel\Format::COLOR_YELLOW)->align(Format::FORMAT_ALIGN_VERTICAL_CENTER)->toResource();//将数据写入文件......$fileObject->header($header)->data($data)->freezePanes(1,0)->setRow('A1',20,$style);//输出$filePath=$fileObject->output();//下载header("Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");header('Content-Disposition:attachment;filename="'.$fileName.'"');header('缓存控制:max-age=0');header('Content-Length:'.filesize($filePath));header('内容传输编码:二进制');header('缓存控制:必须重新验证');header('Pragma:public');ob_clean();冲洗();if(copy($filePath,'php://output')===false){thrownewRuntimeException('导出失败');}//删除临时文件@unlink($filePath);返回真;}/***获取临时文件夹*@returnfalse|string*/privatefunctiongetTmpDir(){//目录可以自定义//return\Yii::$app->params['downloadPath'];$tmp=ini_get('upload_tmp_dir');如果($tmp!==False&&file_exists($tmp)){returnrealpath($tmp);}returnrealpath(sys_get_temp_dir());}/***读取文件*@param$path*@param$fileName*@returnarray*/publicfunctionreadFile($path,$fileName){//读取测试文件$config=['path'=>$path];$excel=new\Vtiful\Kernel\Excel($config);$data=$excel->openFile($fileName)->openSheet()->getSheetData();返回$数据;}调用点的代码导出/***export*/publicfunctionactionExport(){try{/***@var$searchModelSkuBarCodeSearch*/$searchModel=Yii::createObject(SkuBarCodeSearch::className());$queryParams['SkuBarCodeSearch']=[];$result=$searchModel->search($queryParams,true);$格式数据=[];if(!empty($result)){foreach($resultas$key=>&$value){$tmpData=['sku_code'=>$value['sku_code'],'bar_code'=>$value['bar_code'],'created_at'=>$value['created_at'],'updated_at'=>$value['updated_at'],];$formatData[]=array_values($tmpData);}未设置($值);}$fields=['sku_code'=>'SKU编码','bar_code'=>'条形码','created_at'=>'创建时间','updated_at'=>'更新时间',];/***@var$utilServiceUtilService*/$utilService=UtilService::getInstance();$utilService->download(array_values($fields),$formatData,'sku_single_code');}catch(\Exception$e){Yii::$app->getSession()->setFlash('error','Exportfailed');}}importpublicfunctionactionImportTmpSku(){try{/***@var$utilServiceUtilService*/$utilService=UtilService::getInstance();$path='/tmp/';//文件目录$fileName='sku_0320.xlsx';$excelData=$utilService->readFile($path,$fileName);取消设置($excelData[0]);$excelData=array_merge($excelData);//......业务代码}catch(\Exception$e){echo$e->getMessage();出口;}}结论整体使用后,在处理大量数据时,性能确实比原来的PHPExcel高很多。文章如有错误,请指出。文章起始地址:https://tsmliyun.github.io/ph...