首先下载下来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_p_w_picpath($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();
$p_w_picpathInfo = extractImageFromWorksheet($worksheet, ROOT_PATH . "public/uploads/school/");
return $p_w_picpathInfo;
}
/**
* 返回文件路径的信息
*
* @param string $file_name
* @return string
*/
function getExtendFileName($file_name) {
$extend = pathinfo($file_name);
$extend = strtolower($extend["extension"]);
return $extend;
}
/**
* worksheet中提取p_w_picpath
*
* @param object $worksheet
* @param string $basePath
*/
function extractImageFromWorksheet($worksheet,$basePath){
$result = array();
$p_w_picpathFileName = "";
foreach ($worksheet->getDrawingCollection() as $drawing) {
$xy=$drawing->getCoordinates();
$path = $basePath;
// for xlsx
if ($drawing instanceof \PHPExcel_Worksheet_Drawing) {
$filename = $drawing->getPath();
$p_w_picpathFileName = $drawing->getIndexedFilename();
// 可能是office版本的缘故,获取出来的图片文件名字
// 很容易造成文件名重复导致图片被覆盖,这里做了一下
// 处理对图片名字进行微秒的md5处理。
// process p_w_picpathFileName
$tmp = explode(".", $p_w_picpathFileName);
$tmp[0] = md5(microtime(true));
$tmp_fileName = implode(".", $tmp);
// process p_w_picpathFileName
// $path = $path . $drawing->getIndexedFilename();
$path = $path . $tmp_fileName;
$boo = copy($filename, $path);
$result[$xy] = $path;
// for xls
} else if ($drawing instanceof \PHPExcel_Worksheet_MemoryDrawing) {
$p_w_picpath = $drawing->getImageResource();
$renderingFunction = $drawing->getRenderingFunction();
switch ($renderingFunction) {
case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:
$p_w_picpathFileName = $drawing->getIndexedFilename();
$path = $path . $drawing->getIndexedFilename();
p_w_picpathjpeg($p_w_picpath, $path);
break;
case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:
$p_w_picpathFileName = $drawing->getIndexedFilename();
$path = $path . $drawing->getIndexedFilename();
p_w_picpathgif($p_w_picpath, $path);
break;
case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:
$p_w_picpathFileName = $drawing->getIndexedFilename();
$path = $path . $drawing->getIndexedFilename();
p_w_picpathgif($p_w_picpath, $path);
break;
case \PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:
$p_w_picpathFileName = $drawing->getIndexedFilename();
$path = $path . $drawing->getIndexedFilename();
p_w_picpathgif($p_w_picpath, $path);
break;
}
$result[$xy] = $p_w_picpathFileName;
}
}
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提取p_w_picpaths
$p_w_picpath_info = process_excel_p_w_picpath($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 ($p_w_picpath_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_p_w_picpath_path = SITE_URL . "teacher/" . "$basename";
$img_id = Db::name('p_w_picpath')->insertGetId([
"url" => "$full_p_w_picpath_path",
'createdtime' => date("Y-m-d H:i:s"),
'changedtime' => date("Y-m-d H:i:s")
]);
$data['p_w_picpath'] = $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
转载于:https://blog.51cto.com/laok8/1964556