场景
业务功能单据在已有添加、编辑功能的基础上,业务想增加使用 Excel 导入,同时将导入的结果使用原表的格式再返回给用户。
准备
- laravel
- OSS
- RDS MySQL
方案
- 用户通过 Web 页面上传 Excel 数据源。
- Web Server 收到请求后,将 Excel 上传至 OSS,并同时发 MQ 消息通知异步服务器。
- 异步服务器收到消息后从 OSS 下载 Excel,并根据业务逻辑处理数据。
- 异步服务器将数据存储至数据库。
- 异步服务器将处理结果写至 Excel,并将该结果上传至 OSS 后将文件下载链接发送给用户。
步骤
以下为 Excel 处理的主要步骤代码:
- 安装 Excel 插件
composer require phpoffice/phpexcel
- 下载 OSS 文件
//下载文件到本地 $$fileDownloadUrl = "文件下载链接,可以通过 MQ 消息获得"; $destinationFolder = 'storage/downloads/'; //这里的文件后缀可根据下载链接来进行处理 $newFname = $destinationFolder .time().'.xlsx'; $file = fopen ($fileDownloadUrl, "rb"); if ($file) { $newf = fopen($newFname, "wb"); if ($newf){ while(!feof($file)) { fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 ); } } } if ($file) { fclose($file); } if ($newf) { fclose($newf); }
- 读取 Excel 内容
//从excel读取数据 $filePath = "上一步骤中下载的本地文件的地址"; $PHPExcel = new \PHPExcel_Reader_Excel2007(); try { if (!$PHPExcel->canRead($filePath)) { //默认用excel2007读取excel,若格式不对,则用之前的版本进行读取 $PHPExcel = new \PHPExcel_Reader_Excel5(); } $PHPExcel->setReadDataOnly(true); //过滤excel中的特殊字符 $excel = $PHPExcel->load($filePath);//加载excel //读取excel文件中的第一个工作表 $data = $excel->getSheet(0)->toArray(); } catch (\Exception $e) { echo 'excel read error'.$e->getMessage(); }
- 导出 Excel
ini_set('memory_limit', '-1'); //文件保存的路径 $filePath = "storage/downloads/".time().".xlsx"; $objPHPExcel = new \PHPExcel(); $titles = ["姓名","性别","生日","学历"]; $dataList = [ ["张三","男","1995-01-01","本科"], ["张四","男","1995-01-02","本科"], ["张五","男","1995-01-03","本科"], ["张六","男","1995-01-04","本科"], ["张七","男","1995-01-05","本科"], ["张八","男","1995-01-06","本科"], ]; // 设置列宽 $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); //设置第一行为标题 foreach ($titles as $curColumn => $curValue) { $objPHPExcel->setActiveSheetIndex(0) ->setCellValueByColumnAndRow($curColumn, 1,$curValue); } //设置数据内容 foreach ($dataList as $curRow => $curValueList) { $curRow = $curRow+2; foreach ($curValueList as $curColumn => $curValue) { $objPHPExcel->setActiveSheetIndex(0) ->setCellValueByColumnAndRow($curColumn, $curRow,$curValue); } } $objPHPExcel->getActiveSheet()->setTitle('人员'); // sheet 名 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save($filePath); exit;