TP5中封装PHPEXCEL1.8导入数据以及图片功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TP5中封装PHPEXCEL1.8导入数据以及图片功能相关的知识,希望对你有一定的参考价值。

首先下载下来phpEXCEL1.8的类库(https://github.com/PHPOffice/PHPExcel)放到项目目录下面的extend下面即可。

技术分享

由于PHPEXCEL没有使用命名空间(namespace)的模式,所以在使用的只能使用全路径引入了。

// 引入PHPEXCEL类库
import(‘PHPExcel_IOFactory‘, EXTEND_PATH . "PhpExcel/PHPExcel/");
import(‘PHPExcel‘, EXTEND_PATH . "PhpExcel/");


使用到的Excel表格数据:

技术分享


处理图片用到的功能函数我放到了common.php公共文件里面:

PHPEXCEL类库里面已经涵盖了下面几个函数,但对处理表格里面的图片的时候并不好用,所以就提取出来放到公共文件里面了。

// 应用公共文件
define(‘EXCEL_EXTENSION_2003‘, "xls");
define(‘EXCEL_EXTENSION_2007‘, "xlsx");


/**
 * 处理Excel中图片
 *
 * @param string $file_name 文件名
 * @param string $full_path 文件完整路径
 */
function process_excel_image($file_name, $full_path)
{
    // 引入PHPEXCEL类
    import(‘PHPExcel_IOFactory‘, EXTEND_PATH . "PhpExcel/PHPExcel/");
    import(‘PHPExcel‘, EXTEND_PATH . "PhpExcel/");
    // 判断文件版本,选择对应的解析文件
    if(getExtendFileName($file_name) == EXCEL_EXTENSION_2003)
    {
        $reader = \PHPExcel_IOFactory::createReader(‘Excel5‘);
    }
    else if(getExtendFileName($file_name) == EXCEL_EXTENSION_2007)
    {
        $reader = new \PHPExcel_Reader_Excel2007();
    }

    // 解析Excel文件
    // $objPHPExcel = $objReader->load(ROOT_PATH . "public/uploads/" . $file_path);
    $PHPExcel = $reader->load($full_path);
    $worksheet = $PHPExcel->getActiveSheet();
    $imageInfo = extractImageFromWorksheet($worksheet, ROOT_PATH . "public/uploads/school/");

    return $imageInfo;
}

/**
 * 返回文件路径的信息
 *
 * @param string $file_name
 * @return string
 */
function getExtendFileName($file_name) {
     
    $extend = pathinfo($file_name);
    $extend = strtolower($extend["extension"]);
    return $extend;
}

/**
 * worksheet中提取image
 *
 * @param object $worksheet
 * @param string $basePath
 */
function extractImageFromWorksheet($worksheet,$basePath){
     
    $result = array();
     
    $imageFileName = "";
     
    foreach ($worksheet->getDrawingCollection() as $drawing) {
        $xy=$drawing->getCoordinates();
        $path = $basePath;
        // for xlsx
        if ($drawing instanceof \PHPExcel_Worksheet_Drawing) {
             
            $filename = $drawing->getPath();
             
            $imageFileName = $drawing->getIndexedFilename();
             
            // 可能是office版本的缘故,获取出来的图片文件名字
            // 很容易造成文件名重复导致图片被覆盖,这里做了一下
            // 处理对图片名字进行微秒的md5处理。
            // process imageFileName
            $tmp = explode(".", $imageFileName);
            $tmp[0] = md5(microtime(true));
            $tmp_fileName = implode(".", $tmp);
            // process imageFileName
                
            // $path = $path . $drawing->getIndexedFilename();
            $path = $path . $tmp_fileName;
             
            $boo = copy($filename, $path);
             
            $result[$xy] = $path;
             
            // for xls
        } else if ($drawing instanceof \PHPExcel_Worksheet_MemoryDrawing) {
             
            $image = $drawing->getImageResource();
             
            $renderingFunction = $drawing->getRenderingFunction();
             
            switch ($renderingFunction) {
                 
                case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:
                     
                    $imageFileName = $drawing->getIndexedFilename();
                    $path = $path . $drawing->getIndexedFilename();
                    imagejpeg($image, $path);
                    break;
                     
                case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:
                    $imageFileName = $drawing->getIndexedFilename();
                    $path = $path . $drawing->getIndexedFilename();
                    imagegif($image, $path);
                    break;
                     
                case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:
                    $imageFileName = $drawing->getIndexedFilename();
                    $path = $path . $drawing->getIndexedFilename();
                    imagegif($image, $path);
                    break;
                     
                case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:
                    $imageFileName = $drawing->getIndexedFilename();
                    $path = $path . $drawing->getIndexedFilename();
                    imagegif($image, $path);
                    break;
            }
            $result[$xy] = $imageFileName;
        }
    }
    return $result;
}


控制器中处理表格数据&图片并导入数据库表中:

    /**
     * 批量导入老师
     * 
     */
    public function t_bulk_add()
    {
        // 学校id
        $s_id = session(‘s_id‘);
        
        if ($this->request->method() == "POST") {
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file(‘excel‘);
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate([
                ‘size‘=>5242880,
                ‘ext‘=>‘xls,xlsx,csv‘
            ])->move(ROOT_PATH . ‘public‘ . DS . ‘uploads‘);
            
            if ($info) {
                $file_path = $info->getSaveName();
                $file_name = $info->getFileName();
                
                // 引入PHPEXCEL类库
                import(‘PHPExcel_IOFactory‘, EXTEND_PATH . "PhpExcel/PHPExcel/");
                import(‘PHPExcel‘, EXTEND_PATH . "PhpExcel/");
                // 判断文件版本,选择对应的解析文件
                if (‘xlsx‘ == $info->getExtension()) {
                    import(‘PHPExcel_Reader_Excel2007‘, EXTEND_PATH . "PhpExcel/PHPExcel/Reader/");
                    $objReader = \PHPExcel_IOFactory::createReader(‘Excel2007‘);
                } else {
                    import(‘PHPExcel_Reader_Excel5‘, EXTEND_PATH . "PhpExcel/PHPExcel/Reader/");
                    $objReader = \PHPExcel_IOFactory::createReader(‘Excel5‘);
                }
                $full_path = ROOT_PATH . "public/uploads/" . $file_path;
                
                // 解析Excel文件
                $objPHPExcel = $objReader->load($full_path);
                // 读取第一个工作表(编号从0开始)
                $sheet = $objPHPExcel->getSheet(0);
                // 取得总行数
                $highestRow = $sheet->getHighestRow();
                // 取得总列数
                $highestColumn = $sheet->getHighestColumn();
                // 循环读取excel文件,读取一条,插入数组一条
                for ($j=3;$j<=$highestRow;$j++) {
                    for ($k=‘A‘;$k<=$highestColumn;$k++) {
                        // 读取单元格
                        $examPaper_arr[$j][$k] = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
                    }
                }
                
                // 从Excel提取images
                $image_info = process_excel_image($file_name, $full_path);
                // 导入成功总数
                $sum = 0;
                // 重复总数
                $user_repeat = 0;
                $error_num = 0;
                // 开启事务
                // Db::startTrans();
                // try {
                foreach ($examPaper_arr as $key=>$value) { // 教师记录信息
                    if ($this->_model->where("code=‘$value[B]‘")->find()) {
                        $user_repeat++;
                        echo "重复的记录:";
                        var_dump("$value[B]");
                        echo "\r\n";
                    } else {
                        // 图片处理start
                        foreach ($image_info as $kk => $vv) {
                            $kk_new = substr($kk, -1);
                            if ($kk_new == $key) {
                                // 获取图片名字&拼接URL
                                $path_parts = pathinfo($vv);
                                $basename = $path_parts[‘basename‘];
                                $ima = \think\Image::open($vv);
                                // 将图片裁剪为300x300并保存为crop.png
                                // $ima->crop(300, 300,100,30)->save(ROOT_PATH . "public/uploads/crop$kk.png");
                                $ima->thumb(600, 600)->save(ROOT_PATH . "public/uploads/teacher/$basename");
                                $full_image_path = SITE_URL . "teacher/" . "$basename";
                
                                $img_id = Db::name(‘image‘)->insertGetId([
                                    "url" => "$full_image_path",
                                    ‘createdtime‘ => date("Y-m-d H:i:s"),
                                    ‘changedtime‘ => date("Y-m-d H:i:s")
                                ]);
                                $data[‘image‘] = $img_id ? $img_id : 0;
                            }
                        }
                        // 图片处理end
                        // 处理带班
                        if ($value[‘F‘] == ‘是‘) {
                            // $class_grade_info = $this->classGradeModel->where("remark = ‘$value[G]‘")->find();
                            $class_grade_info = Db::name("class_grade")->where("remark = ‘$value[G]‘")->find();
                            if ($class_grade_info) {
                                $data[‘c_g_id‘] = $class_grade_info[‘id‘];
                            } else {
                                return $this->error("班级名称不存在");
                            }
                        } else {
                            $data[‘c_g_id‘] = 2;
                        }
                        $data[‘realname‘] = empty($value[‘A‘]) ? 0 : $value[‘A‘];
                        $data[‘code‘] = empty($value[‘B‘]) ? 0 : $value[‘B‘];
                        $data[‘gender‘] = ($value[‘D‘] == ‘男‘) ? 1 : 0;
                        $data[‘telphone‘] = empty($value[‘E‘]) ? 0 : $value[‘E‘];
                        $data[‘is_foreman‘] = empty($value[‘F‘]) ? 2 : (($value[‘F‘] == "是") ? 1 : 2);
                        $data[‘remark‘] = empty($value[‘E‘]) ? 0 : $value[‘E‘];
                        $data[‘profession‘] = empty($value[‘H‘]) ? 0 : $value[‘H‘];
                        $data[‘s_id‘] = $s_id;
                        $data_2_arr[] = $data;
                    }
                }
                $teacher_id_new = $this->_model->saveAll($data_2_arr);
                if ($teacher_id_new) {
                    $sum++;
                } else {
                    $error_num++;
                }
                // } catch (\Exception $e) {
                // echo $e->getMessage();
                // // 事务回滚
                // // Db::rollback();
                //                 }
                echo "上传结束\r\n导入成功:". count($data_2_arr) .";\r\n重复总数:".$user_repeat . "\r\n失败条数:" . $error_num;die;
            } else {
                // 上传失败获取错误信息
                return $this->error($file->getError());
            }
        } else {
            return $this->fetch();
        }
    }


关于表格里面有图片导入的,会单独放到一篇文章里面

(http://tengteng412.blog.51cto.com/4751263/1964539)


参考文章:

http://blog.csdn.net/nagecomeontom/article/details/17397317

http://php2012web.blog.51cto.com/5585213/1620057


本文出自 “为了以后” 博客,谢绝转载!

以上是关于TP5中封装PHPEXCEL1.8导入数据以及图片功能的主要内容,如果未能解决你的问题,请参考以下文章

thinkphp3.2.3集成phpexcel1.8导出设置单元格合并

tp5封装 phpexecl引入和调用类的封装以及调用

tp5 数据库信息导出到excel(带图片)

tp5 删除图片以及文件

TP5导入EXCEL到数据库

php自己封装一个Db类,跟tp5封装的类一模一样