文章目錄
- 一、前提
- 二、使用
- 2.1、新建一個導入文件
- 2.2、新建一個控制器和方法,調用導入文件
- 2.3、 新建一個頁面,支持文件上傳
一、前提
想要將excel內容入庫,laravel有擴展可以使用,常用的擴展是maatwebsite/excel
,安裝步驟參考上一篇:laravel中安裝Maatwebsite/excel擴展
二、使用
2.1、新建一個導入文件
php artisan make:import 文件名稱 --model=Model地址
然后在里邊編寫你的導入邏輯
<?phpnamespace App\Imports;use App\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;class QuesExport implements ToArray, WithChunkReading, WithHeadingRow
{public function array(array $rows){$data = [];$now = date('Y-m-d H:i:s');foreach ($rows as $row) {$data[] = ['id' => $row['id'],'number' => 0,'parent_id' => 0,'type' => 1,'question' => $row['ques'],'standard_answer' => $row['answer'],'ai_ques_id' => $row['aiid'],'created_at' => $now];}if (!$data) {throw new ApiException('沒有要導入的數據');return false;};//全部導入DB::select('TRUNCATE table questions_copy1');DB::table('questions_copy1')->insert($data);return true;}public function chunkSize(): int{return 500;}public function headingRow(): int{return 1;}/*** @param Failure[] $failures*/public function onFailure(Failure ...$failures){// Handle the failures how you'd like.throw new ApiException('fhwaeurewsdf');}
}
2.2、新建一個控制器和方法,調用導入文件
/*** 導入excel,入庫** */public function uploadQues(Request $request){$file = $request->file('file');// 保存上傳文件$path = public_path('uploads/admin/ques');$this->mkdirs($path); // 已存在的路徑不會再創建$fileName = date('YmdHis') . '_' . uniqid() . '_' . '.' . strtolower($file->getClientOriginalExtension());$file->move($path, $fileName);// 讀取文件并入庫Excel::import(new QuesExport(), $path . '/' . $fileName);// 刪除上傳文件unlink($path . '/' . $fileName);return response()->json(['status'=>1,'msg'=>'',]);}
2.3、 新建一個頁面,支持文件上傳
我這里簡單寫了個頁面,如下:
<!DOCTYPE html>
<html >
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Laravel</title><script src="/js/jquery-3.3.1.min.js?v=2021123999" type="text/javascript" charset="utf-8"></script><meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="flex-center position-ref full-height"><div class="upload_box"><input type="file" name="file" accept="file" id="auth-upload" onchange="uploadFile();"/><div class="reload_file flex-v flex-vc flex-hc"><i class="icon icon_add"></i><p>文件</p></div></div>
</div><script>function uploadFile(){file = $("#auth-upload")[0].files[0];// alert(file);// alert(file.name);// return;file_name = file.name;ext = file_name.slice(file_name.lastIndexOf(".")+1).toLowerCase();imgMaxSize = 1024*1024*10;if (ext != 'xlsx' ) {swal('文件格式不正確');return ;}// if (file.size > imgMaxSize) {swal('文件大小超過10M'); return ;}formData = new FormData();// 自定義formData中的內容formData.append('file', file);formData.append('_token', '{{csrf_token()}}');$.ajax({type: 'POST',url: "/upload",data: formData,cache: false,processData: false,contentType: false,dataType:'json',success: function (data) {if (data.status){alert('成功');}else{alert('失敗');}}});}</script>
</body>
</html>