tp5 Excel导入
要处理的表格
1.建表
2.将PHPExcel类文件复制到框架中extend目录下
3.视图层
<form action="{:url('index/excel_add')}" method="post" enctype="multipart/form-data">
<h2>Excel导入</h2>
<table>
<tr>
<td>
<input type="file" name="excel">
</td>
<td>
<input type="submit">
</td>
</tr>
</table>
</form>
4.控制器层
<?php
namespace app\index\controller;
use think\Controller;
use think\Loader;
use think\Request;
class Index extends Controller
{
public function index()
{
return view();
}
public function excel_add(){
//限制大小
ini_set('memory_limit','1024M');
//引入类文件
Loader::import('PHPExcel.Classes.PHPExcel');
//实例化上传类
$excelobj = new \PHPExcel();
//接收文件
$file = $_FILES['excel'];
//获取后缀名并改为小写
$extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
//判断Excel版本
if ($extension=='xlsx'){
$readobj = \PHPExcel_IOFactory::createReader('excel2007');
}else{
$readobj = \PHPExcel_IOFactory::createReader('excel5');
}
//读取数据并处理
$res = $readobj->load($file['tmp_name']);
$arr = $res->getSheet(0)->toArray();
unset($arr[0]); //删除第一行表头
foreach ($arr as $k =>$val){
$list[$k]['name']=$val[0];
$list[$k]['sex']=$val[1];
$list[$k]['age']=$val[2];
$list[$k]['class']=$val[3];
$list[$k]['type']=$val[4];
}
//执行添加
if (Db('student')->insertAll($list)){
$this->success('导入成功');
}
}
}