php实现下载模板与上传模板解析

<?
//下载模板的请求
if(isset($_GET['action']) && $_GET['action'] =='down_group_excel'){
    $code = down_excel_templates('t_group');
}

//下载excel模板
function down_excel_templates($type = 't_group_member'){
    if(strcasecmp($type, 't_group_member') === 0){
        $filename = 'student模板';
    }else{
        $filename = 'group模板';
    }
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:filename=".$filename.".xls");
    $data = get_execl_template($type);
    $strexport = '';
    foreach($data AS $v){
        $strexport .= $v . "	";
    }
    $strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport);
    exit($strexport);
}

//获取模板数据
function get_execl_template($type = 't_group_member'){
    $data = [
        't_group_member' => [
            'student_id' => '学号', //key对应数据表wp_t_group_member的字段
            'user_name'  => '姓名',
            'pinyin'     => '拼音',
            'user_email' => '邮箱',
            'group_name' => '组织名称',
            'role'       => '角色(填学生*或讲师)'
        ],
        't_group' => [
            'group_name' => '开课班名', //key对应数据表wp_t_group的字段
            'org_name'   => '组织名',
            'course_name'=> '课程名',
            'start_time' => '开始时间',
            'end_time'   => '结束时间',
        ],
    ];
    if(!array_key_exists($type, $data)){
        //key不存在
        $type = 't_group_member';
    }
    return $data[$type];
}


//上传文件的请求
if(isset($_POST['action']) && $_POST['action'] =='import_group'){
    import_excel('group');
}
/**
 * 验证上传的文件
 * @param FILES $filename; $_FILES
 * @param FILES $tmp_name; $_FILES
 * @param string $type; 二级目录
 * @param string $root_path; 指定目录
 **/
function validate_upload_file($filename, $tmp_name, $type = 'excel', $root_path = '' ){
    if(!$filename || !$tmp_name){
        return false;
    }
    //判断文件格式
    $path_parts = pathinfo($filename);
    $extension = strtolower($path_parts['extension']) ;
    if ( !in_array($extension, array('xls','xlsx'))) {
        echo json_encode( ['code' => 1, 'msg' => "文件格式不正确,请重新选择" ]);exit;
    }
    //判断目录是否指定,不指定为默认
    $type = 'excel';
    if(!$root_path) {
        $root_path = "./upload/$type/" . date('Y-m-d', time()) . "/";
    }
    //检查文件或目录是否存在
    if(!file_exists($root_path)) {
        @mkdir($root_path,0777,true);
        @chmod($root_path,0777);
    }
    //上传后的文件名
    $rand_name = substr(md5(rand(10,99)), 0,4) ;
    $name = date('YmdHis').$rand_name.'.'.$extension ;
    $real_file  = $root_path.$name;  //上传后的文件名地址
    //移动上传文件
    $result = move_uploaded_file($tmp_name, $real_file);
    return ['name' => $name, 'real_file' => $real_file, 'result' => $result];
}
/**
 * 导入数据
 * @param string $name <input>控件的名称
 * @param string $type; 二级目录
 * @param string $root_path; 指定目录
 **/
function import_excel($name = '', $type = 'excel', $root_path = ''){
    if($_FILES && isset($_FILES[$name]['name'])){
        $filename = $_FILES[$name]['name'];
        $tmp_name = $_FILES[$name]['tmp_name'];
        //验证文件并导入
        $table = 't_group_member';
        if(strcasecmp($name,'group') === 0){
            $table = 't_group';
        }
        $result = importdata( $filename, $tmp_name,$table, $type, $root_path);
        if(is_array($result)){
            echo json_encode(['code' => 1,'data' => $result, 'msg' => '有部分上传失败!详情按F12查看']);exit;
        }
        echo json_encode(['code' => 0, 'msg' => 'success']);exit;
    }else{
        echo json_encode(['code' => 1, 'msg' => '请选择文件!']);exit;
    }
}

