zoukankan      html  css  js  c++  java
  • 关于PHPExcel

      在学PHPExcel的时候,在网上查了很多资料,花了很多时间,下面是我想要分享给大家的,我找到的并进行了一定修改的亲身实践成功的资料,希望大家对大家有所帮助。

      首先,需要下载PhpExcel资料,下载资料可以在这里下载,http://download.csdn.net/detail/www122930/9207061

      第一,将PHPExcel文件夹,和PHPExcel.php文件放在,一个新建的文件夹Excel中,将Excel文件夹放在,E:WorkspacePHP hinkphp2ThinkPHPExtendVendor,E:WorkspacePHP hinkphp2这一部分是你创建Thinkphp的工作目录。

      第二,编写一个ExcelToArray.class.php文件,将它放在E:WorkspacePHP hinkphp2ThinkPHPExtendLibraryORGUtil,这个目录下,ExcelToArray.class.php文件的源代码如下:

    <?php
    class ExcelToArray {
      public function __construct() {
    		Vendor("Excel.PHPExcel");//引入phpexcel类(注意你自己的路径)
    		Vendor("Excel.PHPExcel.IOFactory"); 	
      }
      public function read($filename,$encode,$file_type){
    	        if(strtolower ( $file_type )=='xls')//判断excel表类型为2003还是2007
    			{
    				Vendor("Excel.PHPExcel.Reader.Excel5"); 
    				$objReader = PHPExcel_IOFactory::createReader('Excel5');
    			}elseif(strtolower ( $file_type )=='xlsx')
    			{
    				Vendor("Excel.PHPExcel.Reader.Excel2007"); 
    				$objReader = PHPExcel_IOFactory::createReader('Excel2007');
    			}
    			$objReader->setReadDataOnly(true);
    			$objPHPExcel = $objReader->load($filename);
    			$objWorksheet = $objPHPExcel->getActiveSheet();
    			$highestRow = $objWorksheet->getHighestRow();
    			$highestColumn = $objWorksheet->getHighestColumn();
    			$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    			$excelData = array();
    			for ($row = 1; $row <= $highestRow; $row++) {
    				for ($col = 0; $col < $highestColumnIndex; $col++) {
    					$excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
    					}
    			}
    			return $excelData;
    	}
    	  
    	public function push($data,$name='Excel'){
    
              error_reporting(E_ALL);
              //date_default_timezone_set('Europe/London');
             $objPHPExcel = new PHPExcel();
    
            /*以下是一些设置 ,什么作者  标题啊之类的*/
             $objPHPExcel->getProperties()->setCreator("转弯的阳光")
                                   ->setLastModifiedBy("转弯的阳光")
                                   ->setTitle("usertable")
                                   ->setSubject("数据EXCEL导出")
                                   ->setDescription("备份数据")
                                   ->setKeywords("excel")
                                  ->setCategory("result file");
    		
    		
    		//
    		$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'username')
            ->setCellValue('B1', 'password')
            ->setCellValue('C1', 'sex');
    
             /*以下就是对处理Excel里的数据, 横着取数据,主要是这一步,其他基本都不要改*/
            for ($i = 0; $i < count($data) - 1; $i++) {
    			$objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 2), $data[$i]['username']);
    			$objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 2), $data[$i]['password']);
    			$objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 2), $data[$i]['sex']);
    		}
    
                $objPHPExcel->getActiveSheet()->setTitle('User');
                $objPHPExcel->setActiveSheetIndex(0);
    			ob_end_clean(); //清除缓冲区,避免乱码
                 header('Content-Type: application/vnd.ms-excel');
                 header('Content-Disposition: attachment;filename="'.$name.'.xls"');
                 header('Cache-Control: max-age=0');
                 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                 $objWriter->save('php://output');
                 exit;
        }
    }
    

      这里有两部分,一部分read function,就是读入Excel中,即将数据库中内容导入到Excel,另一部分,push function,就是讲Excel数据上传到数据库。

      第三,创建一个ExcelAction.clsaa.php,在目录E:WorkspacePHP hinkphp2HomeLibAction下面,ExcelAction.clsaa.php源代码如下:

     1 <?php
     2 class ExcelAction extends Action {
     3     public function __construct()
     4     {
     5         import('ORG.Util.ExcelToArray');//导入excelToArray类
     6     }
     7     
     8     public function index()
     9     {
    10         $this->display();
    11     }
    12     public function add()
    13     {    
    14         dump($_FILES);
    15         
    16         $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
    17         $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
    18         $file_type = $file_types [count ( $file_types ) - 1];
    19     
    20          /*判别是不是.xls文件,判别是不是excel文件*/
    21          if (strtolower ( $file_type ) != "xlsx" && strtolower ( $file_type ) != "xls")              
    22          {
    23               $this->error ( '不是Excel文件,重新上传' );
    24          }
    25     
    26          /*设置上传路径*/
    27          $savePath = 'E:WorkspacePHP	hinkphpUploads\';
    28          /*以时间来命名上传的文件*/
    29          $str = date ( 'Ymdhis' ); 
    30          $file_name = $str . "." . $file_type;
    31          
    32          /*是否上传成功*/
    33          if (! copy ( $tmp_file, $savePath . $file_name )) 
    34           {
    35               $this->error ( '上传失败' );
    36           }
    37         $ExcelToArray=new ExcelToArray();//实例化
    38         $res=$ExcelToArray->read($savePath.$file_name,"UTF-8",$file_type);//传参,判断office2007还是office2003
    39         foreach ( $res as $k => $v ) //循环excel表
    40         {  
             //这一步判断,是为了在Excel内第一行一定是行标题,这里将第一行忽略,直接从第二行读入数据,若没有行标题,则不需要进行if判断,且$k=$k-1;
    41 if($k!=1){ 42 $k=$k-2;//addAll方法要求数组必须有0索引 43 $data[$k]['username'] = $v[0];//创建二维数组 44 $data[$k]['password'] = $v[1]; 45 $data[$k]['sex'] = $v [2]; 46 } 47 } 48 49 //dump($data[0]); 50 $kucun=M('User');//M方法 51 $result=$kucun->addAll($data); 52 if(! $result) 53 { 54 $this->error('导入数据库失败'); 55 exit(); 56 } 57 else 58 { 59 $this->success ( '导入成功' ); 60 } 61 } 62 63 public function load(){ 64 $data= M('User')->select(); //查出数据 65 dump($data); 66 $name='Usertable'; //生成的Excel文件文件名 67 $ExcelToArray=new ExcelToArray();//实例化 68 $res=$ExcelToArray->push($data,$name); 69 } 70 }

      第四,就是创建相应的模板,在目录E:WorkspacePHP hinkphp2HomeTpl下,创建Excel文件夹,新建index.html文件,源代码如下:

    1 <form method="post" action="__APP__/Excel/add" enctype="multipart/form-data">
    2          <h3>导入Excel表:</h3><input  type="file" name="file_stu" />
    3 
    4            <input type="submit"  value="导入" />
    5 </form>
    6 <form method="post" action="__APP__/Excel/load" enctype="multipart/form-data">
    7            <input type="submit"  value="导出" />
    8 </form>

      最后,只需要进行测试就可以了。

      ps,数据库信息如下:

      例如:新建数据库thinkphp,建立表user,user表信息如下:

    id username password sex
    1 zs 123 1

      以上就是使用PhpExcel的全部步骤,谢谢!

  • 相关阅读:
    spring mvc 分页
    get/post时中文乱码问题的解决办法
    mysql-day01
    servler配置
    idea
    springMvc 核心配置
    ServletRequest面试题
    Servlet面试题
    Http面试题
    测试文件
  • 原文地址:https://www.cnblogs.com/double-y/p/PHPExcel.html
Copyright © 2011-2022 走看看