TP6之批量导入2
1 <?php 2 3 declare(strict_types=1); 4 5 namespace app\api\controller\console; 6 7 use app\api\model\Orepipe as OrepipeModel; 8 use PhpOffice\PhpSpreadsheet\IOFactory; 9 10 11 use think\Request; 12 13 14 class Orepipe 15 { 16 /** 17 * 批量导入 18 * @param Request $request 19 * @param Orepipe $Orepipe 20 * @return \think\Response 21 */ 22 public function importPost(Request $request, OrepipeModel $OrepipeModel) 23 { 24 $file = $request->file(); 25 26 validate([ 27 'file' => 'require|file|fileExt:xlsx', 28 ])->check($file); 29 30 $path = app('filesystem')->disk('local')->putFile('import', $file['file'], function () { 31 return 'orepipe_' . time(); 32 }); 33 34 $objRead = IOFactory::createReader('Xlsx'); 35 $objRead->setReadDataOnly(true); //则只读内容,提升读取Excel效率 36 $obj = $objRead->load(config('filesystem.disks.local.root') . '/' . $path); //建立excel对象 37 38 if($obj) 39 { 40 $sheetContent = $obj->getSheet(0)->toArray(); //获取指定的sheet表 41 unset($sheetContent[0]); 42 43 $data = []; 44 $i = 0; 45 //读取内容 46 foreach($sheetContent as $k => $v) 47 { 48 $data[$k]['number'] = $v[1]; 49 $data[$k]['name'] = $v[3]; 50 $data[$k]['address'] = $v[4]; 51 $data[$k]['title'] = $v[5]; 52 $data[$k]['product_scale'] = $v[9]; 53 $data[$k]['mining_area'] = $v[10]; 54 $data[$k]['coordinate'] = ''; 55 $i++; 56 } 57 $info = $OrepipeModel->saveAll($data); 58 if( $info ) 59 { 60 return JsonSuccess('导入成功'); 61 }else{ 62 return JsonError('导入失败'); 63 } 64 }else{ 65 return JsonError('请上传表格'); 66 } 67 } 68 /** 69 * 下载模板表格 70 * @return 71 */ 72 public function tempGet() 73 { 74 $file = getcwd().'/storage/矿区许可证.xlsx'; 75 header('content-type:application/octet-stream'); 76 header('content-disposition:attachment; filename=' . basename($file)); 77 header('content-length:' . filesize($file)); 78 return file_get_contents($file); 79 } 80 }
作者:糖粿
来源:博客园
转载请注明原文链接:https://www.cnblogs.com/silen0119/p/15128286.html
声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。