/**
* csv导入mysql
* @param Request $request
* 安装,导入 导出 参照手册 https://www.helloweba.net/php/561.html
*/
public function uploadCSV(Request $request) { // 如果是 POST 方法才读取文件 if ($request->isMethod(‘POST‘)){ $file = $request->file(‘select_file‘); $ext = $file->getClientOriginalExtension(); //扩展名 $extensions = [‘csv‘]; if(!in_array($ext, $extensions)) Base::output([‘code‘=>601]); // 原文件名 $originalName = $file->getClientOriginalName(); // 临时绝对路径 $realPath = $file->getRealPath(); // 修改文件名 $filename = date(‘Ymdhis‘).uniqid(‘_‘,‘‘).$originalName; // 储存到磁盘相应的路径 $bool = Storage::disk(‘uploads‘)->put($filename,file_get_contents($realPath)); //判断是否上传成功 if($bool) { $path = public_path(‘uploads/‘ . date(‘Ymd‘)) . ‘/‘ . $filename; $reader = IOFactory::createReader(‘Csv‘); $reader->setReadDataOnly(TRUE); $spreadsheet = IOFactory::load($path);//载入csv表格 $worksheet = $spreadsheet->getActiveSheet(); $highestRow = $worksheet->getHighestRow(); // 总行数 $highestColumn = $worksheet->getHighestColumn(); // 总列数 $lines = $highestRow - 1; //过滤掉第一行的标题,从第二行正式数据开始 if ($lines <= 0) { Base::output([‘code‘=>602]); } //至此上传表格成功,我们可以运用 PhpSpreadSheet 所提供的方法来获取表格的数据,存入数据库 //从第二行开始循环遍历 for ($row = 2; $row <= $highestRow; ++$row) { $AEtop = new AetopModel(); $ats_name = $worksheet->getCellByColumnAndRow(1, $row)->getValue(); //产品名 $ats_price = $worksheet->getCellByColumnAndRow(2, $row)->getValue(); //价格 $ats_url = $worksheet->getCellByColumnAndRow(3, $row)->getValue(); //url $obj = $AEtop->select(‘id‘)->where(‘ats_name‘, $ats_name)->first(); if($obj){ $AetopModel = AetopModel::find($obj[‘id‘]); $AetopModel->ats_name = $ats_name; $AetopModel->ats_price = $ats_price; $AetopModel->ats_url = $ats_url; try{ //更新db $res = $AetopModel->save(); }catch (\Exception $e){ Tool::DBlog($e->getMessage()); } }else{ $AEtop->ats_name = $ats_name; $AEtop->ats_price = $ats_price; $AEtop->ats_url = $ats_url; try{ //保存db $res = $AEtop->save(); }catch (\Exception $e){ Tool::DBlog($e->getMessage()); } } } if($res) Base::output([‘code‘=>200]); } }
excel格式:
注:我需要传csv格式;请大家自行优化,这是没有优化的版本,比较直观,其中Base::output(
)大家不用理会,是我自己封装的报错函数