/**
 * 验证上传的文件
 * @param FILES $filename; $_FILES
 * @param FILES $tmp_name; $_FILES
 * @param string $type; 二级目录
 * @param string $root_path; 指定目录
 **/
function importdata ($filename, $tmp_name ,$table = '',$type = 'excel', $root_path = '') {
    //设置超时时间
    set_time_limit(0);
    //引入phpexcel
    require_once(__LIB__ . "PHPExcel/Classes/PHPExcel.php");
    require_once(__LIB__ . "PHPExcel/Classes/PHPExcel/IOFactory.php");
    require_once(__LIB__ . "PHPExcel/Classes/PHPExcel/Reader/Excel5.php");
    //验证
    $msg = [];
    $data = validate_upload_file( $filename, $tmp_name ,$type, $root_path);
    $result = $data['result'];
    $real_file = $data['real_file'];
    if ( $result ) {
        $PHPExcel = new PHPExcel() ;
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if( !$PHPReader->canRead($real_file) ){
            $PHPReader = new PHPExcel_Reader_Excel5();
            if( !$PHPReader->canRead( $real_file ) ){
                echo json_encode( ['code' => 1, 'msg' => "文件不可读,请重新选择" ]);exit;
            }
        }
        $_excelData = array() ;
        //读取excel
        $PHPExcel = $PHPReader->load( $real_file );
        //获取工作表的数目
        $sheet_count = $PHPExcel->getSheetCount();
        for ( $i = 0; $i < $sheet_count; $i++ ) {
            $_currentSheet = $PHPExcel->getSheet( $i ) ;
            $_allRow = $_currentSheet->getHighestRow(); //获取Excel中信息的行数
            $_allColumn = $_currentSheet->getHighestColumn();//获取Excel的列数
            $highestRow = intval( $_allRow ) ;
            $highestColumn = PHPExcel_Cell::columnIndexFromString($_allColumn);//有效总列数
            $field = array_keys(get_execl_template($table)); //获取模板的字段顺序
            for( $row = 2; $row <= $highestRow; $row++ ) {
                for ($col = 0; $col < count($field); $col++) { //列只获取模板的字段个数
                    $_excelData[$field[$col]] = $_currentSheet->getCellByColumnAndRow($col, $row)->getValue();
                }
                if (empty($_excelData)) {
                    $msg[] = array('s_type' => "导入失败", 'do_content' => $filename . " 下 Sheet" . ($i + 1) . " 中第 " . $row . " 行导入失败", 'do_time' => date("Y-m-d H:i:s"));
                    unset($_excelData);
                    continue;
                }
                if ($_excelData) {
                    //插入数据库
                    $code = insert_table($table, $_excelData);
                    if($code !== true){
                        $msg[] = array('s_type' => "插入失败", 'do_content' => $filename . " 下 Sheet" . ($i + 1) . " 中第 " . $row . " 行插入失败:".$code, 'do_time' => date("Y-m-d H:i:s"));
                    };
                }
                unset($_excelData);
            }
        }
        if($msg) {
            return $msg;
        }
    }else{
        echo json_encode( ['code' => 1, 'msg' => "文件上传失败,请重新选择" ]);exit;
    }
}

/**
 * 将数据添加到对应的表中
 * @param string $table ; 数据表名
 * @param array  $data  ; 添加的数据
 * @return string true添加成功,其他是错误信息
**/
function  insert_table($table = '', $data = []){
    global $db;
    if(!$table || !$data || !is_array($data)){
        return false;
    }
    //验证是否数据正确
    switch($table){
        case 't_group_member':
            //验证t_group_member模板的数据,然后保存
           //出错可根据需要,是否还继续。不继续 return '错误信息';
            break;
        case 't_group':
             //验证t_group模板的数据,然后保存
            break;
            default:
            return '没有该模板的数据!';
          break;
    }
    return true;
}
原文地址:https://www.cnblogs.com/f-rt/p/10408216.html