PHP+Excel导入

<form action="{:url('index/excel')}" method="post" enctype="multipart/form-data">
        <tr>
            <td><input type="file" name="excel"></td>
            <td><input type="submit" value="导入"></td>
        </tr>
    </form>
<?php
namespace app\index\controller;
use app\index\model\Index as u;
use app\index\model\PHPExcel;
use think\Controller;
use think\Db;
use think\Request;
use think\loader;
class index extends Controller{
    public function index(){
     return view();
    }
    public function excel(){
        //上传文件的最大限制
        ini_set("menmory_limit",'1024');
        //加载第三方文件
        loader::import("PHPExcel.Classes.PHPExcel");
        //防止乱码
        header("Content-type:text/html;charset=utf-8");
        //实例化文件
        $PHPExcel=new \PHPExcel();
        //接收前台接受的文件
        $file=$_FILES['excel'];
        //把他们都转化为小写
        $extension=strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
        //print_r($_FILES);die;
        if($extension=='xlsx'){
            //2007
            $objReader=\PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            //2003
            $objReader=\PHPExcel_IOFactory::createReader('Excel5');
        }
//        die();
        //查看打开的文件内容
        $Content=$objReader->load($file['tmp_name']);
        //查看有几个sheet
        $sheetContent=$Content->getSheet(0)->toArray();
        unset($sheetContent[0]);
        foreach($sheetContent as $k =>$v){
            $arr['user']=$v[0];
            $arr['iphone']=$v[1];
            $res[]=$arr;
        }
//        print_r($res);die;
        $rest=Db::table('www')->insertAll($res);
        if($rest){
            $this->success('添加成功','show');
        }else{
            $this->error('添加失败');
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_42780341/article/details/82687582