IT教程 | 加入收藏 | 简体 | 繁体
ThinkPHP:Php教程讲解Php函数讲解ThinkPHP
当前位置: 首页 > Php教程 > ThinkPHP

ThinkPHP+PHPExcel[导入][导出]实现方法讲解

2014-11-28来源:[www.121ask.com]热度:0℃ 【字体:

ThinkPHP+PHPExcel[导入][导出]实现方法讲解:

以下是我自己的实现方法,可能存在很多不足,仅供大家参考...
实现步骤:
一:去官网http://phpexcel.codeplex.com/下载最新PHPExcel放到Vendor下,注意位置:ThinkPHP\Extend\Vendor\PHPExcel\PHPExcel.php。
二:在CommonAction.class.php中添加以下两个函数:
  1. /**
  2.      +----------------------------------------------------------
  3.      * Export Excel | 2013.08.23
  4.      * Author:HongPing <hongping626@qq.com>
  5.      +----------------------------------------------------------
  6.      * @param $expTitle     string File name
  7.      +----------------------------------------------------------
  8.      * @param $expCellName  array  Column name
  9.      +----------------------------------------------------------
  10.      * @param $expTableData array  Table data
  11.      +----------------------------------------------------------
  12.      */
  13.     public function exportExcel($expTitle,$expCellName,$expTableData){
  14.         $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
  15.         $fileName = $_SESSION['loginAccount'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
  16.         $cellNum = count($expCellName);
  17.         $dataNum = count($expTableData);
  18.         vendor("PHPExcel.PHPExcel");
  19.         $objPHPExcel = new PHPExcel();
  20.         $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');
  21.         
  22.         $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
  23.         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
  24.         for($i=0;$i<$cellNum;$i++){
  25.             $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
  26.         } 
  27.           // Miscellaneous glyphs, UTF-8   
  28.         for($i=0;$i<$dataNum;$i++){
  29.           for($j=0;$j<$cellNum;$j++){
  30.             $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
  31.           }             
  32.         }  
  33.         
  34.         header('pragma:public');
  35.         header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
  36.         header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
  37.         $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
  38.         $objWriter->save('php://output'); 
  39.         exit;   
  40.     }
  41.      
  42.     /**
  43.      +----------------------------------------------------------
  44.      * Import Excel | 2013.08.23
  45.      * Author:HongPing <hongping626@qq.com>
  46.      +----------------------------------------------------------
  47.      * @param  $file   upload file $_FILES
  48.      +----------------------------------------------------------
  49.      * @return array   array("error","message")
  50.      +----------------------------------------------------------     
  51.      */   
  52.     public function importExecl($file){ 
  53.         if(!file_exists($file)){ 
  54.             return array("error"=>0,'message'=>'file not found!');
  55.         } 
  56.         Vendor("PHPExcel.PHPExcel.IOFactory"); 
  57.         $objReader = PHPExcel_IOFactory::createReader('Excel5'); 
  58.         try{
  59.             $PHPReader = $objReader->load($file);
  60.         }catch(Exception $e){}
  61.         if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!');
  62.         $allWorksheets = $PHPReader->getAllSheets();
  63.         $i = 0;
  64.         foreach($allWorksheets as $objWorksheet){
  65.             $sheetname=$objWorksheet->getTitle();
  66.             $allRow = $objWorksheet->getHighestRow();//how many rows
  67.             $highestColumn = $objWorksheet->getHighestColumn();//how many columns
  68.             $allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
  69.             $array[$i]["Title"] = $sheetname; 
  70.             $array[$i]["Cols"] = $allColumn; 
  71.             $array[$i]["Rows"] = $allRow; 
  72.             $arr = array();
  73.             $isMergeCell = array();
  74.             foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells
  75.                 foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
  76.                     $isMergeCell[$cellReference] = true;
  77.                 }
  78.             }
  79.             for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){ 
  80.                 $row = array(); 
  81.                 for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){;                
  82.                     $cell =$objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
  83.                     $afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);
  84.                     $bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);
  85.                     $col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);
  86.                     $address = $col.$currentRow;
  87.                     $value = $objWorksheet->getCell($address)->getValue();
  88.                     if(substr($value,0,1)=='='){
  89.                         return array("error"=>0,'message'=>'can not use the formula!');
  90.                         exit;
  91.                     }
  92.                     if($cell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC){
  93.                         $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();
  94.                         $formatcode=$cellstyleformat->getFormatCode();
  95.                         if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $formatcode)) {
  96.                             $value=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));
  97.                         }else{
  98.                             $value=PHPExcel_Style_NumberFormat::toFormattedString($value,$formatcode);
  99.                         }                
  100.                     }
  101.                     if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){
  102.                         $temp = $value;
  103.                     }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){
  104.                         $value=$arr[$currentRow-1][$currentColumn];
  105.                     }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){
  106.                         $value=$temp;
  107.                     }
  108.                     $row[$currentColumn] = $value; 
  109.                 } 
  110.                 $arr[$currentRow] = $row; 
  111.             } 
  112.             $array[$i]["Content"] = $arr; 
  113.             $i++;
  114.         } 
  115.         spl_autoload_register(array('Think','autoload'));//must, resolve ThinkPHP and PHPExcel conflicts
  116.         unset($objWorksheet); 
  117.         unset($PHPReader); 
  118.         unset($PHPExcel); 
  119.         unlink($file); 
  120.         return array("error"=>1,"data"=>$array); 
  121.     }
 
 
使用方法
导入:
  1. function impUser(){
  2.      if(isset($_FILES["import"]) && ($_FILES["import"]["error"] == 0)){
  3.         $result = $this->importExecl($_FILES["import"]["tmp_name"]);
  4.         if($result["error"] == 1){          
  5.           $execl_data = $result["data"][0]["Content"];
  6.                   foreach($execl_data as $k=>$v){
  7.                       ..这里写你的业务代码..
  8.                   }
  9.          }
  10.       }
  11. }
 
 
导出:
  1. function expUser(){//导出Excel
  2.         $xlsName  = "User";
  3.         $xlsCell  = array(
  4.             array('id','账号序列'),
  5.             array('account','登录账户'),
  6.             array('nickname','账户昵称')
  7.         );
  8.         $xlsModel = M('Post');
  9.         $xlsData  = $xlsModel->Field('id,account,nickname')->select();
  10.         $this->exportExcel($xlsName,$xlsCell,$xlsData);
  11.     }

以上IT文章《ThinkPHP+PHPExcel[导入][导出]实现方法讲解》由名客技术网[www.121ask.com]提供阅读!
推广信息
推广信息
名客技术网是一个免费为广大IT技术人员提供IT教程,绿色软件,asp/php/jsp/java/net等实例视频教程,CMS教程,破解软件下载以及学习相关源码、知识的IT网站。
名客技术网如果无意之中侵犯了您的版权,请来电告知,本站将在3个工作日内删除 QQ:175352796
Copyright 2011-2017 Powered by 121ASK.COM, All Rights Reserved.
备案号:鄂ICP备11013833号-3