Home  >  Article  >  php教程  >  php uses PHPEXcel to export table data

php uses PHPEXcel to export table data

大家讲道理
大家讲道理Original
2016-11-08 14:10:061167browse

In the project, I need to export the data in the table. I searched online and found that phpexcel is quite easy to use. I would like to share

PHPEXCEL

<?php
 
if(!defined(&#39;BASEPATH&#39;)) exit(&#39;No direct script access allowed&#39;);
//物资发料单明细
class Read_write{  
    /**
     * $name:选择的类型(CSV,EXCEL2003,2007)
     * $titles:标题数组
     * $querys:查询返回的数组 $query->result_array();
     * $filename:保存的文件名称
     */
    function write_Factory($titles,$querys,$filename,$name="EXCEL2003"){ 
 
      $CI = &get_instance();
      $filename=mb_convert_encoding($filename, "GBK","UTF-8");
 
      switch ($name) {
        case "CSV":
            $CI->excel->write_CSV($titles,$querys,$filename);
            break;
        case "EXCEL2003":
            $CI->excel->write_EXCEL2003($titles,$querys,$filename);
            break;
        case "EXCEL2007":
            $CI->excel->write_EXCEL2007($titles,$querys,$filename);
            break;
      }
    }
 
    /**
     * $name:
     */
    function read_Facotry($filePath,$sql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
       $CI = &get_instance();
       $name=$this->_file_extend($filePath);
       switch ($name) {
        case "csv":
            $CI->excel->read_CSV($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
            break;
        case "xls":
            $CI->excel->read_2003Excel($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
            break;
        case "xlsx":
            $CI->excel->read_EXCEL2007($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
            break;
      }
       $CI->mytool->import_info("filePath=$filePath,sql=$sql");
    }
    /**
     * 2012-1-14 读取工作薄名称(sheetnames)
     */
     function read_sheetNames($filePath){
       $CI = &get_instance();
       $name=$this->_file_extend($filePath);
       $sheetnames;
       switch ($name) {
            case "csv":
                $sheetnames=$CI->excel->read_CSV_Sheet($filePath);
                break;
            case "xls":
                $sheetnames=$CI->excel->read_2003Excel_Sheet($filePath);
                break;
            case "xlsx":
                $sheetnames=$CI->excel->read_EXCEL2007_Sheets($filePath);
                break;
       }   
      return $sheetnames;   
     }
    //读取文件后缀名
     function _file_extend($file_name){
        $extend =explode("." , $file_name);
        $last=count($extend)-1;
        return $extend[$last];
    }
  //-----------------------------------------------预备保留 
    //2011-12-21新增CVS导出功能
     public function export_csv($filename,$title,$datas, $delim = ",", $newline = "\n", $enclosure = &#39;"&#39;){
       $CI = &get_instance();
       $cvs= $this->_csv_from_result($title,$datas,$delim,$newline,$enclosure);
       $CI->load->helper(&#39;download&#39;);
       $name=mb_convert_encoding($filename, "GBK","UTF-8");
       force_download($name, $cvs);
    }
    /**
     * @param $titles:标题
     * @param $datas:数据
     */
    function _csv_from_result($titles,$datas, $delim = ",", $newline = "\n", $enclosure = &#39;"&#39;){
        $out = &#39;&#39;;
        // First generate the headings from the table column names
        foreach ($titles as $name){
            $name=mb_convert_encoding($name, "GBK","UTF-8");
            $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
        }
 
        $out = rtrim($out);
        $out .= $newline;
        // Next blast through the result array and build out the rows
        foreach ($datas as $row)
        {
            foreach ($row as $item)
            {
             $item=mb_convert_encoding($item, "GBK","UTF-8");
                $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
            }
            $out = rtrim($out);
            $out .= $newline;
        }
 
        return $out;
    }  
 
}
<?php
/**
 * PHPExcel
 *
 * Copyright (C) 2006 - 2010 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
 * @version    1.7.4, 2010-08-26
 */
/** Error reporting */
error_reporting(E_ALL);
 
date_default_timezone_set (&#39;Asia/Shanghai&#39;);
 
/** PHPExcel */
require_once &#39;Classes/PHPExcel.php&#39;;
require_once &#39;Classes/PHPExcel/IOFactory.php&#39;;
/**
 * 输出到页面上的EXCEL
 */
/**
 * CI_Excel
 *
 * @package ci
 * @author admin
 * @copyright 2011
 * @version $Id$
 * @access public
 */
class CI_Excel
{  
    //列头,Excel每列上的标识
   private $cellArray = array(
                        1=>&#39;A&#39;, 2=>&#39;B&#39;, 3=>&#39;C&#39;, 4=>&#39;D&#39;, 5=>&#39;E&#39;,
                        6=>&#39;F&#39;, 7=>&#39;G&#39;, 8=>&#39;H&#39;, 9=>&#39;I&#39;,10=>&#39;J&#39;,
                        11=>&#39;K&#39;,12=>&#39;L&#39;,13=>&#39;M&#39;,14=>&#39;N&#39;,15=>&#39;O&#39;,
                        16=>&#39;P&#39;,17=>&#39;Q&#39;,18=>&#39;R&#39;,19=>&#39;S&#39;,20=>&#39;T&#39;,
                        21=>&#39;U&#39;,22=>&#39;V&#39;,23=>&#39;W&#39;,24=>&#39;X&#39;,25=>&#39;Y&#39;,
                        26=>&#39;Z&#39;,
                        27=>&#39;AA&#39;, 28=>&#39;AB&#39;, 29=>&#39;AC&#39;, 30=>&#39;AD&#39;, 31=>&#39;AE&#39;,
                        32=>&#39;AF&#39;, 33=>&#39;AG&#39;, 34=>&#39;AH&#39;, 35=>&#39;AI&#39;,36=>&#39;AJ&#39;,
                        37=>&#39;AK&#39;,38=>&#39;AL&#39;,39=>&#39;AM&#39;,40=>&#39;AN&#39;,41=>&#39;AO&#39;,
                        42=>&#39;AP&#39;,43=>&#39;AQ&#39;,44=>&#39;AR&#39;,45=>&#39;AS&#39;,46=>&#39;AT&#39;,
                        47=>&#39;AU&#39;,48=>&#39;AV&#39;,49=>&#39;AW&#39;,50=>&#39;AX&#39;,51=>&#39;AY&#39;,
                        52=>&#39;AZ&#39;, 53=>&#39;BA&#39;, 54=>&#39;BB&#39;, 55=>&#39;BC&#39;, 56=>&#39;BD&#39;, 57=>&#39;BE&#39;,
                        58=>&#39;BF&#39;, 59=>&#39;BG&#39;, 60=>&#39;BH&#39;, 61=>&#39;BI&#39;, 62=>&#39;BJ&#39;, 63=>&#39;BK&#39;, 64=>&#39;BL&#39;);
     private $E2003 = &#39;E2003&#39;;
     private $E2007 = &#39;E2007&#39;;
     private $ECSV  = &#39;ECSV&#39;;
     private $tempName;         //当读取合并文件时,如果第二行为空,则取第一行的名称
/*********************************导出数据开始****************************************************/
    /**
     * 生成Excel2007文件
     */
    function write_EXCEL2007($title=&#39;&#39;,$data=&#39;&#39;,$name=&#39;&#39;)
    {  
       $objPHPExcel=$this->_excelComm($title,$data,$name);
        // Redirect output to a client’s web browser (Excel2007)
        header(&#39;Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8&#39;);
        header("Content-Disposition: attachment;filename=$name.xlsx");
        header(&#39;Cache-Control: max-age=0&#39;);
 
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
        $objWriter->save(&#39;php://output&#39;);  //output 允许向输出缓冲机制写入数据,和 print() 与 echo() 的方式相同。
        exit;
    }
    /**
     * 生成Excel2003文件
     */
    function write_EXCEL2003($title=&#39;&#39;,$data=&#39;&#39;,$name=&#39;&#39;){
 
       $objPHPExcel=$this->_excelComm($title,$data,$name);
       //Redirect output to a client’s web browser (Excel5)
       header(&#39;Content-Type: application/vnd.ms-excel;charset=UTF-8&#39;);
       header("Content-Disposition: attachment;filename=$name.xls");
       header(&#39;Cache-Control: max-age=0&#39;);
 
       $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, &#39;Excel5&#39;);
       $objWriter->save(&#39;php://output&#39;);
 
    }
    /**
     * 生成CSV文件
     */
    function write_CSV($title=&#39;&#39;,$data=&#39;&#39;,$name=&#39;&#39;){
         $objPHPExcel=$this->_excelComm($title,$data,$name);
 
         header("Content-Type: text/csv;charset=UTF-8");  
         header("Content-Disposition: attachment; filename=$name.csv");  
         header(&#39;Cache-Control:must-revalidate,post-check=0,pre-check=0&#39;);  
         header(&#39;Expires:0&#39;);  
         header(&#39;Pragma:public&#39;); 
         $objWriter = new PHPExcel_Writer_CSV($objPHPExcel,&#39;CSV&#39;);
         $objWriter->save("php://output");
         exit;
    }
 
    function _excelComm($title,$data,$name){
         // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();
        $objPHPExcel=$this->_writeTitle($title,$objPHPExcel);
       $objPHPExcel=$this->_writeDatas($data,$objPHPExcel);
       $objPHPExcel=$this->_write_comm($name,$objPHPExcel);
        return $objPHPExcel;
    }
 
    //输出标题
    function _writeTitle($title,$objPHPExcel){
         //表头循环(标题)
        foreach ($title as $tkey => $tvalue){
            $tkey = $tkey+1;                        
            $cell  = $this->cellArray[$tkey].&#39;1&#39;;     //第$tkey列的第1行,列的标识符(a..z)
            // Add some data  //表头
          //  $tvalue=mb_convert_encoding($tvalue, "UTF-8","GBK");
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cell, $tvalue);  //设置第$row列的值(标题)
        }
        return $objPHPExcel;
    }
    //输出内容
    function _writeDatas($data,$objPHPExcel){
         //内容循环(数据库查询的返回值)           
        foreach($data as $key =>$value) {  
            $i = 1;
            foreach ($value as $mkey =>$mvalue){   //返回的类型是array([0]=>array());,所以此处要循环它的value,也就是里面的array
 
                $rows = $key+2; //开始是第二行
                $mrow = $this->cellArray[$i].$rows;   //第$i列的第$row行
             //   $mvalue=mb_convert_encoding($mvalue, "GBK","UTF-8");
              // print_r($mrow."--->".$mvalue);
 
                $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($mrow, $mvalue); 
                $i++;
            }
        }
        return $objPHPExcel;
    }
    function _write_comm($name,$objPHPExcel){
               // Rename sheet(左下角的标题)
       //$objPHPExcel->getActiveSheet()->setTitle($name);
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);   //默认显示
        return $objPHPExcel;
    }
 /*********************************导出数据结束****************************************************/  
 
 /*********************************读取数据开始****************************************************/
 
 /**
  * 使用方法,$insertSql:insert xx (x1,x2,x3,x4) value (
  */
  // function _comm_insert($objReader,$filePath,$insertSql,$sheet=2,$curRow=2,$riqi=TRUE){
    function _comm_insert($objPHPExcel,$insertSql,$curRow,$merge=FALSE,$mergeCol=&#39;B&#39;){
        $CI = &get_instance();
        $currentSheet = $objPHPExcel->getSheet();//得到指定的激活
        /**取得一共有多少列*/
        $allColumn = $currentSheet->getHighestColumn();  
        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow(); 
        $size=strlen($allColumn);//如果超出Z,则出现不执行下去
        $esql="";
 
        for($currentRow = $curRow;$currentRow<=$allRow;$currentRow++){
            $sql=$insertSql;
            if($size==2){
                $i=1;
                $currentColumn=&#39;A&#39;;
                while ($i <= 26) {
                    $address = $currentColumn.$currentRow;
                    $temp=$currentSheet->getCell($address)->getCalculatedValue();
                    $sql.=&#39;"&#39;.$temp.&#39;"&#39;.",";
                    $currentColumn++;
                    $i++;
                }
                for($currentColumn=&#39;AA&#39;;$currentColumn<=$allColumn;$currentColumn++){
                    $address = $currentColumn.$currentRow;
                    $sql.=&#39;"&#39;.$currentSheet->getCell($address)->getCalculatedValue().&#39;"&#39;.",";
                }
 
            }else{
                for($currentColumn=&#39;A&#39;;$currentColumn<=$allColumn;$currentColumn++){
                    if($merge){//如果是读取合并的值,则判断,如果此行的值为NULL,则把前面的tempName赋值给$temp;
                        if($currentColumn==$mergeCol){//这里先指定从B列的名字开始读取合并了的值。以后遇到不同的再调整。
                            $temp=$currentSheet->getCell($mergeCol.$currentRow)->getCalculatedValue();
                             if(empty($temp)){
                                $temp=$this->tempName;
                            }else{
                                $this->tempName=$temp;
                            }                           
                        }else{
                         $address = $currentColumn.$currentRow;//getValue()
                         $temp=$currentSheet->getCell($address)->getCalculatedValue();                           
                        }
                    }else{
                        $address = $currentColumn.$currentRow;//getValue()
                        $temp=$currentSheet->getCell($address)->getCalculatedValue();  
                    }
                    $sql=$sql.&#39;"&#39;.$temp.&#39;"&#39;.",";
                } 
            }
           $esql=rtrim($sql,",").&#39;)&#39;;
//echo($esql);
//return;
          $CI->db->simple_query($esql);
        }
   }
   /**
    * $filePath:读取文件的路径
    * $insertSql:拼写的SQL
    */
    function read_EXCEL2007($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
       $objs=$this->_get_PHPExcel($this->E2007,$filePath,$sheet,$insertSql,$riqi);
       $this->_comm_insert($objs["EXCEL"],$objs["SQL"],$curRow,$merge,$mergeCol);  
    }
    /**
     * 读取2003Excel
     */
     function read_2003Excel($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
       $objs=$this->_get_PHPExcel($this->E2003,$filePath,$sheet,$insertSql,$riqi);
       $this->_comm_insert($objs["EXCEL"],$objs["SQL"],$curRow,$merge,$mergeCol);    
     }
    /**
     * 读取CSV
     */
     function read_CSV($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){  
       $objs=$this->_get_PHPExcel($this->ECSV,$filePath,$sheet,$insertSql,$riqi,$mergeCol);
       $this->_comm_insert($objs["EXCEL"],$objs["SQL"],$curRow,$merge);
     }
     //--------------------------------读取工作薄信息开始
     /**
      * 读取Excel2007工作薄名称
      */
     function read_EXCEL2007_Sheets($filePath){
        return $this->_get_sheetnames($this->E2007,$filePath);
     }
 
    /**
     * 读取2003Excel工作薄名称
     */
     function read_2003Excel_Sheet($filePath){
       return $this->_get_sheetnames($this->E2003,$filePath);
     }
    /**
     * 读取CSV工作薄名称
     */
     function read_CSV_Sheet($filePath){
        return $this->_get_sheetnames($this->ECSV,$filePath);
     }
     //--------------------------------读取工作薄信息结束
     /**
      * 2012-1-14  --------------------------
      */
      //读取Reader流
      function _get_Reader($name){
        $reader=null;
        switch ($name) {
            case $this->E2003:
                $reader = new PHPExcel_Reader_Excel5();
                break;
            case $this->E2007:
                $reader = new PHPExcel_Reader_Excel2007();
                break;
            case $this->ECSV:
                $reader = new PHPExcel_Reader_CSV();
                break;
        }  
        return $reader;
      }
      //得到$objPHPExcel文件对象
     function _get_PHPExcel($name,$filePath,$sheet,$insertSql,$riqi){
        $reader=$this->_get_Reader($name);
        $PHPExcel= $this->_init_Excel($reader,$filePath,$sheet);
        if($riqi){ //如果不需要日期,则忽略.
            $insertSql=$insertSql.&#39;"&#39;.$reader->getSheetTitle().&#39;"&#39;.",";//第一个字段固定是日期2012-1-9           
        }  
        return array("EXCEL"=>$PHPExcel,"SQL"=>$insertSql);
     }
 
     //得到工作薄名称
     function _get_sheetnames($name,$filePath){
        $reader=$this->_get_Reader($name);
        $this->_init_Excel($reader,$filePath);
        return $reader->getAllSheets();
     }
     //加载文件
      function _init_Excel($objReader,$filePath,$sheet=&#39;&#39;){
        $objReader->setReadDataOnly(true);
        if(!empty($sheet)){
             $objReader->setSheetIndex($sheet);//读取第几个Sheet。
        }  
        return $objReader->load("$filePath");
      }
//-------------------------------2012-1-14
}
/*********************************读取数据结束****************************************************/

[PHP] code

------------------------导入操作------------------------
    /**
     *  $sql="INSERT INTO ".mymsg::WY_MMB." (dizhi,xingming) VALUES (";
     */
    //先上传再读取文件
    function upByFile($sql, $url, $curRow = 2, $RIQI = true,$merge = FALSE,$mergeCol=&#39;B&#39;)
    {
 
        $CI = &get_instance();
        $config[&#39;allowed_types&#39;] = &#39;*&#39;; //充许所有文件
        $config[&#39;upload_path&#39;] = IMPORT; // 只在文件的路径
        $CI->load->library(&#39;upload&#39;, $config);
 
        if ($CI->upload->do_upload()) { //默认名是:userfile
            $data = $CI->upload->data();
 
            $full_name = $data[&#39;full_path&#39;]; //得到保存后的路径
            $full_name = mb_convert_encoding($full_name, "GBK", "UTF-8");
            $sheet = $CI->input->post("sheet"); //读取第x列图表
            if (empty($sheet)) {
                $sheet = 0;
            }
 
            $CI->read_write->read_Facotry($full_name, $sql, $sheet, $curRow, $RIQI,$merge,$mergeCol); //执行插入命令
 
        }
 
     $this->alert_msg(mymsg::IMPORT_SUCCESS, site_url($url));
    }
 
------------------------------导出操作----------------------------------
   //导出指定的表字段
   public function show_export(){
    //-----数据库字段
    $field=implode(",",$this->input->post("listCheckBox_show"));//数据库字段
    //显示名称
    $titleArray=$this->input->post("listCheckBox_field");//显示的字段名称(字段Comment注解名,因为传进来的有些空数组,所以必须过滤)
    $title=array();
    foreach ($titleArray as $key => $value) {
        if (!empty($value)) {
            $title[]=$value;
        }
    }   
    //---数据库表名
    $table=$this->input->post("tableName");
    //--数据库表名称(Comment注释)
    $show_name=$this->input->post("tableComment");
    //--导出类型
    $type=$this->input->post("type");
 
    //--where 年月
    $y_month=$this->input->post("year_month");
    if(!empty($y_month)){
        $where["riqi"]=$y_month;
        $datas=$this->mcom_model->queryByWhereReField($field,$where,$table);
    }else{
        //--写出的数据
        $datas=$this->mcom_model->queryByField($field,$table);     
    }
 
    //---开始导出
    $this->read_write->write_Factory($title,$datas,$show_name,$type);
   }


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn