页面和command命令行双导入的实现
需求描述:
excel的导入逻辑在web页面和command均可以,command可以显示导入进度条功能。
实现思路:
- 创建excel导入类的实现ImportVersionAtomextra,实现接口ToModel, WithHeadingRow, WithBatchInserts,不实现接口WithProgressBar;
- 创建excel导入类的command实现ImportVersionAtomextraCmd,继承ImportVersionAtomextra并同时实现WithProgressBar接口;
- 在command逻辑调用ImportVersionAtomextraCmd的实例;
- 在文件上传逻辑调用ImportVersionAtomextra的实例。
关键代码
excel导入类的实现
class ImportVersionAtomextra implements ToModel, WithHeadingRow, WithBatchInserts { public function model(array $row) { //逻辑实现略 } public function batchSize(): int { return 100; } }
excel导入类的command实现
class ImportVersionAtomextraCmd extends ImportVersionAtomextra implements WithProgressBar { use Importable; }
command逻辑调用
class importVersionAtomExtraExcel extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'import:versionatomextra {versionid : The ID of the version for product} {filepath : the file path}'; /** * The console command description. * * @var string */ protected $description = 'import version atom\'s extra information from excel'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->output->title('Starting import'); $this->info('1. Starting sendfile.'); Storage::delete('allparalist.xlsx'); Storage::putFileAs('', new File($this->argument('filepath')), 'allparalist.xlsx'); $this->output->text('Import successful'); $this->info('2. Starting import version atom extra info.'); $VerionAtomextra = new ImportVersionAtomextraCmd; $VerionAtomextra->versionid = $this->argument('versionid'); $VerionAtomextra->withOutput($this->output)->import('storage\app\allparalist.xlsx'); Storage::delete('allparalist.xlsx'); $this->output->success('Import successful'); } }
文件上传逻辑调用
// $model ... try{ // $request ... $file = $request->file('file'); $ImportVersionAtomextra = new ImportVersionAtomextra; Excel::import($ImportVersionAtomextra,$file); return $this->response()->success('Import success...')->refresh(); } catch (\Exception $e){ return $this->response()->error($e->getMessage()); }
// $model ... try{ // $request ... $file = $request->file('file'); $ImportVersionAtomextra = new ImportVersionAtomextra; Excel::import($ImportVersionAtomextra,$file); return $this->response()->success('Import success...')->refresh(); } catch (\Exception $e){ return $this->response()->error($e->getMessage()); }
推荐文章: