一般网站后台都有人员导入或者是订单导出之类的操作,今天分享一下几种php excel cvs等文件导入导出的办法。
第一种比较简单的,自己写的,不引用任何excel类。但是会有bug,代码如下:
首先 视图页面:
<div class="panel-body"> <form action="./index.php" method="post" class="form-horizontal" role="form" enctype="multipart/form-data"> <input type="hidden" name="leadExcel" value="true"> // 导入excel类型 <input type="hidden" name="ac" value="question" /> // 将文件导入到某位置 <label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> <div class="help-block">请先下载导入模板,然后按照模板样式添加试题。</div> <div class="form-group"> <label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> <div class="col-sm-9 col-xs-12"> <input type="file" class="pull-left btn-default" name="inputExcel"> </div> </div> <div class="form-group"> <label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> <div class="col-sm-9 col-xs-12"> <input type="submit" class="btn pull-left btn-primary" value="导入数据"> <a class="btn btn-primary" href="../addons/ewei_exam/example/example_question.csv" style="margin-left: 20px;">下载导入模板</a> </div> </div> </form> </div>
然后是控制层页面
if($_GPC['leadExcel'] == "true") { $filename = $_FILES['inputExcel']['name']; $tmp_name = $_FILES['inputExcel']['tmp_name']; $msg = uploadFile($filename, $tmp_name, $_GPC); //print_r($msg);exit; if ($msg == 1) { message('导入成功!', referer(), 'success'); } else { message($msg, '', 'error'); } }
最后uploadfile这个函数中是读取excel文件内容并插入数据库,可以写在函数中,最好写到excel类中
function uploadFile($file, $filetempname, $array) { if ($result = file_get_contents($filetempname)) { $result = iconv('gbk', 'utf-8', $result); if (empty($result)) { return $msg = '导入失败'; } $result = preg_replace('/\n/', 'h--h', $result); $result = explode('h--h', $result); foreach ($result as $key => $ques) { $ques = explode(',', $ques); if ($key == 0) { continue; } $strs = array(); foreach ($ques as $questi) { $strs[] = preg_replace('/\s/', '', trim($questi, "\"")); if ($array['ac'] == 'question') { upload_question($strs, time(), $array); }elseif ($array['ac'] == 'member') { upload_member($strs, time()); } } } $msg = '1'; } else { $msg = "导入失败!"; } return $msg; } function upload_question($strs, $time, $array) { global $_W; //print_r($array);exit; $question_type = $strs[0]; $level = $strs[1]; $question = $strs[2]; $answer = $strs[3]; $answer1 = $strs[4]; $answer2 = $strs[5]; $answer3 = $strs[6]; $answer4 = $strs[7]; $answer5 = $strs[8]; $answer6 = $strs[9]; $explain = $strs[10]; $row_num = $array['row_num']; $insert = array(); //$insert['userid'] = $userid; pdo_insert('ewei_exam_question', $insert); } }
$insert中是需要插入的数据,上面的都是获取到的数据。
这种方式比较简单,但是导入的时候对excel文件的要求比较高,而且必须是utf8的格式。
第二种是引用线上封装好的的phpexcel类,这种方式基本不会出现任何问题。介绍一种:
https://github.com/dhucaichao/phpexcel.git 我放在github上了,可以自己下载。引用的代码如下:
视图层代码和上面一种一样,获取excel文件信息的代码如下
// 批量导入 function importExecl($file='', $sheet=0){ $file = iconv("utf-8", "gb2312", $file); //转码 if(empty($file) OR !file_exists($file)) { die('file not exists!'); } load()->classs('PHPExcel'); $objRead = new PHPExcel_Reader_Excel2007(); //建立reader对象 if(!$objRead->canRead($file)){ $objRead = new PHPExcel_Reader_Excel5(); if(!$objRead->canRead($file)){ die('No Excel!'); } } $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'); $obj = $objRead->load($file); //建立excel对象 $currSheet = $obj->getSheet($sheet); //获取指定的sheet表 $columnH = $currSheet->getHighestColumn(); //取得最大的列号 $columnCnt = array_search($columnH, $cellName); $rowCnt = $currSheet->getHighestRow(); //获取总行数 $data = array(); for($_row=1; $_row<=$rowCnt; $_row++){ //读取内容 for($_column=0; $_column<=$columnCnt; $_column++){ $cellId = $cellName[$_column].$_row; $cellValue = $currSheet->getCell($cellId)->getValue(); // $cellValue = $currSheet->getCell($cellId)->getCalculatedValue(); if($cellValue instanceof PHPExcel_RichText){ //富文本转换字符串 $cellValue = $cellValue->__toString(); } $data[$_row][$cellName[$_column]] = $cellValue; } } return $data; }
其中load()->classs('PHPExcel');是导入phpexcel类,我用的是框架自带的导入方式,不同框架有不同的导入方式,也可以死直接include进来。
$data是获取到的数据,可以导入数据库,例如:
function upload_staff($data) { global $_W; foreach ($data as $key => $value){ if ($key == 1){ continue; } $insert = array( 'realname' => $value['A'], 'mobile' => $value['B'], 'email' => $value['C'], 'departmentid' => find_department($value['D']), 'position' => $value['E'], 'birthyear' => substr(strReplace($value['F']),0,4), 'birthmonth' => substr(strReplace($value['F']),5,2), 'birthday' => substr(strReplace($value['F']),8,2), 'entrytime' => strReplace($value['G']), 'company' => find_company($_W['uid']) ); $id = find_is_exists($value['B']); if ($id){ $return = pdo_update('mc_members', $insert, array('uid' => $id,'uniacid'=>$_W['uniacid'])); if (!$return){ return "第".($key-1)."条数据更新失败"; } } else { $insert['uniacid'] = $_W['uniacid']; $id = pdo_insert('mc_members', $insert); if (!$id){ return "第".($key-1)."条数据添加失败"; } } } return 1; }
同样,也可以将数据库中的数据导出到excel中:
$list1 = array('部门','职位','手机号','姓名','发放积分','备注'); $where = ' WHERE m.uniacid=:uniacid AND mobile <> :mobile AND d.uniacid = :duniacid'; $param = array(':uniacid'=>$_W['uniacid'],':mobile'=>'',':duniacid'=>$_W['uniacid']); $lists = pdo_fetchall("SELECT d.name,m.position,m.mobile,m.realname FROM " . tablename('mc_members'). " AS m LEFT JOIN " . tablename('xfl_department'). " AS d ON m.departmentid = d.id " .$where,$param); $a = exportExcel($list1,$lists,'员工列表','./',true); header($a); function exportExcel($title=array(), $data=array(), $fileName='', $savePath='./', $isDown=false){ load()->classs('PHPExcel'); $obj = new PHPExcel(); //横向单元格标识 $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'); $obj->getActiveSheet(0)->setTitle('sheet1'); //设置sheet名称 $_row = 1; //设置纵向单元格标识 if($title){ $_cnt = count($title); $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row); //合并单元格 $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出:'.date('Y-m-d H:i:s')); //设置合并后的单元格内容 $_row++; $i = 0; foreach($title AS $v){ //设置列标题 $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v); $i++; } $_row++; } //填写数据 if($data){ $i = 0; foreach($data AS $_v){ $j = 0; foreach($_v AS $_cell){ $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell); $j++; } $i++; } } //文件名处理 if(!$fileName){ $fileName = uniqid(time(),true); } $objWrite = PHPExcel_IOFactory::createWriter($obj, 'Excel2007'); if($isDown){ //网页下载 header('pragma:public'); header("Content-Disposition:attachment;filename=$fileName.xls"); $objWrite->save('php://output');exit; } $_fileName = iconv("utf-8", "gb2312", $fileName); //转码 $_savePath = $savePath.$_fileName.'.xlsx'; $objWrite->save($_savePath); return $savePath.$fileName.'.xlsx'; }
exportExcel返回的是数据导入后的excel文件的地址,可以直接header过去下载。