以前记得总是用PHP生成csv格式的表格,可现在excel表格越来越流行了,许多公司都要求做成excel格式表格,但这并不复杂,因为phpexcel为我们提供了方便、快捷的excel操作类。下面来看实际操作代码吧,这里的案例是基于thinkPHP框架开发的,请大家知晓。实际导出效果如下图所示
首先我们需要引用PHPexcel插件文件夹,这个插件可以在其官网下载,不过该插件是老外写的,所有官网是英文。下载好了的命名为excel文件夹并放到Vendor目录下,详细路径如:ThinkPHP\Library\Vendor\excel。其中excel里面放入一个我自己写的处理类,类里面包括导出export和import导入两个方法,详细单如下
//ThinkPHP\Library\Vendor\excel\importexport.class.php文件 <?php /** * Created by www.100txy.com * User: leixiaotian * Date: 2016/7/12 * Time: 15:45 */ error_reporting(E_ALL); date_default_timezone_set('Asia/ShangHai'); class importexport{ public function __construct(){ require_once(dirname(__FILE__) . '/PHPExcel.php'); // require_once ROOT_DIR . '/app/importexport/lib/excel/PHPExcel.php'; } // 导出 public function export($dataInfo,$arrTitle,$filename,$titlename,$tablesize){ require_once(dirname(__FILE__) . '/PHPExcel/Writer/Excel2007.php'); // require_once ROOT_DIR . '/app/importexport/lib/excel/PHPExcel/Writer/Excel2007.php'; // $filename=urlencode('商品库存明细').'_'.date('Y-m-dHis'); set_time_limit(0); @ini_set('memory_limit','64M'); header('Content-Type: application/vnd.ms-excel'); // header("Content-Disposition: attachment; filename=商品库存明细-".date('Ymd').".xlsx"); header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"'); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); $objPHPExcel = new PHPExcel(); $objPHPExcel->getProperties()->setCreator("雷小天"); $objPHPExcel->getProperties()->setLastModifiedBy("最后修改"); $objPHPExcel->getProperties()->setTitle($titlename); $objPHPExcel->getProperties()->setSubject("Excel导出表"); $objPHPExcel->getProperties()->setDescription("Excel导出表"); $objPHPExcel->getProperties()->setKeywords("Excel2007"); $objPHPExcel->getProperties()->setCategory("正式文件表格"); foreach ($arrTitle as $k => $v) { $Letter = 65; $Letter = chr($Letter + $k); $Letter = $Letter . 1; $objPHPExcel->setActiveSheetIndex(0)->setCellValue($Letter ,$v) ; } foreach ($dataInfo as $key => $data) { // $objPHPExcel->getActiveSheet()->getStyle('A' . ($key +2))->getNumberFormat()->setFormatCode("0");//决绝科学计算法格式 // $objPHPExcel->getActiveSheet()->getStyle('A' . ($key +2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY); $data = array_values($data); foreach ($data as $k => $v) { $Letter = 65; $Letter = chr($Letter + $k); $Letter = $Letter . ($key +2); $value = $v ? ' '.$v : ' '; $objPHPExcel->setActiveSheetIndex(0)->setCellValue($Letter , $value); } } foreach ($tablesize as $key => $value) {//设置不同表格的宽度$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension($key)->setWidth($value); } $objPHPExcel->getActiveSheet()->setTitle($titlename); $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); $objWriter->save('php://output'); exit; } // 导入 public function import($filename)//到时候要传名字$filename { // require_once ROOT_DIR ."/app/importexport/lib/excel/PHPExcel/Reader/Excel2007.php"; // require_once ROOT_DIR ."/app/importexport/lib/excel/PHPExcel/Reader/Excel5.php"; require_once(dirname(__FILE__) . '/PHPExcel/Reader/Excel2007.php'); require_once(dirname(__FILE__) . '/PHPExcel/Reader/Excel5.php'); //先试着用EXCEL2007 读取, 如果读取不到,就用低版本的去读取 $PHPReader = new PHPExcel_Reader_Excel2007; if(!$PHPReader->canRead($filename)){ $PHPReader = new PHPExcel_Reader_Excel5; if(!$PHPReader->canRead($filename)){ return '非EXCEL文件'; } } $PHPExcel = $PHPReader->load($filename); //读取第一个工作表 $currentSheet = $PHPExcel->getSheet(0); // 取列数 $allColumn = $currentSheet->getHighestColumn(); // 取行数 $allRow = $currentSheet->getHighestRow(); // die(var_dump($allColumn)); // 从第二行开始输出,excel表中第一行为列名 $arrImportData = array(); for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ // 第A列 for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){ $arrImportData[$currentRow-2][] =strval($currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue()); // echo strval($currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue()); } } return $arrImportData; } }
公共处理类写好了,我们就要写各个导出和导入实际案例代码,导出代码不一样,导入是公共的,放在公共控制器中
导出案例:导出需要实例化importexport.class.php类
<?php namespace Admin\Controller; use Think\Controller; class RoleController extends CommonController { public function __construct(){ parent::__construct(); $this->roleModle=M("role"); Vendor('excel.importexport#class'); $this->excel = new \importexport(); } //角色导出excel public function exportexcel(){ if(isset($_GET['type'])){ if($_GET['type']==1){ $rolelist = $this->roleModle->order('id asc')->select(); foreach ($rolelist as $k => $v) { $roleArr[$k]['id']=$rolelist[$k]['id']; $roleArr[$k]['name']=$rolelist[$k]['name']; $roleArr[$k]['pid']=$rolelist[$k]['pid']; $roleArr[$k]['status']=($v['status']==1)?'正常':'禁用'; $roleArr[$k]['remark']=$rolelist[$k]['remark']; } // $filename='商品库存明细'.'_'.date('Y-m-dHis'); $filename='角色表'.'-'.date('Ymd'); $titlename='角色表单'; } $arrTemp=array( '编号' => 'id', '名称' => 'name', '上级角色' => 'pid', '状态' => 'status', '备注' => 'remark', ); $arrTitle=array_keys($arrTemp); //自定义每列的宽度 $tablesize=array( 'A'=>18, 'B'=>20, 'C'=>20, 'D'=>20, 'E'=>40, ); $this->excel->export($roleArr,$arrTitle,$filename,$titlename,$tablesize); } } }
导入案例:导入需要先将excel表格上传
<?php //设备excel导入 public function importexcel($file,$type){ Vendor('excel.importexport#class'); $this->excel = new \importexport(); $result=$this->excel->import($file); switch ($type) { case 'equipment': $doorModle=M("doorcontroller"); foreach ($result as $key => $value) { $data=array( 'controllerno'=>trim($value[0]), 'computeno'=>trim($value[1]), 'communicationip'=>trim($value[2]), 'communicationport'=>trim($value[3]), 'areaname'=>trim($value[4]), 'joinstatus'=>0, 'doorfieldno'=>trim($value[6]), 'controllersn'=>trim($value[7]), 'doorstatus'=>trim($value[8]), 'direction'=>trim($value[9]), 'operatorname'=>$_SESSION['username'], 'makedatetime'=>time(), 'remark'=>trim($value[12]), ); $res=$doorModle->add($data); if($res){ $this->success('添加成功',U('Admin/Doorcontroller/index'),3); }else{ $this->error('添加失败',U('Admin/Doorcontroller/index'),3); } } break; case 'area': $areaModle=M("areainfo"); foreach ($result as $key => $value) { $data=array( // 'areano'=>trim($value[0]),//自增长不填写 'upareano'=>trim($value[1]), 'areaname'=>trim($value[2]), 'remark'=>trim($value[3]), 'operatorname'=>trim($value[4]), ); $res=$areaModle->add($data); if($res){ $this->success('导入成功',U('Admin/Areainfo/index'),3); }else{ $this->error('导入失败',U('Admin/Areainfo/index'),3); } } break; case 'value2': # code... break; default: # code... break; } return $result; } public function upload(){//这个方法和上面的方法度需要放到公共函数中 if ($_POST['type']) { $upload = new \Think\Upload();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->exts = array('xlsx', 'xls');// 设置附件上传类型 $upload->rootPath = './Public/Uploads/'; // 设置附件保存根目录 $upload->savePath = './excel/'; // 设置附件根目录下面的保存目录 $upload->replace = true; // 覆盖文件 // 单文件上传 $info = $upload->upload(); if(!$info) { // 上传错误提示错误信息 $this->show($upload->getError()); }else{ // 上传成功 获取上传文件信息 $info['import_file']['savepath']=substr($info['import_file']['savepath'],1); $file = '/data/wwwroot/door/Public/Uploads'.$info['import_file']['savepath'].$info['import_file']['savename']; $this->importexcel($file,$_POST['type']); // $result=$this->excel->import($file); // die(var_dump($result)); exit; } } // $this->display(); }
至此,一个完整的PHP生成excel表格功能就完成了,而且导出时的表格可以通过$tablesize数组控制每列的宽度