Home > Article > Backend Development > TP5 import database
This article mainly introduces the TP5 import database, which has certain reference value. Now I share it with everyone. Friends in need can refer to the
html page code theme:
<form method="post" action="{:url('Index/savestudentImport')}" class="form-signin" enctype="multipart/form-data" > <p> <select name="themeid"> {volist name="theme" id="v"} <option value="{$v.id}">{$v.title}</option> {/volist} </select> </p><br /> <input name="excel" type="file" class="form-control"> <br /><br /> <button class="btn btn-lg btn-primary btn-block">导入</button> </form>
Controller receiving code:
public function savestudentImport(){ //import('phpexcel.PHPExcel', EXTEND_PATH);//方法二 vendor("PHPExcel.PHPExcel"); //方法一 $objPHPExcel = new \PHPExcel(); $themeid=input('post.themeid');//导入数据类型 //获取表单上传文件 $file = request()->file('excel'); $info = $file->validate(['size'=>1567800,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel'); if($info){ $exclePath = $info->getSaveName(); //获取文件名 $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath; //上传文件的地址 $objReader =\PHPExcel_IOFactory::createReader('Excel5'); $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8'); //加载文件内容,编码utf-8 echo "<pre class="brush:php;toolbar:false">"; $excel_array=$obj_PHPExcel->getsheet(0)->toArray(); //转换为数组格式 array_shift($excel_array); //删除第一个数组(标题); $data = []; $i=0; foreach($excel_array as $k=>$v) { $data[$k]['title'] = $v[1]; $data[$k]['optiona'] = $v[2]; $data[$k]['optionb'] = $v[3]; $data[$k]['optionc'] = $v[4]; $data[$k]['optiond'] = $v[5]; $data[$k]['optione'] = $v[6]; $data[$k]['optionf'] = $v[7]; $data[$k]['time'] = date('Y-m-d H:i:s',time()); $data[$k]['themeid'] = $themeid; $i++; } $success=Db::name('sleeptopic')->insertAll($data); //批量插入数据 //$i= $error=$i-$success; echo "总{$i}条,成功{$success}条,失败{$error}条。"; // Db::name('t_station')->insertAll($city); //批量插入数据 }else{ // 上传失败获取错误信息 echo $file->getError(); } }
Related recommendations:
Tp5 project modification database
Sharing examples of table generation in phpexcel in tp5
The above is the detailed content of TP5 import database. For more information, please follow other related articles on the PHP Chinese website!